text
stringlengths
5
1.04M
/** * @file mean_split_impl.hpp * @author Yash Vadalia * @author Ryan Curtin * * Implementation of class(MeanSplit) to split a binary space partition tree. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_IMPL_HPP #define MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_IMPL_HPP #include "mean_split.hpp" namespace mlpack { namespace tree { template<typename BoundType, typename MatType> bool MeanSplit<BoundType, MatType>::SplitNode(const BoundType& bound, MatType& data, const size_t begin, const size_t count, SplitInfo& splitInfo) { double maxWidth = -1; splitInfo.splitDimension = data.n_rows; // Indicate invalid. // Find the split dimension. If the bound is tight, we only need to consult // the bound's width. if (bound::BoundTraits<BoundType>::HasTightBounds) { for (size_t d = 0; d < data.n_rows; d++) { const double width = bound[d].Width(); if (width > maxWidth) { maxWidth = width; splitInfo.splitDimension = d; } } } else { // We must individually calculate bounding boxes. math::Range* ranges = new math::Range[data.n_rows]; for (size_t i = begin; i < begin + count; ++i) { // Expand each dimension as necessary. for (size_t d = 0; d < data.n_rows; ++d) { const double val = data(d, i); if (val < ranges[d].Lo()) ranges[d].Lo() = val; if (val > ranges[d].Hi()) ranges[d].Hi() = val; } } // Now, which is the widest? for (size_t d = 0; d < data.n_rows; d++) { const double width = ranges[d].Width(); if (width > maxWidth) { maxWidth = width; splitInfo.splitDimension = d; } } delete[] ranges; } if (maxWidth == 0) // All these points are the same. We can't split. return false; // Split in the mean of that dimension. splitInfo.splitVal = 0.0; for (size_t i = begin; i < begin + count; ++i) splitInfo.splitVal += data(splitInfo.splitDimension, i); splitInfo.splitVal /= count; Log::Assert(splitInfo.splitVal >= bound[splitInfo.splitDimension].Lo()); Log::Assert(splitInfo.splitVal <= bound[splitInfo.splitDimension].Hi()); return true; } } // namespace tree } // namespace mlpack #endif
// Copyright (c) 2017-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/coinselection.h> #include <util.h> #include <utilmoneystr.h> // Descending order comparator struct { bool operator()(const OutputGroup& a, const OutputGroup& b) const { return a.effective_value > b.effective_value; } } descending; /* * This is the Branch and Bound Coin Selection algorithm designed by Murch. It searches for an input * set that can pay for the spending target and does not exceed the spending target by more than the * cost of creating and spending a change output. The algorithm uses a depth-first search on a binary * tree. In the binary tree, each node corresponds to the inclusion or the omission of a UTXO. UTXOs * are sorted by their effective values and the trees is explored deterministically per the inclusion * branch first. At each node, the algorithm checks whether the selection is within the target range. * While the selection has not reached the target range, more UTXOs are included. When a selection's * value exceeds the target range, the complete subtree deriving from this selection can be omitted. * At that point, the last included UTXO is deselected and the corresponding omission branch explored * instead. The search ends after the complete tree has been searched or after a limited number of tries. * * The search continues to search for better solutions after one solution has been found. The best * solution is chosen by minimizing the waste metric. The waste metric is defined as the cost to * spend the current inputs at the given fee rate minus the long term expected cost to spend the * inputs, plus the amount the selection exceeds the spending target: * * waste = selectionTotal - target + inputs × (currentFeeRate - longTermFeeRate) * * The algorithm uses two additional optimizations. A lookahead keeps track of the total value of * the unexplored UTXOs. A subtree is not explored if the lookahead indicates that the target range * cannot be reached. Further, it is unnecessary to test equivalent combinations. This allows us * to skip testing the inclusion of UTXOs that match the effective value and waste of an omitted * predecessor. * * The Branch and Bound algorithm is described in detail in Murch's Master Thesis: * https://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf * * @param const std::vector<CInputCoin>& utxo_pool The set of UTXOs that we are choosing from. * These UTXOs will be sorted in descending order by effective value and the CInputCoins' * values are their effective values. * @param const CAmount& target_value This is the value that we want to select. It is the lower * bound of the range. * @param const CAmount& cost_of_change This is the cost of creating and spending a change output. * This plus target_value is the upper bound of the range. * @param std::set<CInputCoin>& out_set -> This is an output parameter for the set of CInputCoins * that have been selected. * @param CAmount& value_ret -> This is an output parameter for the total value of the CInputCoins * that were selected. * @param CAmount not_input_fees -> The fees that need to be paid for the outputs and fixed size * overhead (version, locktime, marker and flag) */ static const size_t TOTAL_TRIES = 100000; bool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees) { out_set.clear(); CAmount curr_value = 0; std::vector<bool> curr_selection; // select the utxo at this index curr_selection.reserve(utxo_pool.size()); CAmount actual_target = not_input_fees + target_value; // Calculate curr_available_value CAmount curr_available_value = 0; for (const OutputGroup& utxo : utxo_pool) { // Assert that this utxo is not negative. It should never be negative, effective value calculation should have removed it assert(utxo.effective_value > 0); curr_available_value += utxo.effective_value; } if (curr_available_value < actual_target) { return false; } // Sort the utxo_pool std::sort(utxo_pool.begin(), utxo_pool.end(), descending); CAmount curr_waste = 0; std::vector<bool> best_selection; CAmount best_waste = MAX_MONEY; // Depth First search loop for choosing the UTXOs for (size_t i = 0; i < TOTAL_TRIES; ++i) { // Conditions for starting a backtrack bool backtrack = false; if (curr_value + curr_available_value < actual_target || // Cannot possibly reach target with the amount remaining in the curr_available_value. curr_value > actual_target + cost_of_change || // Selected value is out of range, go back and try other branch (curr_waste > best_waste && (utxo_pool.at(0).fee - utxo_pool.at(0).long_term_fee) > 0)) { // Don't select things which we know will be more wasteful if the waste is increasing backtrack = true; } else if (curr_value >= actual_target) { // Selected value is within range curr_waste += (curr_value - actual_target); // This is the excess value which is added to the waste for the below comparison // Adding another UTXO after this check could bring the waste down if the long term fee is higher than the current fee. // However we are not going to explore that because this optimization for the waste is only done when we have hit our target // value. Adding any more UTXOs will be just burning the UTXO; it will go entirely to fees. Thus we aren't going to // explore any more UTXOs to avoid burning money like that. if (curr_waste <= best_waste) { best_selection = curr_selection; best_selection.resize(utxo_pool.size()); best_waste = curr_waste; } curr_waste -= (curr_value - actual_target); // Remove the excess value as we will be selecting different coins now backtrack = true; } // Backtracking, moving backwards if (backtrack) { // Walk backwards to find the last included UTXO that still needs to have its omission branch traversed. while (!curr_selection.empty() && !curr_selection.back()) { curr_selection.pop_back(); curr_available_value += utxo_pool.at(curr_selection.size()).effective_value; } if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched break; } // Output was included on previous iterations, try excluding now. curr_selection.back() = false; OutputGroup& utxo = utxo_pool.at(curr_selection.size() - 1); curr_value -= utxo.effective_value; curr_waste -= utxo.fee - utxo.long_term_fee; } else { // Moving forwards, continuing down this branch OutputGroup& utxo = utxo_pool.at(curr_selection.size()); // Remove this utxo from the curr_available_value utxo amount curr_available_value -= utxo.effective_value; // Avoid searching a branch if the previous UTXO has the same value and same waste and was excluded. Since the ratio of fee to // long term fee is the same, we only need to check if one of those values match in order to know that the waste is the same. if (!curr_selection.empty() && !curr_selection.back() && utxo.effective_value == utxo_pool.at(curr_selection.size() - 1).effective_value && utxo.fee == utxo_pool.at(curr_selection.size() - 1).fee) { curr_selection.push_back(false); } else { // Inclusion branch first (Largest First Exploration) curr_selection.push_back(true); curr_value += utxo.effective_value; curr_waste += utxo.fee - utxo.long_term_fee; } } } // Check for solution if (best_selection.empty()) { return false; } // Set output set value_ret = 0; for (size_t i = 0; i < best_selection.size(); ++i) { if (best_selection.at(i)) { util::insert(out_set, utxo_pool.at(i).m_outputs); value_ret += utxo_pool.at(i).m_value; } } return true; } // Dash //static void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue, // std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000) static void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue, std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000) // { std::vector<char> vfIncluded; vfBest.assign(groups.size(), true); nBest = nTotalLower; FastRandomContext insecure_rand; for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(groups.size(), false); CAmount nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < groups.size(); i++) { // Dash //-//if (fUseInstantSend && nTotal + vValue[i].first > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN) { //-// continue; //-//} // //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng is fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i]) { nTotal += groups[i].m_value; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= groups[i].m_value; vfIncluded[i] = false; } } } } } } bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) { setCoinsRet.clear(); nValueRet = 0; // List of values less than target boost::optional<OutputGroup> lowest_larger; std::vector<OutputGroup> applicable_groups; CAmount nTotalLower = 0; random_shuffle(groups.begin(), groups.end(), GetRandInt); for (const OutputGroup& group : groups) { if (group.m_value == nTargetValue) { util::insert(setCoinsRet, group.m_outputs); nValueRet += group.m_value; return true; } else if (group.m_value < nTargetValue + MIN_CHANGE) { applicable_groups.push_back(group); nTotalLower += group.m_value; } else if (!lowest_larger || group.m_value < lowest_larger->m_value) { lowest_larger = group; } } if (nTotalLower == nTargetValue) { for (const auto& group : applicable_groups) { util::insert(setCoinsRet, group.m_outputs); nValueRet += group.m_value; } return true; } if (nTotalLower < nTargetValue) { if (!lowest_larger) return false; util::insert(setCoinsRet, lowest_larger->m_outputs); nValueRet += lowest_larger->m_value; return true; } // Solve subset sum by stochastic approximation std::sort(applicable_groups.begin(), applicable_groups.end(), descending); std::vector<char> vfBest; CAmount nBest; // Dash //ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue, vfBest, nBest); //if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) { // ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest); //} ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue, vfBest, nBest); if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) { ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest); } // // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (lowest_larger && ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || lowest_larger->m_value <= nBest)) { util::insert(setCoinsRet, lowest_larger->m_outputs); nValueRet += lowest_larger->m_value; } else { for (unsigned int i = 0; i < applicable_groups.size(); i++) { if (vfBest[i]) { util::insert(setCoinsRet, applicable_groups[i].m_outputs); nValueRet += applicable_groups[i].m_value; } } if (LogAcceptCategory(BCLog::SELECTCOINS)) { LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: "); /* Continued */ for (unsigned int i = 0; i < applicable_groups.size(); i++) { if (vfBest[i]) { LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(applicable_groups[i].m_value)); /* Continued */ } } LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest)); } } return true; } /****************************************************************************** OutputGroup ******************************************************************************/ void OutputGroup::Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants) { m_outputs.push_back(output); m_from_me &= from_me; m_value += output.effective_value; m_depth = std::min(m_depth, depth); // ancestors here express the number of ancestors the new coin will end up having, which is // the sum, rather than the max; this will overestimate in the cases where multiple inputs // have common ancestors m_ancestors += ancestors; // descendants is the count as seen from the top ancestor, not the descendants as seen from the // coin itself; thus, this value is counted as the max, not the sum m_descendants = std::max(m_descendants, descendants); effective_value = m_value; } std::vector<CInputCoin>::iterator OutputGroup::Discard(const CInputCoin& output) { auto it = m_outputs.begin(); while (it != m_outputs.end() && it->outpoint != output.outpoint) ++it; if (it == m_outputs.end()) return it; m_value -= output.effective_value; effective_value -= output.effective_value; return m_outputs.erase(it); } bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const { return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs) && m_ancestors <= eligibility_filter.max_ancestors && m_descendants <= eligibility_filter.max_descendants; }
/* * @Date: 2021-05-06 10:51:55 * @Author: Mengsen Wang * @LastEditors: Mengsen Wang * @LastEditTime: 2021-05-06 10:56:43 */ #include <algorithm> #include <cassert> #include <vector> using namespace std; int rob(vector<int> &nums) { int size = nums.size(); if (size == 1) { return nums[0]; } int first = nums[0], second = max(nums[0], nums[1]); for (int i = 2; i < size; i++) { int temp = second; second = max(first + nums[i], second); first = temp; } return second; } int delete_and_earn(vector<int> &nums) { int n = nums.size(); int ans = 0; sort(nums.begin(), nums.end()); vector<int> sum = {nums[0]}; for (int i = 1; i < n; ++i) { int val = nums[i]; if (val == nums[i - 1]) { sum.back() += val; } else if (val == nums[i - 1] + 1) { sum.push_back(val); } else { ans += rob(sum); sum = {val}; } } ans += rob(sum); return ans; } int main() { { vector<int> nums{3, 4, 2}; assert(delete_and_earn(nums) == 6); } { vector<int> nums{2, 2, 3, 3, 3, 4}; assert(delete_and_earn(nums) == 9); } return 0; }
/* Copyright 2003-2008 Joaquin M Lopez Munoz. * 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) * * See http://www.boost.org/libs/multi_index for library home page. */ #ifndef BOOST_MULTI_INDEX_SAFE_MODE_ERRORS_HPP #define BOOST_MULTI_INDEX_SAFE_MODE_ERRORS_HPP #if defined(_MSC_VER)&&(_MSC_VER>=1200) #pragma once #endif namespace boost{ namespace multi_index{ namespace safe_mode{ /* Error codes for Boost.MultiIndex safe mode. These go in a separate * header so that the user can include it when redefining * BOOST_MULTI_INDEX_SAFE_MODE_ASSERT prior to the inclusion of * any other header of Boost.MultiIndex. */ enum error_code { invalid_iterator=0, not_dereferenceable_iterator, not_incrementable_iterator, not_decrementable_iterator, not_owner, not_same_owner, invalid_range, inside_range, out_of_bounds, same_container }; } /* namespace multi_index::safe_mode */ } /* namespace multi_index */ } /* namespace boost */ #endif
// // posix/descriptor_base.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #ifndef ASIO_POSIX_DESCRIPTOR_BASE_HPP #define ASIO_POSIX_DESCRIPTOR_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "../detail/config.hpp" #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ || defined(GENERATING_DOCUMENTATION) #include "../detail/io_control.hpp" #include "../detail/socket_option.hpp" #include "../detail/push_options.hpp" namespace asio { namespace posix { /// The descriptor_base class is used as a base for the basic_stream_descriptor /// class template so that we have a common place to define the associated /// IO control commands. class descriptor_base { public: /// (Deprecated: Use non_blocking().) IO control command to set the blocking /// mode of the descriptor. /** * Implements the FIONBIO IO control command. * * @par Example * @code * asio::posix::stream_descriptor descriptor(io_service); * ... * asio::descriptor_base::non_blocking_io command(true); * descriptor.io_control(command); * @endcode * * @par Concepts: * IoControlCommand. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined non_blocking_io; #else typedef asio::detail::io_control::non_blocking_io non_blocking_io; #endif /// IO control command to get the amount of data that can be read without /// blocking. /** * Implements the FIONREAD IO control command. * * @par Example * @code * asio::posix::stream_descriptor descriptor(io_service); * ... * asio::descriptor_base::bytes_readable command(true); * descriptor.io_control(command); * std::size_t bytes_readable = command.get(); * @endcode * * @par Concepts: * IoControlCommand. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined bytes_readable; #else typedef asio::detail::io_control::bytes_readable bytes_readable; #endif protected: /// Protected destructor to prevent deletion through this type. ~descriptor_base() { } }; } // namespace posix } // namespace asio #include "../detail/pop_options.hpp" #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_POSIX_DESCRIPTOR_BASE_HPP
// // branch-and-bound.cpp // SofaBounds Version 1.0 // // This source file is part of the SofaBounds software package // SofaBounds is a program that proves upper bounds in the moving sofa problem, // as described in the paper "Improved upper bounds in the moving sofa problem", // by Yoav Kallus and Dan Romik // // For more information go to the project web page: *** TODO: add URL *** // // Copyright © 2017 Yoav Kallus and Dan Romik // #include <queue> #include <vector> #include "sofa-bounds.hpp" int branch_and_bound(struct bb_thread_params *my_bb_thread_params) { unsigned int i,j; std::priority_queue<struct box, std::vector<struct box>, struct CompareBoxes> boxqueue; struct box currentbox; struct box newbox[2]; ExactRational newbound[2]; ExactRational a,b,c,d; ExactRational bestyet; //initialize lower bound bestyet = my_bb_thread_params->lower_bound; //initailize the queue newbox[0] = a_priori_bounds(*my_bb_thread_params,my_bb_thread_params->num_intermediate/2); newbox[0].upper_bound_on_max_in_box = area_of_union(newbox[0],*my_bb_thread_params); boxqueue.push(newbox[0]); //initialize interation counter and vector recording the lower bound witness my_bb_thread_params->iterations = 0UL; my_bb_thread_params->lower_bound_witness.resize(2*my_bb_thread_params->num_intermediate); //main branch-and-bound loop while (!boxqueue.empty() && !my_bb_thread_params->stop_flag) { my_bb_thread_params->iterations++; //pop top box from the stack, and declare its upper bound the universal upper bound currentbox = boxqueue.top(); boxqueue.pop(); my_bb_thread_params->upper_bound = currentbox.upper_bound_on_max_in_box; //if requested, construct polygons corresponding to the current best lower bound and upper bound //and print their vertex coordinates to a file if (my_bb_thread_params->report_flag) { //upper bound polygon //first line is number of vertices x 2 polygon_of_union(currentbox,*my_bb_thread_params,&my_bb_thread_params->upper_bound_polygon); std::ofstream fpoly(my_bb_thread_params->fpoly_name); fpoly << my_bb_thread_params->upper_bound_polygon.size() << std::endl; for (i=0; i<my_bb_thread_params->upper_bound_polygon.size();i++) //each subsequent line alternates between x and y coordinates of successive vertices fpoly << rat_str(my_bb_thread_params->upper_bound_polygon[i]) << std::endl; //lower bound polygon fpoly << my_bb_thread_params->lower_bound_polygon.size() << std::endl; for (i=0; i<my_bb_thread_params->lower_bound_polygon.size();i++) fpoly << rat_str(my_bb_thread_params->lower_bound_polygon[i]) << std::endl; fpoly.close(); my_bb_thread_params->report_flag = false; } //if local lower bound on max in current box is better than current global bound, update global bound a = lower_bound_on_max_in_box(currentbox,*my_bb_thread_params); if (a > bestyet) { bestyet = a; my_bb_thread_params->lower_bound = bestyet; newbox[0] = currentbox; //also record the witness variables and the associated polygon for (i=0;i<2*my_bb_thread_params->num_intermediate;i++) { newbox[0].coord_bound_intervals[i] = midpoint_of_interval(currentbox.coord_bound_intervals[i]); my_bb_thread_params->lower_bound_witness[i] = newbox[0].coord_bound_intervals[i].left; } polygon_of_union(newbox[0],*my_bb_thread_params,&my_bb_thread_params->lower_bound_polygon); } if (my_bb_thread_params->reporteverysec_on) { std::chrono::high_resolution_clock::time_point t_end = std::chrono::high_resolution_clock::now(); //long ms = std::chrono::duration_cast<std::chrono::milliseconds>(t_end-my_bb_thread_params->reporteverysec_last).count(); //if (ms >= 1000*my_bb_thread_params->reporteverysec_inc) { if (t_end - my_bb_thread_params->reporteverysec_last >= std::chrono::seconds(my_bb_thread_params->reporteverysec_inc)) { std::cout << std::endl; short_inspect(my_bb_thread_params); std::cout << std::flush; //my_bb_thread_params->reporteverysec_last = t_end; while (t_end - my_bb_thread_params->reporteverysec_last >= std::chrono::seconds(my_bb_thread_params->reporteverysec_inc)) my_bb_thread_params->reporteverysec_last += std::chrono::seconds(my_bb_thread_params->reporteverysec_inc); } } if (my_bb_thread_params->reporteveryiter_on) { if (my_bb_thread_params->iterations - my_bb_thread_params->reporteveryiter_last >= my_bb_thread_params->reporteveryiter_inc) { std::cout << std::endl; short_inspect(my_bb_thread_params); std::cout << std::flush; my_bb_thread_params->reporteveryiter_last = (my_bb_thread_params->iterations/my_bb_thread_params->reporteveryiter_inc)*my_bb_thread_params->reporteveryiter_inc; } } if (my_bb_thread_params->reporteveryjump_on) { if (my_bb_thread_params->reporteveryjump_last - CGAL::to_double(my_bb_thread_params->upper_bound) >= my_bb_thread_params->reporteveryjump_inc) { std::cout << std::endl; short_inspect(my_bb_thread_params); std::cout << std::flush; my_bb_thread_params->reporteveryjump_last = round(CGAL::to_double(my_bb_thread_params->upper_bound)/my_bb_thread_params->reporteveryjump_inc)*my_bb_thread_params->reporteveryjump_inc; } } //uncomment for verbose output //fprintf(stdout,"%12lu (%6d, %12lu): %18.15lf %18.15lf %18.15lf\n",iter,currentbox.depth,boxqueue.size(),CGAL::to_double(a),CGAL::to_double(currentbox.upper_bound_on_max_in_box),CGAL::to_double(bestyet)); //split the box into two descendents j = index_of_coordinate_to_split(currentbox,*my_bb_thread_params); newbox[0] = currentbox; newbox[1] = currentbox; split_interval(currentbox.coord_bound_intervals[j],&(newbox[0].coord_bound_intervals[j]),&(newbox[1].coord_bound_intervals[j])); //calculate the upper bound for the descendents for (i=0;i<2;i++) { newbound[i] = area_of_union(newbox[i],*my_bb_thread_params); } for (i=0;i<2;i++) { //if descendent cannot be discarded if ( (newbound[i] < 0) || (newbound[i] > bestyet) ) { //update its depth and upper bound and push it to the queue newbox[i].depth++; newbox[i].upper_bound_on_max_in_box = newbound[i]; boxqueue.push(newbox[i]); } //if it can be discarded, just do nothing } } //this point should only be reach if the initial "lower bound" was greater than the actual supremum, //otherwise the loop should continue ad infinitum giving progressively better and better bounds. std::cerr << "stopped after " << my_bb_thread_params->iterations << " iterations" << std::endl; return 0; }
#include "../../includes/linux/InotifyService.h" InotifyService::InotifyService(std::shared_ptr<EventQueue> queue, std::string path): mEventLoop(NULL), mQueue(queue), mTree(NULL) { mInotifyInstance = inotify_init(); if (mInotifyInstance == -1) { return; } mTree = new InotifyTree(mInotifyInstance, path); if (!mTree->isRootAlive()) { delete mTree; mTree = NULL; mEventLoop = NULL; } else { mEventLoop = new InotifyEventLoop( mInotifyInstance, this ); } } InotifyService::~InotifyService() { if (mEventLoop != NULL) { delete mEventLoop; } if (mTree != NULL) { delete mTree; } close(mInotifyInstance); } void InotifyService::create(int wd, std::string name) { dispatch(CREATED, wd, name); } void InotifyService::dispatch(EventType action, int wd, std::string name) { std::string path; if (!mTree->getPath(path, wd)) { return; } mQueue->enqueue(action, path, name); } void InotifyService::dispatchRename(int fromWd, std::string fromName, int toWd, std::string toName) { std::string fromPath, toPath; if (!mTree->getPath(fromPath, fromWd) || !mTree->getPath(toPath, toWd)) { return; } mQueue->enqueue(RENAMED, fromPath, fromName, toPath, toName); } std::string InotifyService::getError() { if (!isWatching()) { return "Service shutdown unexpectedly"; } if (mTree->hasErrored()) { return mTree->getError(); } return ""; } bool InotifyService::hasErrored() { return !isWatching() || (mTree == NULL ? false : mTree->hasErrored()); } bool InotifyService::isWatching() { if (mTree == NULL || mEventLoop == NULL) { return false; } return mTree->isRootAlive() && mEventLoop->isLooping(); } void InotifyService::modify(int wd, std::string name) { dispatch(MODIFIED, wd, name); } void InotifyService::remove(int wd, std::string name) { dispatch(DELETED, wd, name); } void InotifyService::rename(int fromWd, std::string fromName, int toWd, std::string toName) { dispatchRename(fromWd, fromName, toWd, toName); } void InotifyService::createDirectory(int wd, std::string name) { if (!mTree->nodeExists(wd)) { return; } mTree->addDirectory(wd, name); dispatch(CREATED, wd, name); } void InotifyService::removeDirectory(int wd) { mTree->removeDirectory(wd); } void InotifyService::renameDirectory(int fromWd, std::string fromName, int toWd, std::string toName) { if (!mTree->nodeExists(fromWd) || !mTree->nodeExists(toWd)) { return; } mTree->renameDirectory(fromWd, fromName, toWd, toName); dispatchRename(fromWd, fromName, toWd, toName); }
/** * @copyright Copyright 2016 The J-PET Framework Authors. 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 find a copy of the License in the LICENCE file. * * 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 HitFinderTools.h */ #include "HitFinderTools.h" using namespace std; vector<JPetHit> HitFinderTools::createHits(JPetStatistics& stats, const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow, const std::map<int, std::vector<double>> velMap) { vector<JPetHit> hits; for (auto scintillator : allSignalsInTimeWindow) { auto sideA = scintillator.second.first; auto sideB = scintillator.second.second; if (sideA.size() > 0 && sideB.size() > 0) { std::sort(sideA.begin(), sideA.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) { return h1.getTime() < h2.getTime(); }); std::sort(sideB.begin(), sideB.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) { return h1.getTime() < h2.getTime(); }); for (auto signalA : sideA) { for (auto signalB : sideB) { if ((signalB.getTime() - signalA.getTime()) > timeDifferenceWindow) break; if (fabs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow) { //Creating hit for successfully matched pair of Phys singlas //Setting meaningless parameters of Energy, Position, quality JPetHit hit; hit.setSignalA(signalA); hit.setSignalB(signalB); hit.setTime((signalA.getTime()+signalB.getTime())/2.0); hit.setQualityOfTime(-1.0); hit.setTimeDiff(signalA.getTime()-signalB.getTime()); hit.setQualityOfTimeDiff(-1.0); hit.setEnergy(-1.0); hit.setQualityOfEnergy(-1.0); hit.setScintillator(signalA.getPM().getScin()); hit.setBarrelSlot(signalA.getPM().getBarrelSlot()); hit.setPosX(hit.getBarrelSlot().getLayer().getRadius() *cos(hit.getBarrelSlot().getTheta())); hit.setPosY(hit.getBarrelSlot().getLayer().getRadius() *sin(hit.getBarrelSlot().getTheta())); auto search = velMap.find(hit.getBarrelSlot().getID()); if(search != velMap.end()){ double vel = search->second.at(0); double position = vel*hit.getTimeDiff()/2000; hit.setPosZ(position); }else{ hit.setPosZ(-1000000.0); } hits.push_back(hit); stats.getHisto2D("time_diff_per_scin") .Fill(hit.getTimeDiff(), (float) (hit.getScintillator().getID())); stats.getHisto2D("hit_pos_per_scin") .Fill(hit.getPosZ(), (float) (hit.getScintillator().getID())); } } } } } return hits; }
// Copyright 2019 The Fuchsia 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 <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fdio/directory.h> #include <lib/fdio/fd.h> #include <lib/fdio/fdio.h> #include <lib/fdio/limits.h> #include <lib/vfs/cpp/internal/file.h> #include <lib/vfs/cpp/node_kind.h> #include <unistd.h> #include <zircon/processargs.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "gtest/gtest.h" namespace { class TestFile : public vfs::internal::File { public: explicit TestFile(std::vector<uint8_t>* buffer) : buffer_(buffer) {} ~TestFile() override = default; zx_status_t ReadAt(uint64_t count, uint64_t offset, std::vector<uint8_t>* out_data) override { if (offset >= buffer_->size()) { return ZX_OK; } size_t actual = std::min(count, buffer_->size() - offset); out_data->resize(actual); std::copy_n(buffer_->begin() + offset, actual, out_data->begin()); return ZX_OK; } zx_status_t WriteAt(std::vector<uint8_t> data, uint64_t offset, uint64_t* out_actual) override { if (offset >= buffer_->size()) { *out_actual = 0u; return ZX_OK; } size_t actual = std::min(data.size(), buffer_->size() - offset); std::copy_n(data.begin(), actual, buffer_->begin() + offset); *out_actual = actual; return ZX_OK; } uint64_t GetLength() override { return buffer_->size(); } size_t GetCapacity() override { return buffer_->size(); } protected: vfs::NodeKind::Type GetKind() const override { vfs::NodeKind::Type kind = File::GetKind() | vfs::NodeKind::kReadable | vfs::NodeKind::kWritable; return kind; } private: std::vector<uint8_t>* buffer_; }; int OpenAsFD(vfs::internal::Node* node, async_dispatcher_t* dispatcher) { zx::channel local, remote; EXPECT_EQ(ZX_OK, zx::channel::create(0, &local, &remote)); EXPECT_EQ(ZX_OK, node->Serve(fuchsia::io::OPEN_RIGHT_READABLE | fuchsia::io::OPEN_RIGHT_WRITABLE, std::move(remote), dispatcher)); int fd = -1; EXPECT_EQ(ZX_OK, fdio_fd_create(local.release(), &fd)); return fd; } TEST(File, Control) { std::vector<uint8_t> store(12u); TestFile file(&store); async::Loop loop(&kAsyncLoopConfigNoAttachToCurrentThread); loop.StartThread("vfs test thread"); int fd = OpenAsFD(&file, loop.dispatcher()); ASSERT_LE(0, fd); ASSERT_EQ(4, write(fd, "abcd", 4)); EXPECT_EQ(0, strcmp("abcd", reinterpret_cast<char*>(store.data()))); ASSERT_EQ(5, write(fd, "exxxi", 5)); EXPECT_EQ(0, strcmp("abcdexxxi", reinterpret_cast<char*>(store.data()))); ASSERT_EQ(3, pwrite(fd, "fgh", 3, 5)); EXPECT_EQ(0, strcmp("abcdefghi", reinterpret_cast<char*>(store.data()))); char buffer[1024]; memset(buffer, 0, sizeof(buffer)); ASSERT_EQ(7, pread(fd, buffer, 7, 1)); EXPECT_EQ(0, strcmp("bcdefgh", buffer)); ASSERT_EQ(3, write(fd, "jklmn", 5)); EXPECT_EQ('l', store[store.size() - 1]); memset(buffer, 0, sizeof(buffer)); ASSERT_EQ(4, pread(fd, buffer, 10, 8)); EXPECT_EQ(0, strcmp("ijkl", buffer)); ASSERT_GE(0, close(fd)); } TEST(File, Clone) { std::vector<uint8_t> store(12u); TestFile file(&store); async::Loop loop(&kAsyncLoopConfigNoAttachToCurrentThread); loop.StartThread("vfs test thread"); int fd = OpenAsFD(&file, loop.dispatcher()); ASSERT_LE(0, fd); ASSERT_EQ(4, write(fd, "abcd", 4)); EXPECT_EQ(0, strcmp("abcd", reinterpret_cast<char*>(store.data()))); zx_handle_t handle = ZX_HANDLE_INVALID; ASSERT_EQ(ZX_OK, fdio_fd_clone(fd, &handle)); int cloned = -1; EXPECT_EQ(ZX_OK, fdio_fd_create(handle, &cloned)); ASSERT_LE(0, cloned); ASSERT_EQ(3, write(cloned, "xyz", 3)); EXPECT_EQ(0, strcmp("xyzd", reinterpret_cast<char*>(store.data()))); ASSERT_GE(0, close(fd)); ASSERT_GE(0, close(cloned)); } } // namespace
/* * Copyright (c) 2015 Intel Corporation * * 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 (including the next * paragraph) 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. */ /** * \file lower_buffer_access.cpp * * Helper for IR lowering pass to replace dereferences of buffer object based * shader variables with intrinsic function calls. * * This helper is used by lowering passes for UBOs, SSBOs and compute shader * shared variables. */ #include "lower_buffer_access.h" #include "ir_builder.h" #include "main/macros.h" #include "util/list.h" #include "glsl_parser_extras.h" #include "linker.h" using namespace ir_builder; namespace lower_buffer_access { static inline int writemask_for_size(unsigned n) { return ((1 << n) - 1); } /** * Takes a deref and recursively calls itself to break the deref down to the * point that the reads or writes generated are contiguous scalars or vectors. */ void lower_buffer_access::emit_access(void *mem_ctx, bool is_write, ir_dereference *deref, ir_variable *base_offset, unsigned int deref_offset, bool row_major, const glsl_type *matrix_type, enum glsl_interface_packing packing, unsigned int write_mask) { if (deref->type->is_record()) { unsigned int field_offset = 0; for (unsigned i = 0; i < deref->type->length; i++) { const struct glsl_struct_field *field = &deref->type->fields.structure[i]; ir_dereference *field_deref = new(mem_ctx) ir_dereference_record(deref->clone(mem_ctx, NULL), field->name); unsigned field_align; if (packing == GLSL_INTERFACE_PACKING_STD430) field_align = field->type->std430_base_alignment(row_major); else field_align = field->type->std140_base_alignment(row_major); field_offset = glsl_align(field_offset, field_align); emit_access(mem_ctx, is_write, field_deref, base_offset, deref_offset + field_offset, row_major, NULL, packing, writemask_for_size(field_deref->type->vector_elements)); if (packing == GLSL_INTERFACE_PACKING_STD430) field_offset += field->type->std430_size(row_major); else field_offset += field->type->std140_size(row_major); } return; } if (deref->type->is_array()) { unsigned array_stride = packing == GLSL_INTERFACE_PACKING_STD430 ? deref->type->fields.array->std430_array_stride(row_major) : glsl_align(deref->type->fields.array->std140_size(row_major), 16); for (unsigned i = 0; i < deref->type->length; i++) { ir_constant *element = new(mem_ctx) ir_constant(i); ir_dereference *element_deref = new(mem_ctx) ir_dereference_array(deref->clone(mem_ctx, NULL), element); emit_access(mem_ctx, is_write, element_deref, base_offset, deref_offset + i * array_stride, row_major, NULL, packing, writemask_for_size(element_deref->type->vector_elements)); } return; } if (deref->type->is_matrix()) { for (unsigned i = 0; i < deref->type->matrix_columns; i++) { ir_constant *col = new(mem_ctx) ir_constant(i); ir_dereference *col_deref = new(mem_ctx) ir_dereference_array(deref->clone(mem_ctx, NULL), col); /* For a row-major matrix, the next column starts at the next * element. Otherwise it is offset by the matrix stride. */ const unsigned size_mul = row_major ? (deref->type->is_double() ? 8 : 4) : link_calculate_matrix_stride(deref->type, row_major, packing); emit_access(mem_ctx, is_write, col_deref, base_offset, deref_offset + i * size_mul, row_major, deref->type, packing, writemask_for_size(col_deref->type->vector_elements)); } return; } assert(deref->type->is_scalar() || deref->type->is_vector()); if (!row_major) { ir_rvalue *offset = add(base_offset, new(mem_ctx) ir_constant(deref_offset)); unsigned mask = is_write ? write_mask : (1 << deref->type->vector_elements) - 1; insert_buffer_access(mem_ctx, deref, deref->type, offset, mask, -1); } else { /* We're dereffing a column out of a row-major matrix, so we * gather the vector from each stored row. */ assert(deref->type->is_float() || deref->type->is_double()); assert(matrix_type != NULL); const unsigned matrix_stride = link_calculate_matrix_stride(matrix_type, row_major, packing); const glsl_type *deref_type = deref->type->get_scalar_type(); for (unsigned i = 0; i < deref->type->vector_elements; i++) { ir_rvalue *chan_offset = add(base_offset, new(mem_ctx) ir_constant(deref_offset + i * matrix_stride)); if (!is_write || ((1U << i) & write_mask)) insert_buffer_access(mem_ctx, deref, deref_type, chan_offset, (1U << i), i); } } } /** * Determine if a thing being dereferenced is row-major * * There is some trickery here. * * If the thing being dereferenced is a member of uniform block \b without an * instance name, then the name of the \c ir_variable is the field name of an * interface type. If this field is row-major, then the thing referenced is * row-major. * * If the thing being dereferenced is a member of uniform block \b with an * instance name, then the last dereference in the tree will be an * \c ir_dereference_record. If that record field is row-major, then the * thing referenced is row-major. */ bool lower_buffer_access::is_dereferenced_thing_row_major(const ir_rvalue *deref) { bool matrix = false; const ir_rvalue *ir = deref; while (true) { matrix = matrix || ir->type->without_array()->is_matrix(); switch (ir->ir_type) { case ir_type_dereference_array: { const ir_dereference_array *const array_deref = (const ir_dereference_array *) ir; ir = array_deref->array; break; } case ir_type_dereference_record: { const ir_dereference_record *const record_deref = (const ir_dereference_record *) ir; ir = record_deref->record; const int idx = record_deref->field_idx; assert(idx >= 0); const enum glsl_matrix_layout matrix_layout = glsl_matrix_layout(ir->type->fields.structure[idx].matrix_layout); switch (matrix_layout) { case GLSL_MATRIX_LAYOUT_INHERITED: break; case GLSL_MATRIX_LAYOUT_COLUMN_MAJOR: return false; case GLSL_MATRIX_LAYOUT_ROW_MAJOR: return matrix || deref->type->without_array()->is_record(); } break; } case ir_type_dereference_variable: { const ir_dereference_variable *const var_deref = (const ir_dereference_variable *) ir; const enum glsl_matrix_layout matrix_layout = glsl_matrix_layout(var_deref->var->data.matrix_layout); switch (matrix_layout) { case GLSL_MATRIX_LAYOUT_INHERITED: { /* For interface block matrix variables we handle inherited * layouts at HIR generation time, but we don't do that for shared * variables, which are always column-major */ MAYBE_UNUSED ir_variable *var = deref->variable_referenced(); assert((var->is_in_buffer_block() && !matrix) || var->data.mode == ir_var_shader_shared); return false; } case GLSL_MATRIX_LAYOUT_COLUMN_MAJOR: return false; case GLSL_MATRIX_LAYOUT_ROW_MAJOR: return matrix || deref->type->without_array()->is_record(); } unreachable("invalid matrix layout"); break; } default: return false; } } /* The tree must have ended with a dereference that wasn't an * ir_dereference_variable. That is invalid, and it should be impossible. */ unreachable("invalid dereference tree"); return false; } /** * This function initializes various values that will be used later by * emit_access when actually emitting loads or stores. * * Note: const_offset is an input as well as an output, clients must * initialize it to the offset of the variable in the underlying block, and * this function will adjust it by adding the constant offset of the member * being accessed into that variable. */ void lower_buffer_access::setup_buffer_access(void *mem_ctx, ir_rvalue *deref, ir_rvalue **offset, unsigned *const_offset, bool *row_major, const glsl_type **matrix_type, const glsl_struct_field **struct_field, enum glsl_interface_packing packing) { *offset = new(mem_ctx) ir_constant(0u); *row_major = is_dereferenced_thing_row_major(deref); *matrix_type = NULL; /* Calculate the offset to the start of the region of the UBO * dereferenced by *rvalue. This may be a variable offset if an * array dereference has a variable index. */ while (deref) { switch (deref->ir_type) { case ir_type_dereference_variable: { deref = NULL; break; } case ir_type_dereference_array: { ir_dereference_array *deref_array = (ir_dereference_array *) deref; unsigned array_stride; if (deref_array->array->type->is_vector()) { /* We get this when storing or loading a component out of a vector * with a non-constant index. This happens for v[i] = f where v is * a vector (or m[i][j] = f where m is a matrix). If we don't * lower that here, it gets turned into v = vector_insert(v, i, * f), which loads the entire vector, modifies one component and * then write the entire thing back. That breaks if another * thread or SIMD channel is modifying the same vector. */ array_stride = 4; if (deref_array->array->type->is_64bit()) array_stride *= 2; } else if (deref_array->array->type->is_matrix() && *row_major) { /* When loading a vector out of a row major matrix, the * step between the columns (vectors) is the size of a * float, while the step between the rows (elements of a * vector) is handled below in emit_ubo_loads. */ array_stride = 4; if (deref_array->array->type->is_64bit()) array_stride *= 2; *matrix_type = deref_array->array->type; } else if (deref_array->type->without_array()->is_interface()) { /* We're processing an array dereference of an interface instance * array. The thing being dereferenced *must* be a variable * dereference because interfaces cannot be embedded in other * types. In terms of calculating the offsets for the lowering * pass, we don't care about the array index. All elements of an * interface instance array will have the same offsets relative to * the base of the block that backs them. */ deref = deref_array->array->as_dereference(); break; } else { /* Whether or not the field is row-major (because it might be a * bvec2 or something) does not affect the array itself. We need * to know whether an array element in its entirety is row-major. */ const bool array_row_major = is_dereferenced_thing_row_major(deref_array); /* The array type will give the correct interface packing * information */ if (packing == GLSL_INTERFACE_PACKING_STD430) { array_stride = deref_array->type->std430_array_stride(array_row_major); } else { array_stride = deref_array->type->std140_size(array_row_major); array_stride = glsl_align(array_stride, 16); } } ir_rvalue *array_index = deref_array->array_index; if (array_index->type->base_type == GLSL_TYPE_INT) array_index = i2u(array_index); ir_constant *const_index = array_index->constant_expression_value(mem_ctx, NULL); if (const_index) { *const_offset += array_stride * const_index->value.u[0]; } else { *offset = add(*offset, mul(array_index, new(mem_ctx) ir_constant(array_stride))); } deref = deref_array->array->as_dereference(); break; } case ir_type_dereference_record: { ir_dereference_record *deref_record = (ir_dereference_record *) deref; const glsl_type *struct_type = deref_record->record->type; unsigned intra_struct_offset = 0; for (unsigned int i = 0; i < struct_type->length; i++) { const glsl_type *type = struct_type->fields.structure[i].type; ir_dereference_record *field_deref = new(mem_ctx) ir_dereference_record(deref_record->record, struct_type->fields.structure[i].name); const bool field_row_major = is_dereferenced_thing_row_major(field_deref); ralloc_free(field_deref); unsigned field_align = 0; if (packing == GLSL_INTERFACE_PACKING_STD430) field_align = type->std430_base_alignment(field_row_major); else field_align = type->std140_base_alignment(field_row_major); if (struct_type->fields.structure[i].offset != -1) { intra_struct_offset = struct_type->fields.structure[i].offset; } intra_struct_offset = glsl_align(intra_struct_offset, field_align); assert(deref_record->field_idx >= 0); if (i == (unsigned) deref_record->field_idx) { if (struct_field) *struct_field = &struct_type->fields.structure[i]; break; } if (packing == GLSL_INTERFACE_PACKING_STD430) intra_struct_offset += type->std430_size(field_row_major); else intra_struct_offset += type->std140_size(field_row_major); /* If the field just examined was itself a structure, apply rule * #9: * * "The structure may have padding at the end; the base offset * of the member following the sub-structure is rounded up to * the next multiple of the base alignment of the structure." */ if (type->without_array()->is_record()) { intra_struct_offset = glsl_align(intra_struct_offset, field_align); } } *const_offset += intra_struct_offset; deref = deref_record->record->as_dereference(); break; } case ir_type_swizzle: { ir_swizzle *deref_swizzle = (ir_swizzle *) deref; assert(deref_swizzle->mask.num_components == 1); *const_offset += deref_swizzle->mask.x * sizeof(int); deref = deref_swizzle->val->as_dereference(); break; } default: assert(!"not reached"); deref = NULL; break; } } } } /* namespace lower_buffer_access */
#include <math.h> double computeDistance(const double* feat1,const double* feat2,const int f1, const int f2,const int size) { int nbBins = 8; double descd = 0; unsigned int index [] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127}; const unsigned int nextindex [] = { // The inner ring 56,57,58,59,60,61,62,63, 0,1,2,3,4,5,6,7, 8,9,10,11,12,13,14,15, 16,17,18,19,20,21,22,23, 24,25,26,27,28,29,30,31, 32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55, // The outher ring 120,121,122,123,124,125,126,127, 64,65,66,67,68,69,70,71, 72,73,74,75,76,77,78,79, 80,81,82,83,84,85,86,87, 88,89,90,91,92,93,94,95, 96,97,98,99,100,101,102,103, 104,105,106,107,108,109,110,111, 112,113,114,115,116,117,118,119 }; double mindescd = 1e10; for (int idxShift = 0;idxShift < nbBins;idxShift++) { descd=0; for(int v=0;v<size-9;v++){//distance is computed here !!!! descd+=fabs(feat1[f1+index[v]+9]-feat2[f2+v+9]); index[v] = nextindex[index[v]]; } if (mindescd > descd) mindescd = descd; } descd = mindescd; return descd; }
// // mc.cpp // // manage c++ code // // Created by Daniel Kozitza // #include <csignal> #include <cstdlib> #include <dirent.h> #include <fstream> #include <iomanip> #include <iostream> #include <sys/ioctl.h> #include <omp.h> #include "commands.hpp" #include "tools.hpp" #include "sorters.hpp" using namespace tools; typedef map<string, string>::iterator map_iter; void build(vector<string>& argv); void cnt(); void env(); void makefile(vector<string>& argv); void mkreadme(vector<string>& argv); void rebuild(vector<string>& argv); void run(vector<string>& argv); void runtime(vector<string>& argv); void runtimeavg(vector<string>& argv); int main(int argc, char *argv[]) { vector<string> Argv(0); string cmd_str; signal(SIGINT, signals_callback_handler); struct winsize ws; ioctl(0, TIOCGWINSZ, &ws); commands cmds; cmds.set_program_name(string(argv[0])); cmds.set_max_line_width(ws.ws_col); cmds.set_cmds_help( "\nmc is a tool for managing c++ source code.\n\n" "Usage:\n\n mc command [arguments]\n"); cmds.handle( "makefile", makefile, "Creates a make file by calling vfnmkmc [arguments].", "makefile [arguments]"); cmds.handle( "build", build, "Calls vfnmkmc [arguments] (if needed) then calls make.", "build [arguments]"); cmds.handle( "rebuild", rebuild, "Calls make clean, vfnmkmc [arguments] (if needed), then make.", "rebuild [arguments]"); cmds.handle( "run", run, "Calls vfnmkmc (if needed), make, then ./program [arguments].", "run [arguments]"); cmds.handle( "runtime", runtime, "Time the run command.", "runtime [arguments]"); cmds.handle( "runtimeavg", runtimeavg, "Get the average time of multiple run executions.", "runtimeavg [RUNS=10, [arguments]]"); cmds.handle( "env", env, "Displays the variables read from vfnmkmc.conf.", "env"); cmds.handle( "mkreadme", mkreadme, "Make a README.md file from ./program [arguments].", "mkreadme"); cmds.handle( "cnt", cnt, "Counts the number of lines in each of the source files.", "cnt"); if (argc < 2) cmd_str = "help"; else cmd_str = argv[1]; for (int i = 2; i < argc; i++) Argv.push_back(string(argv[i])); cmds.run(cmd_str, Argv); return 0; } void makefile(vector<string>& argv) { string sys_call = "vfnmkmc"; for (int i = 0; i < argv.size(); i++) sys_call += " \"" + argv[i] + "\""; cout << "mc::makefile: calling `" << sys_call << "`." << endl; require(system(sys_call.c_str())); } void build(vector<string>& argv) { map<string, string> vfnconf; if (!get_vfnmkmc_conf(vfnconf)) { makefile(argv); cout << "mc::build: reading vfnmkmc.conf." << endl; require(get_vfnmkmc_conf(vfnconf)); vfnconf["src_files"] = get_src_files(vfnconf["src_directory"]); save_vfnmkmc_conf(vfnconf); } else { // vfnmkmc.conf was read, check if current source file listing matches // the one in vfnconf. string new_src_files = get_src_files(vfnconf["src_directory"]); if (vfnconf["src_files"] != new_src_files) { // if no match set new_src_files and call vfnmake vfnconf["src_files"] = new_src_files; save_vfnmkmc_conf(vfnconf); makefile(argv); } } cout << "mc::build: calling `make`." << endl; require(system("make")); } void rebuild(vector<string>& argv) { cout << "mc::rebuild: calling `make clean`.\n"; require(system("make clean")); build(argv); } void run(vector<string>& argv) { vector<string> empty_v; build(empty_v); map<string, string> vfnconf; require(get_vfnmkmc_conf(vfnconf)); string system_call = "./"; system_call += vfnconf["name"]; for (int i = 0; i < argv.size(); i++) system_call += " \"" + argv[i] + "\""; cout << "mc::run: calling `" << system_call << "`.\n"; system(system_call.c_str()); } void runtime(vector<string>& argv) { double start, end; vector<string> empty_v; build(empty_v); map<string, string> vfnconf; require(get_vfnmkmc_conf(vfnconf)); string system_call = "./"; system_call += vfnconf["name"]; for (int i = 0; i < argv.size(); i++) system_call += " \"" + argv[i] + "\""; cout << "mc::runtime: calling `" << system_call << "`.\n"; start = omp_get_wtime(); system(system_call.c_str()); end = omp_get_wtime(); cout << "mc::runtime: execution time (seconds): `"; cout << end - start << "`.\n"; } void runtimeavg(vector<string>& argv) { double start, end, average = 0; int runs; vector<string> empty_v; build(empty_v); map<string, string> vfnconf; require(get_vfnmkmc_conf(vfnconf)); if (argv.size() < 1) runs = 10; else runs = atoi(argv[0].c_str()); string system_call = "./"; system_call += vfnconf["name"]; for (int z = 1; z < argv.size(); z++) system_call += " \"" + argv[z] + "\""; for(int j = 0; j < runs; ++j) { cout << "mc::runtimeavg: starting run " << j + 1 << "/" << runs << ".\n"; cout << "mc::runtimeavg: calling `" << system_call << "`.\n"; start = omp_get_wtime(); system(system_call.c_str()); end = omp_get_wtime(); cout << "mc::runtimeavg: execution time for run " << j + 1 << "/"; cout << runs << " (seconds): `" << end - start << "`.\n"; if (average != 0) average = (average + (end - start)) / 2; else average = end - start; } cout << "mc::runtimeavg: execution time average after "; cout << runs << " runs (seconds): `"; cout << average << "`.\n"; } void env() { map<string, string> vfnconf; cout << "mc::env: reading vfnmkmc.conf." << endl; require(get_vfnmkmc_conf(vfnconf)); cout << "\nvfnmkmc.conf:\n\n"; //for (const auto item : vfnconf) { // cout << item.first << ": " << item.second << "\n"; //} for (map_iter it = vfnconf.begin(); it != vfnconf.end(); ++it) cout << it->first << ": " << it->second << "\n"; cout << "\n"; } void mkreadme(vector<string>& argv) { map<string, string> vfnconf; cout << "mc::mkreadme: reading vfnmkmc.conf." << endl; require(get_vfnmkmc_conf(vfnconf)); string sys_call = "echo '# " + vfnconf["name"] + "' > README.md"; cout << "mc::mkreadme: calling `" << sys_call << "`.\n"; require(system(sys_call.c_str())); sys_call = "./" + vfnconf["name"]; for (int i = 0; i < argv.size(); ++i) sys_call += " \"" + argv[i] + "\""; sys_call += " >> README.md"; cout << "mc::mkreadme: calling `" << sys_call << "`.\n"; system(sys_call.c_str()); } void cnt() { map<string, string> vfnconf; vector<string> contents(0); unsigned int total_lines = 0; string src_dir; if (get_vfnmkmc_conf(vfnconf)) src_dir = vfnconf["src_directory"]; else src_dir = "."; if (!list_dir_r(src_dir, contents)) { cerr << "mc::cnt: vfnmkmc src_directory `" + src_dir; cerr << "` does not exist\n"; return; } vector<string> new_contents(0); for (int i = 0; i < contents.size(); ++i) { if (pmatches(contents[i], "(\\.cpp|\\.c|\\.hpp|\\.h)$")) { new_contents.push_back(contents[i]); } } contents = new_contents; new_contents.clear(); int longest = 0; for (int i = 0; i < contents.size(); ++i) { string fname = src_dir + "/" + contents[i]; if (fname.size() > longest) longest = fname.size() + 1; } sorters::radix(contents); ifstream fh; for (int i = 0; i < contents.size(); ++i) { string fname = src_dir + "/" + contents[i]; fh.open(fname.c_str(), ifstream::in); if (!fh.is_open()) { cout << "mc::cnt: could not open file: `" << fname << "`\n"; continue; } char c; int file_lines = 0; while (fh.peek() != EOF) { fh.get(c); if (c == '\n') ++file_lines; } fh.close(); total_lines += file_lines; fname += ":"; cout << left << setw(longest) << fname; cout << " " << file_lines << endl; } cout << endl << left << setw(longest) << "total_loc:"; cout << " " << total_lines << "\n\n"; }
// Copyright 2014 The Cockroach 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. See the AUTHORS file // for names of contributors. // // Author: Spencer Kimball (spencer.kimball@gmail.com) // Author: Peter Mattis (petermattis@gmail.com) #include "rocksdb/slice.h" namespace { const uint8_t kEscape1 = 0x00; const uint8_t kEscape2 = 0xff; const uint8_t kEscapedTerm = 0x01; const uint8_t kEscapedNul = 0xff; const uint8_t kEscapedFF = 0x00; template <typename T> bool DecodeUvarint(rocksdb::Slice* buf, T* value) { if (buf->empty()) { return false; } int len = (*buf)[0] - 8; if (len < 0) { return false; } if ((len + 1) > buf->size()) { return false; } if (len > sizeof(T)) { // Decoded value will overflow. return false; } *value = 0; const uint8_t* ptr = reinterpret_cast<const uint8_t*>(buf->data()) + len; for (int i = 0; i < len; ++i) { *value |= static_cast<T>(*ptr--) << (i * 8); } buf->remove_prefix(len + 1); return true; } } // namespace // TODO(pmattis): These functions are not tested. Doing so is made // difficult by "go test" because _test.go files cannot 'import "C"'. bool DecodeBytes(rocksdb::Slice* buf, std::string* decoded) { const uint8_t *data = reinterpret_cast<const uint8_t*>(buf->data()); if (buf->size() > 0 && data[0] == kEscape2) { if (buf->size() == 1) { return false; } if (data[1] != kEscapedFF) { return false; } decoded->append("\xff", 1); buf->remove_prefix(2); } int copyStart = 0; for (int i = 0, n = int(buf->size()) - 1; i < n; ++i) { uint8_t v = data[i]; if (v == kEscape1) { decoded->append(buf->data() + copyStart, i-copyStart); v = data[++i]; if (v == kEscapedTerm) { buf->remove_prefix(i + 1); return true; } if (v != kEscapedNul) { return false; } decoded->append("\0", 1); copyStart = i + 1; } } return false; } bool DecodeUvarint64(rocksdb::Slice* buf, uint64_t* value) { return DecodeUvarint(buf, value); }
//======================================================================= // Copyright Baptiste Wicht 2011-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "cpp_utils/assert.hpp" #include "mangling.hpp" #include "Type.hpp" #include "Platform.hpp" #include "GlobalContext.hpp" using namespace eddic; /* Standard Types */ std::shared_ptr<const Type> eddic::BOOL = std::make_shared<StandardType>(BaseType::BOOL, false); std::shared_ptr<const Type> eddic::INT = std::make_shared<StandardType>(BaseType::INT, false); std::shared_ptr<const Type> eddic::CHAR = std::make_shared<StandardType>(BaseType::CHAR, false); std::shared_ptr<const Type> eddic::FLOAT = std::make_shared<StandardType>(BaseType::FLOAT, false); std::shared_ptr<const Type> eddic::STRING = std::make_shared<StandardType>(BaseType::STRING, false); std::shared_ptr<const Type> eddic::VOID = std::make_shared<StandardType>(BaseType::VOID, false); /* Const versions */ const std::shared_ptr<const Type> CBOOL = std::make_shared<StandardType>(BaseType::BOOL, true); const std::shared_ptr<const Type> CINT = std::make_shared<StandardType>(BaseType::INT, true); const std::shared_ptr<const Type> CCHAR = std::make_shared<StandardType>(BaseType::CHAR, true); const std::shared_ptr<const Type> CFLOAT = std::make_shared<StandardType>(BaseType::FLOAT, true); const std::shared_ptr<const Type> CSTRING = std::make_shared<StandardType>(BaseType::STRING, true); const std::shared_ptr<const Type> CVOID = std::make_shared<StandardType>(BaseType::VOID, true); /* Implementation of Type */ Type::Type() {} bool Type::is_array() const { return false; } bool Type::is_dynamic_array() const { return is_array() && !has_elements(); } bool Type::is_structure() const { return is_custom_type() || is_template_type(); } bool Type::is_pointer() const { return false; } bool Type::is_custom_type() const { return false; } bool Type::is_standard_type() const { return false; } bool Type::is_const() const { return false; } bool Type::is_template_type() const { return false; } unsigned int Type::size(Platform) const { cpp_unreachable("Not specialized type"); } unsigned int Type::elements() const { cpp_unreachable("Not an array type"); } bool Type::has_elements() const { cpp_unreachable("Not an array type"); } std::string Type::type() const { cpp_unreachable("Not a custom type"); } std::shared_ptr<const Type> Type::data_type() const { cpp_unreachable("No data type"); } std::vector<std::shared_ptr<const Type>> Type::template_types() const { cpp_unreachable("No template types"); } BaseType Type::base() const { cpp_unreachable("Not a standard type"); } std::string Type::mangle() const { return ::mangle(shared_from_this()); } bool eddic::operator==(std::shared_ptr<const Type> lhs, std::shared_ptr<const Type> rhs){ if(lhs->is_array()){ return rhs->is_array() && lhs->data_type() == rhs->data_type() ;//&& lhs->elements() == rhs->elements(); } if(lhs->is_pointer()){ return rhs->is_pointer() && lhs->data_type() == rhs->data_type(); } if(lhs->is_custom_type()){ return rhs->is_custom_type() && lhs->type() == rhs->type(); } if(lhs->is_standard_type()){ return rhs->is_standard_type() && lhs->base() == rhs->base(); } if(lhs->is_template_type()){ if(rhs->is_template_type() && lhs->type() == rhs->type()){ return lhs->template_types() == rhs->template_types(); } } return false; } bool eddic::operator!=(std::shared_ptr<const Type> lhs, std::shared_ptr<const Type> rhs){ return !(lhs == rhs); } /* Implementation of StandardType */ StandardType::StandardType(BaseType type, bool const_) : base_type(type), const_(const_) {} BaseType StandardType::base() const { return base_type; } bool StandardType::is_standard_type() const { return true; } bool StandardType::is_const() const { return const_; } unsigned int StandardType::size(Platform platform) const { auto descriptor = getPlatformDescriptor(platform); return descriptor->size_of(base()); } /* Implementation of CustomType */ CustomType::CustomType(std::shared_ptr<GlobalContext> context, const std::string& type) : context(context), m_type(type) {} std::string CustomType::type() const { return m_type; } bool CustomType::is_custom_type() const { return true; } unsigned int CustomType::size(Platform) const { return context->total_size_of_struct(context->get_struct(shared_from_this())); } /* Implementation of ArrayType */ ArrayType::ArrayType(std::shared_ptr<const Type> sub_type) : sub_type(sub_type) {} ArrayType::ArrayType(std::shared_ptr<const Type> sub_type, int size) : sub_type(sub_type), m_elements(size) {} unsigned int ArrayType::elements() const { assert(has_elements()); return *m_elements; } bool ArrayType::has_elements() const { return static_cast<bool>(m_elements); } std::shared_ptr<const Type> ArrayType::data_type() const { return sub_type; } bool ArrayType::is_array() const { return true; } unsigned int ArrayType::size(Platform platform) const { if(has_elements()){ return data_type()->size(platform) * elements() + INT->size(platform); } else { return INT->size(platform); } } /* Implementation of PointerType */ PointerType::PointerType(std::shared_ptr<const Type> sub_type) : sub_type(sub_type) {} std::shared_ptr<const Type> PointerType::data_type() const { return sub_type; } bool PointerType::is_pointer() const { return true; } unsigned int PointerType::size(Platform platform) const { return INT->size(platform); } /* Implementation of TemplateType */ TemplateType::TemplateType(std::shared_ptr<GlobalContext> context, std::string main_type, std::vector<std::shared_ptr<const Type>> sub_types) : context(context), main_type(main_type), sub_types(sub_types) {} std::string TemplateType::type() const { return main_type; } std::vector<std::shared_ptr<const Type>> TemplateType::template_types() const { return sub_types; } bool TemplateType::is_template_type() const { return true; } unsigned int TemplateType::size(Platform) const { return context->total_size_of_struct(context->get_struct(shared_from_this())); } /* Implementation of factories */ std::shared_ptr<const Type> eddic::new_type(std::shared_ptr<GlobalContext> context, const std::string& type, bool const_){ //Parse standard and custom types if(is_standard_type(type)){ if(const_){ if (type == "int") { return CINT; } else if (type == "char") { return CCHAR; } else if (type == "bool") { return CBOOL; } else if (type == "float"){ return CFLOAT; } else if (type == "str"){ return CSTRING; } else { return CVOID; } } else { if (type == "int") { return INT; } else if (type == "char") { return CHAR; } else if (type == "bool") { return BOOL; } else if (type == "float"){ return FLOAT; } else if (type == "str"){ return STRING; } else { return VOID; } } } else { cpp_assert(!const_, "Only standard type can be const"); return std::make_shared<CustomType>(context, type); } } std::shared_ptr<const Type> eddic::new_array_type(std::shared_ptr<const Type> data_type){ return std::make_shared<ArrayType>(data_type); } std::shared_ptr<const Type> eddic::new_array_type(std::shared_ptr<const Type> data_type, int size){ return std::make_shared<ArrayType>(data_type, size); } std::shared_ptr<const Type> eddic::new_pointer_type(std::shared_ptr<const Type> data_type){ return std::make_shared<PointerType>(data_type); } std::shared_ptr<const Type> eddic::new_template_type(std::shared_ptr<GlobalContext> context, std::string data_type, std::vector<std::shared_ptr<const Type>> template_types){ return std::make_shared<TemplateType>(context, data_type, template_types); } bool eddic::is_standard_type(const std::string& type){ return type == "int" || type == "char" || type == "void" || type == "str" || type == "bool" || type == "float"; }
// IssuerAndSerialNumber.cpp: implementation of the CIssuerAndSerialNumber class. // ////////////////////////////////////////////////////////////////////// #include "IssuerAndSerialNumber.h" #include "ASN1OptionalField.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CIssuerAndSerialNumber::CIssuerAndSerialNumber(UUCBufferedReader& reader) : CASN1Sequence(reader) { } CIssuerAndSerialNumber::CIssuerAndSerialNumber(const CASN1Object& issuerAndSerNum) : CASN1Sequence(issuerAndSerNum) { } CIssuerAndSerialNumber::CIssuerAndSerialNumber(const CName& issuer, const CASN1Integer& serNum, bool contextSpecific) { if(contextSpecific) { CASN1Sequence issuerField; issuerField.addElement(issuer); CASN1Sequence innerSequence; innerSequence.addElement(CASN1OptionalField(issuerField, 0x04)); addElement(innerSequence); addElement(serNum); } else { addElement(issuer); addElement(serNum); } } CIssuerAndSerialNumber::~CIssuerAndSerialNumber() { }
#include <iostream> #include <deque> using namespace std; int main(){ system("Color 02"); deque<int> deff; int n; cout<<"N="; cin>>n; for(int i=1; i<=n; i++){ if(i%2==0) deff.push_front(i); else deff.push_back(i); } for(int i=0; i<deff.size(); i++){ cout<<deff.at(i)<<"\t"; } cout<<"\n\n"; main(); }
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #include "Test.h" #include "GrClip.h" #include "GrContext.h" #include "GrContextPriv.h" #include "GrGpuResource.h" #include "GrMemoryPool.h" #include "GrProxyProvider.h" #include "GrRenderTargetContext.h" #include "GrRenderTargetContextPriv.h" #include "GrResourceProvider.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "ops/GrMeshDrawOp.h" #include "ops/GrRectOpFactory.h" #include "TestUtils.h" #include <random> namespace { class TestOp : public GrMeshDrawOp { public: DEFINE_OP_CLASS_ID static std::unique_ptr<GrDrawOp> Make(GrContext* context, std::unique_ptr<GrFragmentProcessor> fp) { GrOpMemoryPool* pool = context->contextPriv().opMemoryPool(); return pool->allocate<TestOp>(std::move(fp)); } const char* name() const override { return "TestOp"; } void visitProxies(const VisitProxyFunc& func, VisitorType) const override { fProcessors.visitProxies(func); } FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; } RequiresDstTexture finalize(const GrCaps& caps, const GrAppliedClip* clip) override { static constexpr GrProcessorAnalysisColor kUnknownColor; GrColor4h overrideColor; fProcessors.finalize(kUnknownColor, GrProcessorAnalysisCoverage::kNone, clip, false, caps, &overrideColor); return RequiresDstTexture::kNo; } private: friend class ::GrOpMemoryPool; // for ctor TestOp(std::unique_ptr<GrFragmentProcessor> fp) : INHERITED(ClassID()), fProcessors(std::move(fp)) { this->setBounds(SkRect::MakeWH(100, 100), HasAABloat::kNo, IsZeroArea::kNo); } void onPrepareDraws(Target* target) override { return; } GrProcessorSet fProcessors; typedef GrMeshDrawOp INHERITED; }; /** * FP used to test ref/IO counts on owned GrGpuResources. Can also be a parent FP to test counts * of resources owned by child FPs. */ class TestFP : public GrFragmentProcessor { public: static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> child) { return std::unique_ptr<GrFragmentProcessor>(new TestFP(std::move(child))); } static std::unique_ptr<GrFragmentProcessor> Make(const SkTArray<sk_sp<GrTextureProxy>>& proxies, const SkTArray<sk_sp<GrBuffer>>& buffers) { return std::unique_ptr<GrFragmentProcessor>(new TestFP(proxies, buffers)); } const char* name() const override { return "test"; } void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override { // We don't really care about reusing these. static int32_t gKey = 0; b->add32(sk_atomic_inc(&gKey)); } std::unique_ptr<GrFragmentProcessor> clone() const override { return std::unique_ptr<GrFragmentProcessor>(new TestFP(*this)); } private: TestFP(const SkTArray<sk_sp<GrTextureProxy>>& proxies, const SkTArray<sk_sp<GrBuffer>>& buffers) : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags), fSamplers(4) { for (const auto& proxy : proxies) { fSamplers.emplace_back(proxy); } this->setTextureSamplerCnt(fSamplers.count()); } TestFP(std::unique_ptr<GrFragmentProcessor> child) : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags), fSamplers(4) { this->registerChildProcessor(std::move(child)); } explicit TestFP(const TestFP& that) : INHERITED(kTestFP_ClassID, that.optimizationFlags()), fSamplers(4) { for (int i = 0; i < that.fSamplers.count(); ++i) { fSamplers.emplace_back(that.fSamplers[i]); } for (int i = 0; i < that.numChildProcessors(); ++i) { this->registerChildProcessor(that.childProcessor(i).clone()); } this->setTextureSamplerCnt(fSamplers.count()); } virtual GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { class TestGLSLFP : public GrGLSLFragmentProcessor { public: TestGLSLFP() {} void emitCode(EmitArgs& args) override { GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder; fragBuilder->codeAppendf("%s = %s;", args.fOutputColor, args.fInputColor); } private: }; return new TestGLSLFP(); } bool onIsEqual(const GrFragmentProcessor&) const override { return false; } const TextureSampler& onTextureSampler(int i) const override { return fSamplers[i]; } GrTAllocator<TextureSampler> fSamplers; typedef GrFragmentProcessor INHERITED; }; } template <typename T> inline void testingOnly_getIORefCnts(const T* resource, int* refCnt, int* readCnt, int* writeCnt) { *refCnt = resource->fRefCnt; *readCnt = resource->fPendingReads; *writeCnt = resource->fPendingWrites; } void testingOnly_getIORefCnts(GrTextureProxy* proxy, int* refCnt, int* readCnt, int* writeCnt) { *refCnt = proxy->getBackingRefCnt_TestOnly(); *readCnt = proxy->getPendingReadCnt_TestOnly(); *writeCnt = proxy->getPendingWriteCnt_TestOnly(); } DEF_GPUTEST_FOR_ALL_CONTEXTS(ProcessorRefTest, reporter, ctxInfo) { GrContext* context = ctxInfo.grContext(); GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider(); GrSurfaceDesc desc; desc.fWidth = 10; desc.fHeight = 10; desc.fConfig = kRGBA_8888_GrPixelConfig; for (bool makeClone : {false, true}) { for (int parentCnt = 0; parentCnt < 2; parentCnt++) { sk_sp<GrRenderTargetContext> renderTargetContext( context->contextPriv().makeDeferredRenderTargetContext( SkBackingFit::kApprox, 1, 1, kRGBA_8888_GrPixelConfig, nullptr)); { sk_sp<GrTextureProxy> proxy1 = proxyProvider->createProxy( desc, kTopLeft_GrSurfaceOrigin, SkBackingFit::kExact, SkBudgeted::kYes); sk_sp<GrTextureProxy> proxy2 = proxyProvider->createProxy( desc, kTopLeft_GrSurfaceOrigin, SkBackingFit::kExact, SkBudgeted::kYes); sk_sp<GrTextureProxy> proxy3 = proxyProvider->createProxy( desc, kTopLeft_GrSurfaceOrigin, SkBackingFit::kExact, SkBudgeted::kYes); sk_sp<GrTextureProxy> proxy4 = proxyProvider->createProxy( desc, kTopLeft_GrSurfaceOrigin, SkBackingFit::kExact, SkBudgeted::kYes); { SkTArray<sk_sp<GrTextureProxy>> proxies; SkTArray<sk_sp<GrBuffer>> buffers; proxies.push_back(proxy1); auto fp = TestFP::Make(std::move(proxies), std::move(buffers)); for (int i = 0; i < parentCnt; ++i) { fp = TestFP::Make(std::move(fp)); } std::unique_ptr<GrFragmentProcessor> clone; if (makeClone) { clone = fp->clone(); } std::unique_ptr<GrDrawOp> op(TestOp::Make(context, std::move(fp))); renderTargetContext->priv().testingOnly_addDrawOp(std::move(op)); if (clone) { op = TestOp::Make(context, std::move(clone)); renderTargetContext->priv().testingOnly_addDrawOp(std::move(op)); } } int refCnt, readCnt, writeCnt; testingOnly_getIORefCnts(proxy1.get(), &refCnt, &readCnt, &writeCnt); // IO counts should be double if there is a clone of the FP. int ioRefMul = makeClone ? 2 : 1; REPORTER_ASSERT(reporter, -1 == refCnt); REPORTER_ASSERT(reporter, ioRefMul * 1 == readCnt); REPORTER_ASSERT(reporter, ioRefMul * 0 == writeCnt); context->flush(); testingOnly_getIORefCnts(proxy1.get(), &refCnt, &readCnt, &writeCnt); REPORTER_ASSERT(reporter, 1 == refCnt); REPORTER_ASSERT(reporter, ioRefMul * 0 == readCnt); REPORTER_ASSERT(reporter, ioRefMul * 0 == writeCnt); } } } } // This test uses the random GrFragmentProcessor test factory, which relies on static initializers. #if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS #include "SkCommandLineFlags.h" DEFINE_bool(randomProcessorTest, false, "Use non-deterministic seed for random processor tests?"); DEFINE_uint32(processorSeed, 0, "Use specific seed for processor tests. Overridden by " \ "--randomProcessorTest."); #if GR_TEST_UTILS static GrColor input_texel_color(int i, int j, SkScalar delta) { // Delta must be less than 0.5 to prevent over/underflow issues with the input color SkASSERT(delta <= 0.5); SkColor color = SkColorSetARGB((uint8_t)i, (uint8_t)j, (uint8_t)(i + j), (uint8_t)(2 * j - i)); SkColor4f color4f = SkColor4f::FromColor(color); for (int i = 0; i < 4; i++) { if (color4f[i] > 0.5) { color4f[i] -= delta; } else { color4f[i] += delta; } } return color4f.premul().toBytes_RGBA(); } void test_draw_op(GrContext* context, GrRenderTargetContext* rtc, std::unique_ptr<GrFragmentProcessor> fp, sk_sp<GrTextureProxy> inputDataProxy) { GrPaint paint; paint.addColorTextureProcessor(std::move(inputDataProxy), SkMatrix::I()); paint.addColorFragmentProcessor(std::move(fp)); paint.setPorterDuffXPFactory(SkBlendMode::kSrc); auto op = GrRectOpFactory::MakeNonAAFill(context, std::move(paint), SkMatrix::I(), SkRect::MakeWH(rtc->width(), rtc->height()), GrAAType::kNone); rtc->addDrawOp(GrNoClip(), std::move(op)); } // This assumes that the output buffer will be the same size as inputDataProxy void render_fp(GrContext* context, GrRenderTargetContext* rtc, GrFragmentProcessor* fp, sk_sp<GrTextureProxy> inputDataProxy, GrColor* buffer) { int width = inputDataProxy->width(); int height = inputDataProxy->height(); // test_draw_op needs to take ownership of an FP, so give it a clone that it can own test_draw_op(context, rtc, fp->clone(), inputDataProxy); memset(buffer, 0x0, sizeof(GrColor) * width * height); rtc->readPixels(SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType), buffer, 0, 0, 0); } /** Initializes the two test texture proxies that are available to the FP test factories. */ bool init_test_textures(GrProxyProvider* proxyProvider, SkRandom* random, sk_sp<GrTextureProxy> proxies[2]) { static const int kTestTextureSize = 256; { // Put premul data into the RGBA texture that the test FPs can optionally use. std::unique_ptr<GrColor[]> rgbaData(new GrColor[kTestTextureSize * kTestTextureSize]); for (int y = 0; y < kTestTextureSize; ++y) { for (int x = 0; x < kTestTextureSize; ++x) { rgbaData[kTestTextureSize * y + x] = input_texel_color( random->nextULessThan(256), random->nextULessThan(256), 0.0f); } } SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize, kRGBA_8888_SkColorType, kPremul_SkAlphaType); SkPixmap pixmap(ii, rgbaData.get(), ii.minRowBytes()); sk_sp<SkImage> img = SkImage::MakeRasterCopy(pixmap); proxies[0] = proxyProvider->createTextureProxy(img, kNone_GrSurfaceFlags, 1, SkBudgeted::kYes, SkBackingFit::kExact); } { // Put random values into the alpha texture that the test FPs can optionally use. std::unique_ptr<uint8_t[]> alphaData(new uint8_t[kTestTextureSize * kTestTextureSize]); for (int y = 0; y < kTestTextureSize; ++y) { for (int x = 0; x < kTestTextureSize; ++x) { alphaData[kTestTextureSize * y + x] = random->nextULessThan(256); } } SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize, kAlpha_8_SkColorType, kPremul_SkAlphaType); SkPixmap pixmap(ii, alphaData.get(), ii.minRowBytes()); sk_sp<SkImage> img = SkImage::MakeRasterCopy(pixmap); proxies[1] = proxyProvider->createTextureProxy(img, kNone_GrSurfaceFlags, 1, SkBudgeted::kYes, SkBackingFit::kExact); } return proxies[0] && proxies[1]; } // Creates a texture of premul colors used as the output of the fragment processor that precedes // the fragment processor under test. Color values are those provided by input_texel_color(). sk_sp<GrTextureProxy> make_input_texture(GrProxyProvider* proxyProvider, int width, int height, SkScalar delta) { std::unique_ptr<GrColor[]> data(new GrColor[width * height]); for (int y = 0; y < width; ++y) { for (int x = 0; x < height; ++x) { data.get()[width * y + x] = input_texel_color(x, y, delta); } } SkImageInfo ii = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType); SkPixmap pixmap(ii, data.get(), ii.minRowBytes()); sk_sp<SkImage> img = SkImage::MakeRasterCopy(pixmap); return proxyProvider->createTextureProxy(img, kNone_GrSurfaceFlags, 1, SkBudgeted::kYes, SkBackingFit::kExact); } bool log_surface_context(sk_sp<GrSurfaceContext> src, SkString* dst) { SkImageInfo ii = SkImageInfo::Make(src->width(), src->height(), kRGBA_8888_SkColorType, kPremul_SkAlphaType); SkBitmap bm; SkAssertResult(bm.tryAllocPixels(ii)); SkAssertResult(src->readPixels(ii, bm.getPixels(), bm.rowBytes(), 0, 0)); return bitmap_to_base64_data_uri(bm, dst); } bool log_surface_proxy(GrContext* context, sk_sp<GrSurfaceProxy> src, SkString* dst) { sk_sp<GrSurfaceContext> sContext(context->contextPriv().makeWrappedSurfaceContext(src)); return log_surface_context(sContext, dst); } bool fuzzy_color_equals(const SkPMColor4f& c1, const SkPMColor4f& c2) { // With the loss of precision of rendering into 32-bit color, then estimating the FP's output // from that, it is not uncommon for a valid output to differ from estimate by up to 0.01 // (really 1/128 ~ .0078, but frequently floating point issues make that tolerance a little // too unforgiving). static constexpr SkScalar kTolerance = 0.01f; for (int i = 0; i < 4; i++) { if (!SkScalarNearlyEqual(c1[i], c2[i], kTolerance)) { return false; } } return true; } int modulation_index(int channelIndex, bool alphaModulation) { return alphaModulation ? 3 : channelIndex; } // Given three input colors (color preceding the FP being tested), and the output of the FP, this // ensures that the out1 = fp * in1.a, out2 = fp * in2.a, and out3 = fp * in3.a, where fp is the // pre-modulated color that should not be changing across frames (FP's state doesn't change). // // When alphaModulation is false, this tests the very similar conditions that out1 = fp * in1, // etc. using per-channel modulation instead of modulation by just the input alpha channel. // - This estimates the pre-modulated fp color from one of the input/output pairs and confirms the // conditions hold for the other two pairs. bool legal_modulation(const GrColor& in1, const GrColor& in2, const GrColor& in3, const GrColor& out1, const GrColor& out2, const GrColor& out3, bool alphaModulation) { // Convert to floating point, which is the number space the FP operates in (more or less) SkPMColor4f in1f = SkPMColor4f::FromBytes_RGBA(in1); SkPMColor4f in2f = SkPMColor4f::FromBytes_RGBA(in2); SkPMColor4f in3f = SkPMColor4f::FromBytes_RGBA(in3); SkPMColor4f out1f = SkPMColor4f::FromBytes_RGBA(out1); SkPMColor4f out2f = SkPMColor4f::FromBytes_RGBA(out2); SkPMColor4f out3f = SkPMColor4f::FromBytes_RGBA(out3); // Reconstruct the output of the FP before the shader modulated its color with the input value. // When the original input is very small, it may cause the final output color to round // to 0, in which case we estimate the pre-modulated color using one of the stepped frames that // will then have a guaranteed larger channel value (since the offset will be added to it). SkPMColor4f fpPreModulation; for (int i = 0; i < 4; i++) { int modulationIndex = modulation_index(i, alphaModulation); if (in1f[modulationIndex] < 0.2f) { // Use the stepped frame fpPreModulation[i] = out2f[i] / in2f[modulationIndex]; } else { fpPreModulation[i] = out1f[i] / in1f[modulationIndex]; } } // With reconstructed pre-modulated FP output, derive the expected value of fp * input for each // of the transformed input colors. SkPMColor4f expected1 = alphaModulation ? (fpPreModulation * in1f.fA) : (fpPreModulation * in1f); SkPMColor4f expected2 = alphaModulation ? (fpPreModulation * in2f.fA) : (fpPreModulation * in2f); SkPMColor4f expected3 = alphaModulation ? (fpPreModulation * in3f.fA) : (fpPreModulation * in3f); return fuzzy_color_equals(out1f, expected1) && fuzzy_color_equals(out2f, expected2) && fuzzy_color_equals(out3f, expected3); } DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorOptimizationValidationTest, reporter, ctxInfo) { GrContext* context = ctxInfo.grContext(); GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider(); auto resourceProvider = context->contextPriv().resourceProvider(); using FPFactory = GrFragmentProcessorTestFactory; uint32_t seed = FLAGS_processorSeed; if (FLAGS_randomProcessorTest) { std::random_device rd; seed = rd(); } // If a non-deterministic bot fails this test, check the output to see what seed it used, then // use --processorSeed <seed> (without --randomProcessorTest) to reproduce. SkRandom random(seed); // Make the destination context for the test. static constexpr int kRenderSize = 256; sk_sp<GrRenderTargetContext> rtc = context->contextPriv().makeDeferredRenderTargetContext( SkBackingFit::kExact, kRenderSize, kRenderSize, kRGBA_8888_GrPixelConfig, nullptr); sk_sp<GrTextureProxy> proxies[2]; if (!init_test_textures(proxyProvider, &random, proxies)) { ERRORF(reporter, "Could not create test textures"); return; } GrProcessorTestData testData(&random, context, rtc.get(), proxies); // Coverage optimization uses three frames with a linearly transformed input texture. The first // frame has no offset, second frames add .2 and .4, which should then be present as a fixed // difference between the frame outputs if the FP is properly following the modulation // requirements of the coverage optimization. static constexpr SkScalar kInputDelta = 0.2f; auto inputTexture1 = make_input_texture(proxyProvider, kRenderSize, kRenderSize, 0.0f); auto inputTexture2 = make_input_texture(proxyProvider, kRenderSize, kRenderSize, kInputDelta); auto inputTexture3 = make_input_texture(proxyProvider, kRenderSize, kRenderSize, 2*kInputDelta); // Encoded images are very verbose and this tests many potential images, so only export the // first failure (subsequent failures have a reasonable chance of being related). bool loggedFirstFailure = false; bool loggedFirstWarning = false; // Storage for the three frames required for coverage compatibility optimization. Each frame // uses the correspondingly numbered inputTextureX. std::unique_ptr<GrColor[]> readData1(new GrColor[kRenderSize * kRenderSize]); std::unique_ptr<GrColor[]> readData2(new GrColor[kRenderSize * kRenderSize]); std::unique_ptr<GrColor[]> readData3(new GrColor[kRenderSize * kRenderSize]); // Because processor factories configure themselves in random ways, this is not exhaustive. for (int i = 0; i < FPFactory::Count(); ++i) { int timesToInvokeFactory = 5; // Increase the number of attempts if the FP has child FPs since optimizations likely depend // on child optimizations being present. std::unique_ptr<GrFragmentProcessor> fp = FPFactory::MakeIdx(i, &testData); for (int j = 0; j < fp->numChildProcessors(); ++j) { // This value made a reasonable trade off between time and coverage when this test was // written. timesToInvokeFactory *= FPFactory::Count() / 2; } for (int j = 0; j < timesToInvokeFactory; ++j) { fp = FPFactory::MakeIdx(i, &testData); if (!fp->instantiate(resourceProvider)) { continue; } if (!fp->hasConstantOutputForConstantInput() && !fp->preservesOpaqueInput() && !fp->compatibleWithCoverageAsAlpha()) { continue; } if (fp->compatibleWithCoverageAsAlpha()) { // 2nd and 3rd frames are only used when checking coverage optimization render_fp(context, rtc.get(), fp.get(), inputTexture2, readData2.get()); render_fp(context, rtc.get(), fp.get(), inputTexture3, readData3.get()); } // Draw base frame last so that rtc holds the original FP behavior if we need to // dump the image to the log. render_fp(context, rtc.get(), fp.get(), inputTexture1, readData1.get()); if (0) { // Useful to see what FPs are being tested. SkString children; for (int c = 0; c < fp->numChildProcessors(); ++c) { if (!c) { children.append("("); } children.append(fp->childProcessor(c).name()); children.append(c == fp->numChildProcessors() - 1 ? ")" : ", "); } SkDebugf("%s %s\n", fp->name(), children.c_str()); } // This test has a history of being flaky on a number of devices. If an FP is logically // violating the optimizations, it's reasonable to expect it to violate requirements on // a large number of pixels in the image. Sporadic pixel violations are more indicative // of device errors and represents a separate problem. #if defined(SK_SKQP_GLOBAL_ERROR_TOLERANCE) static constexpr int kMaxAcceptableFailedPixels = 0; // Strict when running as SKQP #else static constexpr int kMaxAcceptableFailedPixels = 2 * kRenderSize; // ~0.7% of the image #endif int failedPixelCount = 0; // Collect first optimization failure message, to be output later as a warning or an // error depending on whether the rendering "passed" or failed. SkString coverageMessage; SkString opaqueMessage; SkString constMessage; for (int y = 0; y < kRenderSize; ++y) { for (int x = 0; x < kRenderSize; ++x) { bool passing = true; GrColor input = input_texel_color(x, y, 0.0f); GrColor output = readData1.get()[y * kRenderSize + x]; if (fp->compatibleWithCoverageAsAlpha()) { GrColor i2 = input_texel_color(x, y, kInputDelta); GrColor i3 = input_texel_color(x, y, 2 * kInputDelta); GrColor o2 = readData2.get()[y * kRenderSize + x]; GrColor o3 = readData3.get()[y * kRenderSize + x]; // A compatible processor is allowed to modulate either the input color or // just the input alpha. bool legalAlphaModulation = legal_modulation(input, i2, i3, output, o2, o3, /* alpha */ true); bool legalColorModulation = legal_modulation(input, i2, i3, output, o2, o3, /* alpha */ false); if (!legalColorModulation && !legalAlphaModulation) { passing = false; if (coverageMessage.isEmpty()) { coverageMessage.printf("\"Modulating\" processor %s did not match " "alpha-modulation nor color-modulation rules. " "Input: 0x%08x, Output: 0x%08x, pixel (%d, %d).", fp->name(), input, output, x, y); } } } SkPMColor4f input4f = SkPMColor4f::FromBytes_RGBA(input); SkPMColor4f output4f = SkPMColor4f::FromBytes_RGBA(output); SkPMColor4f expected4f; if (fp->hasConstantOutputForConstantInput(input4f, &expected4f)) { float rDiff = fabsf(output4f.fR - expected4f.fR); float gDiff = fabsf(output4f.fG - expected4f.fG); float bDiff = fabsf(output4f.fB - expected4f.fB); float aDiff = fabsf(output4f.fA - expected4f.fA); static constexpr float kTol = 4 / 255.f; if (rDiff > kTol || gDiff > kTol || bDiff > kTol || aDiff > kTol) { if (constMessage.isEmpty()) { passing = false; constMessage.printf("Processor %s claimed output for const input " "doesn't match actual output. Error: %f, Tolerance: %f, " "input: (%f, %f, %f, %f), actual: (%f, %f, %f, %f), " "expected(%f, %f, %f, %f)", fp->name(), SkTMax(rDiff, SkTMax(gDiff, SkTMax(bDiff, aDiff))), kTol, input4f.fR, input4f.fG, input4f.fB, input4f.fA, output4f.fR, output4f.fG, output4f.fB, output4f.fA, expected4f.fR, expected4f.fG, expected4f.fB, expected4f.fA); } } } if (GrColorIsOpaque(input) && fp->preservesOpaqueInput() && !GrColorIsOpaque(output)) { passing = false; if (opaqueMessage.isEmpty()) { opaqueMessage.printf("Processor %s claimed opaqueness is preserved but " "it is not. Input: 0x%08x, Output: 0x%08x.", fp->name(), input, output); } } if (!passing) { // Regardless of how many optimizations the pixel violates, count it as a // single bad pixel. failedPixelCount++; } } } // Finished analyzing the entire image, see if the number of pixel failures meets the // threshold for an FP violating the optimization requirements. if (failedPixelCount > kMaxAcceptableFailedPixels) { ERRORF(reporter, "Processor violated %d of %d pixels, seed: 0x%08x, processor: %s" ", first failing pixel details are below:", failedPixelCount, kRenderSize * kRenderSize, seed, fp->dumpInfo().c_str()); // Print first failing pixel's details. if (!coverageMessage.isEmpty()) { ERRORF(reporter, coverageMessage.c_str()); } if (!constMessage.isEmpty()) { ERRORF(reporter, constMessage.c_str()); } if (!opaqueMessage.isEmpty()) { ERRORF(reporter, opaqueMessage.c_str()); } if (!loggedFirstFailure) { // Print with ERRORF to make sure the encoded image is output SkString input; log_surface_proxy(context, inputTexture1, &input); SkString output; log_surface_context(rtc, &output); ERRORF(reporter, "Input image: %s\n\n" "===========================================================\n\n" "Output image: %s\n", input.c_str(), output.c_str()); loggedFirstFailure = true; } } else if(failedPixelCount > 0) { // Don't trigger an error, but don't just hide the failures either. INFOF(reporter, "Processor violated %d of %d pixels (below error threshold), seed: " "0x%08x, processor: %s", failedPixelCount, kRenderSize * kRenderSize, seed, fp->dumpInfo().c_str()); if (!coverageMessage.isEmpty()) { INFOF(reporter, coverageMessage.c_str()); } if (!constMessage.isEmpty()) { INFOF(reporter, constMessage.c_str()); } if (!opaqueMessage.isEmpty()) { INFOF(reporter, opaqueMessage.c_str()); } if (!loggedFirstWarning) { SkString input; log_surface_proxy(context, inputTexture1, &input); SkString output; log_surface_context(rtc, &output); INFOF(reporter, "Input image: %s\n\n" "===========================================================\n\n" "Output image: %s\n", input.c_str(), output.c_str()); loggedFirstWarning = true; } } } } } // Tests that fragment processors returned by GrFragmentProcessor::clone() are equivalent to their // progenitors. DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorCloneTest, reporter, ctxInfo) { GrContext* context = ctxInfo.grContext(); GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider(); auto resourceProvider = context->contextPriv().resourceProvider(); SkRandom random; // Make the destination context for the test. static constexpr int kRenderSize = 1024; sk_sp<GrRenderTargetContext> rtc = context->contextPriv().makeDeferredRenderTargetContext( SkBackingFit::kExact, kRenderSize, kRenderSize, kRGBA_8888_GrPixelConfig, nullptr); sk_sp<GrTextureProxy> proxies[2]; if (!init_test_textures(proxyProvider, &random, proxies)) { ERRORF(reporter, "Could not create test textures"); return; } GrProcessorTestData testData(&random, context, rtc.get(), proxies); auto inputTexture = make_input_texture(proxyProvider, kRenderSize, kRenderSize, 0.0f); std::unique_ptr<GrColor[]> readData1(new GrColor[kRenderSize * kRenderSize]); std::unique_ptr<GrColor[]> readData2(new GrColor[kRenderSize * kRenderSize]); auto readInfo = SkImageInfo::Make(kRenderSize, kRenderSize, kRGBA_8888_SkColorType, kPremul_SkAlphaType); // Because processor factories configure themselves in random ways, this is not exhaustive. for (int i = 0; i < GrFragmentProcessorTestFactory::Count(); ++i) { static constexpr int kTimesToInvokeFactory = 10; for (int j = 0; j < kTimesToInvokeFactory; ++j) { auto fp = GrFragmentProcessorTestFactory::MakeIdx(i, &testData); auto clone = fp->clone(); if (!clone) { ERRORF(reporter, "Clone of processor %s failed.", fp->name()); continue; } const char* name = fp->name(); if (!fp->instantiate(resourceProvider) || !clone->instantiate(resourceProvider)) { continue; } REPORTER_ASSERT(reporter, !strcmp(fp->name(), clone->name())); REPORTER_ASSERT(reporter, fp->compatibleWithCoverageAsAlpha() == clone->compatibleWithCoverageAsAlpha()); REPORTER_ASSERT(reporter, fp->isEqual(*clone)); REPORTER_ASSERT(reporter, fp->preservesOpaqueInput() == clone->preservesOpaqueInput()); REPORTER_ASSERT(reporter, fp->hasConstantOutputForConstantInput() == clone->hasConstantOutputForConstantInput()); REPORTER_ASSERT(reporter, fp->numChildProcessors() == clone->numChildProcessors()); REPORTER_ASSERT(reporter, fp->usesLocalCoords() == clone->usesLocalCoords()); // Draw with original and read back the results. render_fp(context, rtc.get(), fp.get(), inputTexture, readData1.get()); // Draw with clone and read back the results. render_fp(context, rtc.get(), clone.get(), inputTexture, readData2.get()); // Check that the results are the same. bool passing = true; for (int y = 0; y < kRenderSize && passing; ++y) { for (int x = 0; x < kRenderSize && passing; ++x) { int idx = y * kRenderSize + x; if (readData1[idx] != readData2[idx]) { ERRORF(reporter, "Processor %s made clone produced different output. " "Input color: 0x%08x, Original Output Color: 0x%08x, " "Clone Output Color: 0x%08x..", name, input_texel_color(x, y, 0.0f), readData1[idx], readData2[idx]); passing = false; } } } } } } #endif // GR_TEST_UTILS #endif // SK_ALLOW_STATIC_GLOBAL_INITIALIZERS
// // Copyright (c) 2012-2020 Kris Jusiak (kris at jusiak dot net) // // 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 "boost/di/extension/providers/runtime_provider.hpp" #include <cassert> #include <string> namespace di = boost::di; struct i1 { virtual ~i1() noexcept = default; virtual int foo() const = 0; }; struct i2 { virtual ~i2() noexcept = default; virtual int bar() const = 0; }; struct i3 { virtual ~i3() noexcept = default; virtual int f() const = 0; }; struct i4 { virtual ~i4() noexcept = default; virtual int foo() const = 0; }; struct impl3 : i3 { explicit impl3(const int& i) { assert(i == 87); } int f() const override { return 1234; } }; struct impl2 : i2 { explicit impl2(i3& i, std::string str) { assert(i.f() == 1234); assert(str == "text"); } int bar() const override { return 99; } }; struct impl1 : i1 { explicit impl1(std::unique_ptr<i2> sp2) { assert(sp2->bar() == 99); } int foo() const override { return 42; } }; class ctor; class dtor; struct impl4 : i4 { template <class> static auto& calls() { static auto i = 0; return i; } impl4() { ++calls<ctor>(); } ~impl4() { ++calls<dtor>(); } int foo() const override { return 100; } }; class module_example { public: explicit module_example(std::shared_ptr<i4> sp) : sp{sp} {} auto get() const { return sp->foo() * 2; } private: std::shared_ptr<i4> sp{}; }; struct example { example(std::shared_ptr<i1> sp, int i, module_example& me) { assert(dynamic_cast<impl1*>(sp.get())); assert(sp->foo() == 42); assert(i == 87); assert(me.get() == 2 * 100); } }; auto ct_module = [] { return di::make_injector(di::bind<i4>().to<impl4>()); }; di::extension::runtime_injector rt_module() { return di::make_injector(di::bind<i4>().to<impl4>()); } int main() { // clang-format off namespace di = boost::di; /*<<create runtime injector>>*/ di::extension::runtime_injector injector{}; /*<<install bindings>>*/ injector.install( di::bind<i1>().to<impl1>(), di::bind<i2>().to<impl2>() ); /*<<more bindings>>*/ injector.install(di::bind<int>().to(87)); /*<<injector bindings>>*/ auto component = di::make_injector( di::bind<i3>().to<impl3>(), di::bind<std::string>().to("text") ); injector.install(component); /*<<module bindings>>*/ injector.install(ct_module()); /*<<create example>>*/ injector.create<example>(); // scoped injector { impl4::calls<ctor>() = {}; impl4::calls<dtor>() = {}; di::extension::runtime_injector injector{}; injector.install(rt_module()); auto m = di::create<module_example>(injector); assert(m.get() == 2 * 100); assert(impl4::calls<ctor>() == 1); assert(impl4::calls<dtor>() == 0); } assert(impl4::calls<ctor>() == 1); assert(impl4::calls<dtor>() == 1); // clang-format on }
#include <stdio.h> #include <stack> using namespace std; int main(void){ int n, p, cnt = 0; stack<int> s[7]; scanf("%d %d", &n, &p); for(int i=0;i<n;i++){ int a, b; scanf("%d %d", &a, &b); L:; if(s[a].empty() || s[a].top() < b){ s[a].push(b); cnt++; }else if(s[a].top() > b){ s[a].pop(); cnt++; goto L; } } printf("%d", cnt); return 0; }
#include "oniguruma.h" // Must be first. #include "transcoder.h" #include "regenc.h" #include "builtin/string.hpp" #include "builtin/array.hpp" #include "builtin/bytearray.hpp" #include "builtin/class.hpp" #include "builtin/encoding.hpp" #include "builtin/exception.hpp" #include "builtin/fixnum.hpp" #include "builtin/float.hpp" #include "builtin/integer.hpp" #include "builtin/regexp.hpp" #include "builtin/symbol.hpp" #include "builtin/tuple.hpp" #include "util/murmur_hash3.hpp" #include "configuration.hpp" #include "vm.hpp" #include "object_utils.hpp" #include "objectmemory.hpp" #include "primitives.hpp" #include "windows_compat.h" #include "ontology.hpp" #include "capi/handle.hpp" #include "builtin/nativemethod.hpp" #include <gdtoa.h> #include <unistd.h> #include <string.h> #include <iostream> #include <ctype.h> #include <stdint.h> #include <sstream> namespace rubinius { void String::init(STATE) { GO(string).set(ontology::new_class(state, "String", G(object))); G(string)->set_object_type(state, StringType); } /* Creates a String instance with +num_bytes+ == +size+ and * having a ByteArray with at least (size + 1) bytes. */ String* String::create(STATE, Fixnum* size) { String *so; so = state->new_object<String>(G(string)); so->num_bytes(state, size); so->hash_value(state, nil<Fixnum>()); so->shared(state, cFalse); native_int bytes = size->to_native() + 1; ByteArray* ba = ByteArray::create(state, bytes); ba->raw_bytes()[bytes-1] = 0; so->data(state, ba); return so; } String* String::create_reserved(STATE, native_int bytes) { String *so; so = state->new_object<String>(G(string)); so->num_bytes(state, Fixnum::from(0)); so->hash_value(state, nil<Fixnum>()); so->shared(state, cFalse); ByteArray* ba = ByteArray::create(state, bytes+1); ba->raw_bytes()[bytes] = 0; so->data(state, ba); return so; } /* * Creates a String instance with +num_bytes+ bytes of storage. * It also pins the ByteArray used for storage, so it can be passed * to an external function (like ::read) */ String* String::create_pinned(STATE, Fixnum* size) { String *so; so = state->new_object<String>(G(string)); so->num_bytes(state, size); so->hash_value(state, nil<Fixnum>()); so->shared(state, cFalse); native_int bytes = size->to_native() + 1; ByteArray* ba = ByteArray::create_pinned(state, bytes); ba->raw_bytes()[bytes-1] = 0; so->data(state, ba); return so; } /* +bytes+ should NOT attempt to take the trailing null into account * +bytes+ is the number of 'real' characters in the string */ String* String::create(STATE, const char* str) { if(!str) return String::create(state, Fixnum::from(0)); native_int bytes = strlen(str); return String::create(state, str, bytes); } /* +bytes+ should NOT attempt to take the trailing null into account * +bytes+ is the number of 'real' characters in the string */ String* String::create(STATE, const char* str, native_int bytes) { String* so = String::create(state, Fixnum::from(bytes)); if(str) memcpy(so->byte_address(), str, bytes); return so; } String* String::from_bytearray(STATE, ByteArray* ba, native_int size) { String* s = state->new_object<String>(G(string)); s->num_bytes(state, Fixnum::from(size)); s->hash_value(state, nil<Fixnum>()); s->shared(state, cFalse); s->data(state, ba); return s; } String* String::from_bytearray(STATE, ByteArray* ba, Fixnum* start, Fixnum* count) { String* s = state->new_object<String>(G(string)); s->num_bytes(state, count); s->hash_value(state, nil<Fixnum>()); s->shared(state, cFalse); // fetch_bytes NULL terminates s->data(state, ba->fetch_bytes(state, start, count)); return s; } void String::update_handle() { if(!inflated_header_p()) return; capi::Handle* handle = inflated_header()->handle(); if(!handle) return; handle->update(NativeMethodEnvironment::get()); } static bool byte_compatible_p(Encoding* enc) { return enc->nil_p() || ONIGENC_MBC_MAXLEN(enc->get_encoding()) == 1; } static bool fixed_width_p(Encoding* enc) { if(enc->nil_p()) return true; OnigEncodingType* e = enc->get_encoding(); return ONIGENC_MBC_MAXLEN(e) == ONIGENC_MBC_MINLEN(e); } static const uint8_t* find_non_ascii(const uint8_t* data, int num) { for(int i = 0; i < num; i++) { if(!ISASCII(data[i])) { return data + i; } } return 0; } static int mbclen(const uint8_t* p, const uint8_t* e, OnigEncodingType* enc) { int n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e); if (ONIGENC_MBCLEN_CHARFOUND_P(n) && ONIGENC_MBCLEN_CHARFOUND_LEN(n) <= e-p) { return ONIGENC_MBCLEN_CHARFOUND_LEN(n); } else { int min = ONIGENC_MBC_MINLEN(enc); return min <= e-p ? min : (int)(e-p); } } static int precise_mbclen(const uint8_t* p, const uint8_t* e, OnigEncodingType* enc) { int n; if (e <= p) { return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(1); } n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e); if (e-p < n) { return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(n-(int)(e-p)); } return n; } static void invalid_codepoint_error(STATE, unsigned int c) { std::ostringstream msg; msg << "invalid codepoint: " << c; Exception::range_error(state, msg.str().c_str()); } struct convert_escaped_state { #define CONVERT_BUFSIZE 6 STATE; String* str; OnigEncodingType* enc; bool ascii; bool utf8; ByteArray* ba; uint8_t* bp; uint8_t* be; uint8_t* p; uint8_t* e; uint8_t* lp; uint8_t buf[CONVERT_BUFSIZE]; convert_escaped_state(STATE, String* str) : state(state) , str(str) , enc(0) , ascii(true) , utf8(false) , ba(0) , bp(0) , be(0) { p = str->byte_address(); e = p + str->byte_size(); lp = p; buf[0] = 0; } void update_index(int delta=0) { lp = p + delta; } void new_bytes(int len) { ba = ByteArray::create(state, len); bp = ba->raw_bytes(); be = bp + ba->size(); } void expand_bytes(int len) { ByteArray* old_ba = ba; uint8_t* old_bp = bp; new_bytes(old_ba->size() + len); memcpy(ba->raw_bytes(), old_ba->raw_bytes(), old_ba->size()); bp = ba->raw_bytes() + (old_bp - old_ba->raw_bytes()); } void copy_bytes(int delta=0) { if(!ba) new_bytes(str->byte_size()); int len = (p + delta) - lp; if(len > 0) { if(len > be - bp) { expand_bytes(len); } memcpy(bp, lp, len); bp += len; } update_index(delta); } void append_bytes(uint8_t* ptr, int len) { if(len > be - bp) { expand_bytes(len); } memcpy(bp, ptr, len); bp += len; } void append_utf8(int value) { if(value < 128) { int n = snprintf(reinterpret_cast<char*>(buf), CONVERT_BUFSIZE, "\\x%02X", value); append_bytes(buf, n); } else { if(!utf8) { ascii = false; utf8 = true; enc = Encoding::utf8_encoding(state)->get_encoding(); } int n = ONIGENC_CODE_TO_MBCLEN(enc, value); if(n <= 0) invalid_codepoint_error(state, value); n = ONIGENC_CODE_TO_MBC(enc, value, (UChar*)bp); if(n <= 0) invalid_codepoint_error(state, value); bp += n; } } int convert_ctrl(bool ctrl=false, bool meta=false) { if(ctrl) raise_error("duplicate control escape"); if(p == e) raise_error("control escape is too short"); if((*p & 0x80) == 0) { int value = *p++; if(value == '\\') { value = convert_byte(true, meta); } return value &= 0x1f; } raise_error("invalid control escape"); // not reached return 0; } int convert_meta(bool ctrl=false, bool meta=false) { if(meta) raise_error("duplicate meta escape"); if(p == e) raise_error("meta escape is too short"); if((*p & 0x80) == 0) { int value = *p++; if(value == '\\') { value = convert_byte(true, meta); } return value |= 0x80; } raise_error("invalid meta escape"); // not reached return 0; } int convert_byte(bool ctrl=false, bool meta=false) { if(p == e || *p++ != '\\') { raise_error("escape multibyte character is too short"); } switch(*p++) { case '\\': return '\\'; case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'v': return '\013'; case 'a': return '\007'; case 'e': return '\033'; /* \OOO */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': p--; return convert_octal(); case 'x': /* \xHH */ return convert_hex(1, 2); case 'M': /* \M-X, \M-\C-X, \M-\cX */ if(p == e || *p++ != '-') { raise_error("meta escape is too short"); } return convert_meta(ctrl); case 'C': /* \C-X, \C-\M-X */ if (p == e || *p++ != '-') { raise_error("control escape is too short"); } // fall through case 'c': /* \cX, \c\M-X */ return convert_ctrl(meta); default: raise_error("unexpected escape sequence"); } // not reached return 0; } void convert_nonascii() { int maxlen = ONIGENC_MBC_MAXLEN(enc); int i = 0; int n = 0; do { buf[i++] = convert_byte(); n = precise_mbclen(buf, buf + i, enc); } while(p < e && i < maxlen && ONIGENC_MBCLEN_NEEDMORE_P(n)); n = precise_mbclen(buf, buf + i, enc); if(ONIGENC_MBCLEN_INVALID_P(n)) { raise_error("invalid multibyte escape"); } else if(i > 1 || (*buf & 0x80)) { if(i == 1 && utf8) { raise_error("escaped non-ASCII character in UTF-8 Regexp"); } ascii = false; append_bytes(buf, n); } else { int n = snprintf(reinterpret_cast<char*>(buf), CONVERT_BUFSIZE, "\\x%02X", *buf); append_bytes(buf, n); } } int convert_octal() { int value = 0; for(int i = 0; p < e && i < 3 && *p >= '0' && *p <= '7'; i++, p++) { value <<= 3; value |= *p - '0'; } return value; } int convert_hex(int min, int max) { int value = 0; int i = 0; for(uint8_t d = *p; p < e && i < max; d = *++p, i++) { if(d >= '0' && d <= '9') { d -= '0'; } else if(d >= 'A' && d <= 'F') { d -= 'A'; d += 10; } else if(d >= 'a' && d <= 'f') { d -= 'a'; d += 10; } else { break; } value <<= 4; value += d; } if(i < min) { raise_error("hexadecimal number is too short"); } return value; } void raise_error(const char* reason) { std::ostringstream msg; msg << reason << ": byte: " << p - str->byte_address() << ": " << str->c_str(state); Exception::regexp_error(state, msg.str().c_str()); } String* finalize() { if(ba) { copy_bytes(); str = String::from_bytearray(state, ba, bp - ba->raw_bytes()); } return str; } }; String* String::convert_escaped(STATE, Encoding*& enc, bool& fixed_encoding) { struct convert_escaped_state ces(state, this); if(!fixed_encoding && !enc) { enc = Encoding::ascii8bit_encoding(state); } else if(enc == Encoding::utf8_encoding(state)) { ces.utf8 = true; } else if(enc == Encoding::usascii_encoding(state)) { enc = Encoding::ascii8bit_encoding(state); } ces.enc = enc->get_encoding(); while(ces.p < ces.e) { int n = precise_mbclen(ces.p, ces.e, ces.enc); if(!ONIGENC_MBCLEN_CHARFOUND_P(n)) { ces.raise_error("invalid multibyte character"); } n = ONIGENC_MBCLEN_CHARFOUND_LEN(n); if(n > 1 || (*ces.p & 0x80)) { if(n == 1 && ces.utf8) { ces.raise_error("non-ASCII character in UTF-8 Regexp"); } ces.ascii = false; ces.p += n; continue; } if(*ces.p++ == '\\') { if(ces.p == ces.e) { ces.raise_error("escape sequence is too short"); } switch(*ces.p++) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': { // \O, \OO, \OOO or backref uint8_t* sp = ces.p--; if(ces.convert_octal() < 128) { continue; } else { ces.p = sp; } // fall through } case '0': // \0, \0O, \0OO case 'x': // \xHH case 'C': // \C-X, \C-\M-X case 'c': // \cX, \c\M-X case 'M': // \M-X, \M-\C-X, \M-\cX ces.p -= 2; ces.copy_bytes(); ces.convert_nonascii(); ces.update_index(); break; case 'u': if (ces.p == ces.e) { ces.raise_error("escape sequence is too short"); } ces.copy_bytes(-2); if (*ces.p == '{') { // \u{H HH HHH HHHH HHHHH HHHHHH ...} ces.p++; int value = -1; while(ces.p < ces.e) { if(ISSPACE(*ces.p)) continue; value = ces.convert_hex(1, 6); if(*ces.p != '}' && !ISSPACE(*ces.p)) { ces.raise_error("invalid Unicode list"); } ces.append_utf8(value); if(*ces.p == '}') break; } if(ces.p == ces.e || *ces.p++ != '}' || value < 0) { ces.raise_error("invalid Unicode list"); } } else { // \uHHHH ces.append_utf8(ces.convert_hex(4, 4)); } ces.update_index(); break; case 'p': /* \p{Hiragana} */ case 'P': /* TODO if (!*encp) { *has_property = 1; } */ break; default: // \n, \\, \d, \9, etc. break; } } } String* str = ces.finalize(); if(!fixed_encoding) { if(ces.utf8) { if(CBOOL(str->ascii_only_p(state))) { enc = Encoding::usascii_encoding(state); } else { enc = Encoding::utf8_encoding(state); fixed_encoding = true; } } else if(ces.ascii || CBOOL(str->ascii_only_p(state))) { enc = Encoding::usascii_encoding(state); } } return str; } native_int String::char_size(STATE) { if(num_chars_->nil_p()) { if(LANGUAGE_18_ENABLED(state)) { num_chars(state, num_bytes_); } else { if(byte_compatible_p(encoding_)) { num_chars(state, num_bytes_); } else { OnigEncodingType* enc = encoding_->get_encoding(); native_int chars; if(fixed_width_p(encoding_)) { chars = (byte_size() + ONIGENC_MBC_MINLEN(enc) - 1) / ONIGENC_MBC_MINLEN(enc); } else { uint8_t* p = byte_address(); uint8_t* e = p + byte_size(); for(chars = 0; p < e; chars++) { int n = precise_mbclen(p, e, enc); if(ONIGENC_MBCLEN_CHARFOUND_P(n)) { p += ONIGENC_MBCLEN_CHARFOUND_LEN(n); } else if(p + ONIGENC_MBC_MINLEN(enc) <= e) { p += ONIGENC_MBC_MINLEN(enc); } else { p = e; } } } num_chars(state, Fixnum::from(chars)); } } } return num_chars_->to_native(); } Fixnum* String::size(STATE) { return Fixnum::from(char_size(state)); } Encoding* String::encoding(STATE) { if(encoding_->nil_p()) { encoding(state, Encoding::usascii_encoding(state)); } return encoding_; } hashval String::hash_string(STATE) { if(!hash_value_->nil_p()) { return (hashval)as<Fixnum>(hash_value_)->to_native(); } unsigned char* bp = (unsigned char*)(byte_address()); hashval h = hash_str(state, bp, byte_size()); hash_value(state, Fixnum::from(h)); return h; } hashval String::hash_str(const unsigned char *bp, unsigned int sz, uint32_t seed) { #ifdef IS_X8664 hashval hv[2]; MurmurHash3_x64_128(bp, sz, seed, hv); #else hashval hv[1]; MurmurHash3_x86_32(bp, sz, seed, hv); #endif return hv[0] & FIXNUM_MAX; } Symbol* String::to_sym(STATE) { return state->symbol(this); } const char* String::c_str(STATE) { char* c_string = (char*)byte_address(); native_int current_size = byte_size(); /* * Oh Oh... String's don't need to be \0 terminated.. * The problem here is that that means we can't just * set \0 on the c_string[size()] element since that means * we might write outside the ByteArray storage allocated for this! * * Therefore we need to guard this case just in case so we don't * put the VM in a state with corrupted memory. */ if(current_size >= as<ByteArray>(data_)->size()) { ByteArray* ba = ByteArray::create(state, current_size + 1); memcpy(ba->raw_bytes(), byte_address(), current_size); data(state, ba); if(shared_ == cTrue) shared(state, cFalse); // We need to read it again since we have a new ByteArray c_string = (char*)byte_address(); c_string[current_size] = 0; } if(c_string[current_size] != 0) { unshare(state); // Read it again because unshare might change it. c_string = (char*)byte_address(); c_string[current_size] = 0; } return c_string; } const char* String::c_str_null_safe(STATE) { const char* str = c_str(state); if(byte_size() > (native_int) strlen(str)) { Exception::argument_error(state, "string contains NULL byte"); } return str; } Object* String::secure_compare(STATE, String* other) { native_int s1 = num_bytes()->to_native(); native_int s2 = other->num_bytes()->to_native(); native_int d1 = as<ByteArray>(data_)->size(); native_int d2 = as<ByteArray>(other->data_)->size(); if(unlikely(s1 > d1)) { s1 = d1; } if(unlikely(s2 > d2)) { s2 = d2; } native_int max = (s2 > s1) ? s2 : s1; uint8_t* p1 = byte_address(); uint8_t* p2 = other->byte_address(); uint8_t* p1max = p1 + s1; uint8_t* p2max = p2 + s2; uint8_t sum = 0; for(native_int i = 0; i < max; i++) { uint8_t* c1 = p1 + i; uint8_t* c2 = p2 + i; uint8_t b1 = (c1 >= p1max) ? 0 : *c1; uint8_t b2 = (c2 >= p2max) ? 0 : *c2; sum |= (b1 ^ b2); } return (sum == 0) ? cTrue : cFalse; } String* String::string_dup(STATE) { Module* mod = klass_; Class* cls = try_as_instance<Class>(mod); if(unlikely(!cls)) { while(!cls) { mod = mod->superclass(); if(mod->nil_p()) rubinius::bug("Object::class_object() failed to find a class"); cls = try_as_instance<Class>(mod); } } String* so = state->new_object<String>(cls); infect(state, so); so->num_bytes(state, num_bytes()); so->data(state, data()); so->hash_value(state, hash_value()); so->encoding(state, encoding()); so->valid_encoding(state, valid_encoding()); so->ascii_only(state, ascii_only()); so->shared(state, cTrue); shared(state, cTrue); return so; } void String::unshare(STATE) { if(shared_ == cTrue) { if(data_->reference_p()) { data(state, as<ByteArray>(data_->duplicate(state))); } shared(state, cFalse); } } String* String::append(STATE, String* other) { // Clamp the length of the other string to the maximum byte array size native_int length = other->byte_size(); native_int data_length = as<ByteArray>(other->data_)->size(); if(unlikely(length > data_length)) { length = data_length; } return append(state, reinterpret_cast<const char*>(other->byte_address()), length); } String* String::append(STATE, const char* other) { return append(state, other, strlen(other)); } String* String::append(STATE, const char* other, native_int length) { native_int current_size = byte_size(); native_int data_size = as<ByteArray>(data_)->size(); // Clamp the string size the maximum underlying byte array size if(unlikely(current_size > data_size)) { current_size = data_size; } native_int new_size = current_size + length; native_int capacity = data_size; if(capacity < new_size + 1) { // capacity needs one extra byte of room for the trailing null do { // @todo growth should be more intelligent than doubling capacity *= 2; } while(capacity < new_size + 1); // No need to call unshare and duplicate a ByteArray // just to throw it away. if(shared_ == cTrue) shared(state, cFalse); ByteArray* ba = ByteArray::create(state, capacity); memcpy(ba->raw_bytes(), byte_address(), current_size); data(state, ba); } else { if(shared_ == cTrue) unshare(state); } // Append on top of the null byte at the end of s1, not after it memcpy(byte_address() + current_size, other, length); // The 0-based index of the last character is new_size - 1 byte_address()[new_size] = 0; num_bytes(state, Fixnum::from(new_size)); num_chars(state, nil<Fixnum>()); hash_value(state, nil<Fixnum>()); return this; } String* String::resize_capacity(STATE, Fixnum* count) { native_int sz = count->to_native(); if(sz < 0) { Exception::argument_error(state, "negative byte array size"); } else if(sz >= INT32_MAX) { // >= is used deliberately because we use a size of + 1 // for the byte array Exception::argument_error(state, "too large byte array size"); } ByteArray* ba = ByteArray::create(state, sz + 1); native_int copy_size = sz; native_int data_size = as<ByteArray>(data_)->size(); // Check that we don't copy any data outside the existing byte array if(unlikely(copy_size > data_size)) { copy_size = data_size; } memcpy(ba->raw_bytes(), byte_address(), copy_size); // We've unshared shared(state, cFalse); data(state, ba); hash_value(state, nil<Fixnum>()); // If we shrunk it and num_bytes said there was more than there // is, clamp it. if(num_bytes()->to_native() > sz) { num_bytes(state, count); num_chars(state, nil<Fixnum>()); } return this; } String* String::add(STATE, String* other) { return string_dup(state)->append(state, other); } String* String::add(STATE, const char* other) { return string_dup(state)->append(state, other); } Float* String::to_f(STATE) { return Float::create(state, to_double(state)); } double String::to_double(STATE) { double value; char *ba = data_->to_chars(state, num_bytes_); char *p, *n, *rest; int e_seen = 0; p = ba; while(ISSPACE(*p)) p++; n = p; while(*p) { if(*p == '_') { p++; } else { if(*p == 'e' || *p == 'E') { if(e_seen) { *n = 0; break; } e_seen = 1; } else if(!(ISDIGIT(*p) || *p == '.' || *p == '-' || *p == '+')) { *n = 0; break; } *n++ = *p++; } } *n = 0; value = ruby_strtod(ba, &rest); free(ba); return value; } // Character-wise logical AND of two strings. Modifies the receiver. String* String::apply_and(STATE, String* other) { native_int count; if(num_bytes_ > other->num_bytes()) { count = other->num_bytes()->to_native(); } else { count = num_bytes_->to_native(); } uint8_t* s = byte_address(); uint8_t* o = other->byte_address(); // Use && not & to keep 1's in the table. for(native_int i = 0; i < count; i++) { s[i] = s[i] && o[i]; } return this; } struct tr_data { uint8_t tr[256]; native_int set[256]; native_int steps; native_int last; native_int limit; bool assign(native_int chr) { int j, i = set[chr]; if(limit >= 0 && steps >= limit) return true; if(i < 0) { tr[last] = chr; } else { last--; for(j = i + 1; j <= last; j++) { set[tr[j]]--; tr[j-1] = tr[j]; } tr[last] = chr; } set[chr] = last++; steps++; return false; } }; Fixnum* String::tr_expand(STATE, Object* limit, Object* invalid_as_empty) { struct tr_data tr_data; tr_data.last = 0; tr_data.steps = 0; if(Fixnum* lim = try_as<Fixnum>(limit)) { tr_data.limit = lim->to_native(); } else { tr_data.limit = -1; } uint8_t* str = byte_address(); native_int bytes = byte_size(); native_int start = bytes > 1 && str[0] == '^' ? 1 : 0; memset(tr_data.set, -1, sizeof(native_int) * 256); for(native_int i = start; i < bytes;) { native_int chr = str[i]; native_int seq = ++i < bytes ? str[i] : -1; if(chr == '\\' && seq >= 0) { continue; } else if(seq == '-') { native_int max = ++i < bytes ? str[i] : -1; if(max >= 0 && chr > max && CBOOL(invalid_as_empty)) { i++; } else if(max >= 0) { do { if(tr_data.assign(chr)) return tr_replace(state, &tr_data); chr++; } while(chr <= max); i++; } else { if(tr_data.assign(chr)) return tr_replace(state, &tr_data); if(tr_data.assign(seq)) return tr_replace(state, &tr_data); } } else { if(tr_data.assign(chr)) return tr_replace(state, &tr_data); } } return tr_replace(state, &tr_data); } Fixnum* String::tr_replace(STATE, struct tr_data* tr_data) { if(tr_data->last + 1 > byte_size() || shared_->true_p()) { ByteArray* ba = ByteArray::create(state, tr_data->last + 1); data(state, ba); shared(state, cFalse); } memcpy(byte_address(), tr_data->tr, tr_data->last); byte_address()[tr_data->last] = 0; num_bytes(state, Fixnum::from(tr_data->last)); num_chars(state, nil<Fixnum>()); return Fixnum::from(tr_data->steps); } String* String::transform(STATE, Tuple* tbl, Object* respect_kcode) { uint8_t invalid[5]; if(tbl->num_fields() < 256) { return force_as<String>(Primitives::failure()); } Object** tbl_ptr = tbl->field; kcode::table* kcode_tbl = 0; if(CBOOL(respect_kcode)) { kcode_tbl = state->shared().kcode_table(); } else { kcode_tbl = kcode::null_table(); } // Pointers to iterate input bytes. uint8_t* in_p = byte_address(); native_int str_size = byte_size(); native_int data_size = as<ByteArray>(data_)->size(); if(unlikely(str_size > data_size)) { str_size = data_size; } uint8_t* in_end = in_p + str_size; // Optimistic estimate that output size will be 1.25 x input. native_int out_chunk = str_size * 5 / 4; native_int out_size = out_chunk; uint8_t* output = (uint8_t*)malloc(out_size); uint8_t* out_p = output; uint8_t* out_end = out_p + out_size; while(in_p < in_end) { native_int len = 0; uint8_t byte = *in_p; uint8_t* cur_p = 0; if(kcode::mbchar_p(kcode_tbl, byte)) { len = kcode::mbclen(kcode_tbl, byte); native_int rem = in_end - in_p; // if the character length is greater than the remaining // bytes, we have a malformed character. Handled below. if(rem >= len) { cur_p = in_p; in_p += len; } } else if(String* str = try_as<String>(tbl_ptr[byte])) { cur_p = str->byte_address(); len = str->byte_size(); in_p++; } else { Tuple* tbl = as<Tuple>(tbl_ptr[byte]); for(native_int i = 0; i < tbl->num_fields(); i += 2) { String* key = as<String>(tbl->at(i)); native_int rem = in_end - in_p; native_int klen = key->byte_size(); if(rem < klen) continue; if(memcmp(in_p, key->byte_address(), klen) == 0) { String* str = as<String>(tbl->at(i+1)); cur_p = str->byte_address(); len = str->byte_size(); in_p += klen; break; } } } // We could not map this byte, so we add it to the output // in stringified octal notation (ie \nnn). if(!cur_p) { snprintf((char*)invalid, 5, "\\%03o", *((char*)in_p) & 0377); in_p++; cur_p = invalid; len = 4; } if(out_p + len > out_end) { native_int pos = out_p - output; out_size += (len > out_chunk ? len : out_chunk); output = (uint8_t*)realloc(output, out_size); out_p = output + pos; out_end = output + out_size; } switch(len) { case 1: *out_p++ = *cur_p; break; case 2: *out_p++ = *cur_p++; *out_p++ = *cur_p; break; case 3: *out_p++ = *cur_p++; *out_p++ = *cur_p++; *out_p++ = *cur_p; break; default: memcpy(out_p, cur_p, len); out_p += len; break; } } String* result = String::create(state, reinterpret_cast<const char*>(output), out_p - output); free(output); infect(state, result); return result; } String* String::copy_from(STATE, String* other, Fixnum* start, Fixnum* size, Fixnum* dest) { native_int src = start->to_native(); native_int dst = dest->to_native(); native_int cnt = size->to_native(); native_int osz = other->byte_size(); if(src >= osz) return this; if(cnt < 0) return this; if(src < 0) src = 0; if(cnt > osz - src) cnt = osz - src; // This bounds checks on the total capacity rather than the virtual // size() of the String. This allows for string adjustment within // the capacity without having to change the virtual size first. native_int sz = as<ByteArray>(data_)->size(); if(dst >= sz) return this; if(dst < 0) dst = 0; if(cnt > sz - dst) cnt = sz - dst; memmove(byte_address() + dst, other->byte_address() + src, cnt); return this; } Fixnum* String::compare_substring(STATE, String* other, Fixnum* start, Fixnum* size) { native_int src = start->to_native(); native_int cnt = size->to_native(); native_int sz = byte_size(); native_int osz = other->byte_size(); native_int dsz = as<ByteArray>(data_)->size(); native_int odsz = as<ByteArray>(other->data_)->size(); if(unlikely(sz > dsz)) { sz = dsz; } if(unlikely(osz > odsz)) { osz = odsz; } if(src < 0) src = osz + src; if(src >= osz) { Exception::object_bounds_exceeded_error(state, "start exceeds size of other"); } else if(src < 0) { Exception::object_bounds_exceeded_error(state, "start less than zero"); } if(src + cnt > osz) cnt = osz - src; if(cnt > sz) cnt = sz; native_int cmp = memcmp(byte_address(), other->byte_address() + src, cnt); if(cmp < 0) { return Fixnum::from(-1); } else if(cmp > 0) { return Fixnum::from(1); } else { return Fixnum::from(0); } } String* String::pattern(STATE, Object* self, Fixnum* size, Object* pattern) { if(!size->positive_p()) { Exception::argument_error(state, "size must be positive"); } String* s = String::create(state, size); s->klass(state, (Class*)self); self->infect(state, s); native_int cnt = size->to_native(); if(Fixnum* chr = try_as<Fixnum>(pattern)) { memset(s->byte_address(), (int)chr->to_native(), cnt); } else if(String* pat = try_as<String>(pattern)) { pat->infect(state, s); native_int psz = pat->byte_size(); if(psz == 1) { memset(s->byte_address(), pat->byte_address()[0], cnt); } else if(psz > 1) { native_int i, j, n; native_int sz = cnt / psz; for(n = i = 0; i < sz; i++) { for(j = 0; j < psz; j++, n++) { s->byte_address()[n] = pat->byte_address()[j]; } } for(i = n, j = 0; i < cnt; i++, j++) { s->byte_address()[i] = pat->byte_address()[j]; } } } else { Exception::argument_error(state, "pattern must be a Fixnum or String"); } return s; } String* String::from_codepoint(STATE, Object* self, Integer* code, Encoding* enc) { String* s = state->new_object<String>(G(string)); unsigned int c = code->to_uint(); int n = ONIGENC_CODE_TO_MBCLEN(enc->get_encoding(), c); if(n <= 0) invalid_codepoint_error(state, c); s->num_bytes(state, Fixnum::from(n)); s->hash_value(state, nil<Fixnum>()); s->shared(state, cFalse); s->encoding(state, enc); ByteArray* ba = ByteArray::create(state, n); n = ONIGENC_CODE_TO_MBC(enc->get_encoding(), c, (UChar*)ba->raw_bytes()); if(n <= 0) invalid_codepoint_error(state, c); s->data(state, ba); return s; } String* String::crypt(STATE, String* salt) { return String::create(state, ::crypt(this->c_str(state), salt->c_str(state))); } Integer* String::to_i(STATE, Fixnum* fix_base, Object* strict) { const char* str = c_str(state); int base = fix_base->to_native(); if(strict == cTrue) { // In strict mode the string can't have null bytes. if(byte_size() > (native_int)strlen(str)) return nil<Integer>(); } return Integer::from_cstr(state, str, base, strict); } Integer* String::to_inum_prim(STATE, Fixnum* base, Object* strict) { Integer* val = to_i(state, base, strict); if(val->nil_p()) return (Integer*)Primitives::failure(); return val; } Object* String::aref(STATE, Fixnum* index) { native_int i = index->to_native(); if(i < 0) i += byte_size(); if(i >= byte_size() || i < 0) return cNil; if(LANGUAGE_18_ENABLED(state)) { return Fixnum::from(byte_address()[i]); } if(byte_compatible_p(encoding_)) { return byte_substring(state, i, 1); } else { // Assumptions above about size are possibly invalid, recalculate. i = index->to_native(); if(i < 0) i += char_size(state); if(i >= char_size(state) || i < 0) return cNil; return char_substring(state, i, 1); } } /* Returns the byte index of the character at logical 'index'. The 'start' * parameter is the byte index of a character at which to start searching. */ native_int String::find_character_byte_index(STATE, native_int index, native_int start) { if(byte_compatible_p(encoding_)) { return index; } else if(fixed_width_p(encoding_)) { return index * ONIGENC_MBC_MINLEN(encoding_->get_encoding()); } else { OnigEncodingType* enc = encoding_->get_encoding(); uint8_t* p = byte_address() + start; uint8_t* e = byte_address() + byte_size(); while(p < e && index--) { p += mbclen(p, e, enc); } if(p > e) p = e; return p - byte_address(); } } /* The 'index' and 'length' parameters are byte based. This method is a * worker method called from other methods that have already computed the * canonical byte (0 <= index < byte_size) and (0 <= length < byte_size). */ String* String::byte_substring(STATE, native_int index, native_int length) { native_int data_size = as<ByteArray>(data_)->size(); // Clamp the range to the underlying byte array size if(unlikely(index > data_size)) index = data_size; if(unlikely(index + length > data_size)) { length = data_size - index; } String* sub = String::create(state, Fixnum::from(length)); sub->klass(state, class_object(state)); uint8_t* buf = byte_address() + index; memcpy(sub->byte_address(), buf, length); if(tainted_p(state)->true_p()) sub->taint(state); if(untrusted_p(state)->true_p()) sub->untrust(state); sub->encoding(state, encoding()); return sub; } /* The 'index' and 'length' parameters are character based. This method is a * worker method called from other methods that have already computed the * canonical character (0 <= index < char_size) and (0 <= length < char_size). */ String* String::char_substring(STATE, native_int index, native_int length) { native_int i = find_character_byte_index(state, index); native_int e = find_character_byte_index(state, length - 1, i); int c = precise_mbclen(byte_address() + e, byte_address() + byte_size(), encoding_->get_encoding()); if(ONIGENC_MBCLEN_CHARFOUND_P(c)) { e += ONIGENC_MBCLEN_CHARFOUND_LEN(c); } else { e += 1; } return byte_substring(state, i, e - i); } String* String::byte_substring(STATE, Fixnum* index, Fixnum* length) { native_int i = index->to_native(); native_int n = length->to_native(); native_int size = byte_size(); if(n < 0) return nil<String>(); if(i < 0) { i += size; if(i < 0) return nil<String>(); } else if(i > size) { return nil<String>(); } if(i + n > size) { n = size - i; } return byte_substring(state, i, n); } String* String::substring(STATE, Fixnum* index, Fixnum* length) { native_int i = index->to_native(); native_int n = length->to_native(); native_int size; if(n < 0) return nil<String>(); if(byte_compatible_p(encoding_)) { size = byte_size(); } else { size = char_size(state); } if(i < 0) { i += size; if(i < 0) return nil<String>(); } else if(i > size) { return nil<String>(); } if(i + n > size) { n = size - i; } if(n == 0 || byte_compatible_p(encoding_)) { return byte_substring(state, i, n); } else { return char_substring(state, i, n); } } Fixnum* String::index(STATE, String* pattern, Fixnum* start) { native_int total = byte_size(); native_int match_size = pattern->byte_size(); if(start->to_native() < 0) { Exception::argument_error(state, "negative start given"); } switch(match_size) { case 0: return start; case 1: { uint8_t* buf = byte_address(); uint8_t matcher = pattern->byte_address()[0]; for(native_int pos = start->to_native(); pos < total; pos++) { if(buf[pos] == matcher) return Fixnum::from(pos); } } return nil<Fixnum>(); default: { uint8_t* buf = byte_address(); uint8_t* matcher = pattern->byte_address(); uint8_t* last = buf + (total - match_size); uint8_t* pos = buf + start->to_native(); while(pos <= last) { // Checking *pos directly then also checking memcmp is an // optimization. It's about 10x faster than just calling memcmp // everytime. if(*pos == *matcher && memcmp(pos, matcher, match_size) == 0) { return Fixnum::from(pos - buf); } pos++; } } return nil<Fixnum>(); } } Fixnum* String::rindex(STATE, String* pattern, Fixnum* start) { native_int total = byte_size(); native_int match_size = pattern->byte_size(); native_int pos = start->to_native(); if(pos < 0) { Exception::argument_error(state, "negative start given"); } if(pos >= total) pos = total - 1; switch(match_size) { case 0: return start; case 1: { uint8_t* buf = byte_address(); uint8_t matcher = pattern->byte_address()[0]; while(pos >= 0) { if(buf[pos] == matcher) return Fixnum::from(pos); pos--; } } return nil<Fixnum>(); default: { uint8_t* buf = byte_address(); uint8_t* matcher = pattern->byte_address(); if(total - pos < match_size) { pos = total - match_size; } uint8_t* right = buf + pos; uint8_t* cur = right; while(cur >= buf) { if(memcmp(cur, matcher, match_size) == 0) { return Fixnum::from(cur - buf); } cur--; } } return nil<Fixnum>(); } } String* String::find_character(STATE, Fixnum* offset) { native_int o = offset->to_native(); if(o >= byte_size()) return nil<String>(); if(o < 0) return nil<String>(); uint8_t* cur = byte_address() + o; String* output = 0; kcode::table* tbl = state->shared().kcode_table(); if(kcode::mbchar_p(tbl, *cur)) { native_int clen = kcode::mbclen(tbl, *cur); if(o + clen <= byte_size()) { output = String::create(state, reinterpret_cast<const char*>(cur), clen); } } if(!output) { output = String::create(state, reinterpret_cast<const char*>(cur), 1); } output->klass(state, class_object(state)); if(CBOOL(tainted_p(state))) output->taint(state); return output; } Array* String::awk_split(STATE, Fixnum* f_limit) { native_int limit = f_limit->to_native(); native_int sz = byte_size(); uint8_t* start = byte_address(); int end = 0; int begin = 0; native_int i = 0; if(limit > 0) i = 1; bool skip = true; Array* ary = Array::create(state, 3); Class* out_class = class_object(state); int taint = (is_tainted_p() ? 1 : 0); // Algorithm ported from MRI for(uint8_t* ptr = start; ptr < start+sz; ptr++) { if(skip) { if(ISSPACE(*ptr)) { begin++; } else { end = begin + 1; skip = false; if(limit > 0 && limit <= i) break; } } else { if(ISSPACE(*ptr)) { String* str = String::create(state, (const char*)start+begin, end-begin); str->klass(state, out_class); str->set_tainted(taint); ary->append(state, str); skip = true; begin = end + 1; if(limit > 0) i++; } else { end++; } } } int fin_sz = sz-begin; if(fin_sz > 0 || (limit > 0 && i <= limit) || limit < 0) { String* str = String::create(state, (const char*)start+begin, fin_sz); str->klass(state, out_class); str->set_tainted(taint); ary->append(state, str); } return ary; } Object* String::ascii_only_p(STATE) { if(ascii_only_->nil_p()) { if(byte_size() == 0) { ascii_only(state, encoding(state)->ascii_compatible_p(state)); } else { if(!CBOOL(encoding(state)->ascii_compatible_p(state))) { ascii_only(state, cFalse); } else if(find_non_ascii(byte_address(), byte_size())) { ascii_only(state, cFalse); } else { ascii_only(state, cTrue); } } } return ascii_only_; } Object* String::valid_encoding_p(STATE) { if(valid_encoding_->nil_p()) { if(encoding(state) == Encoding::from_index(state, Encoding::eBinary)) { valid_encoding(state, cTrue); return valid_encoding_; } OnigEncodingType* enc = encoding_->get_encoding(); uint8_t* p = byte_address(); uint8_t* e = p + byte_size(); while(p < e) { int n = precise_mbclen(p, e, enc); if(!ONIGENC_MBCLEN_CHARFOUND_P(n)) { valid_encoding(state, cFalse); return valid_encoding_; } p += n; } valid_encoding(state, cTrue); } return valid_encoding_; } Fixnum* String::codepoint(STATE) { if(char_size(state) == 0) return force_as<Fixnum>(Primitives::failure()); if(byte_compatible_p(encoding_)) { return Fixnum::from(byte_address()[0]); } else { OnigEncodingType* enc = encoding_->get_encoding(); uint8_t* p = byte_address(); uint8_t* e = p + byte_size(); int n = precise_mbclen(p, e, enc); if(ONIGENC_MBCLEN_CHARFOUND_P(n)) { return Fixnum::from(ONIGENC_MBC_TO_CODE(enc, (UChar*)p, (UChar*)e)); } } return force_as<Fixnum>(Primitives::failure()); } void String::Info::show(STATE, Object* self, int level) { String* str = as<String>(self); std::cout << "\"" << str->c_str(state) << "\"" << std::endl; } void String::Info::show_simple(STATE, Object* self, int level) { show(state, self, level); } }
#include <stdio.h> #include <component586/lib1.h> int component586_1 () { printf("Hello world!\n"); return 0; }
/* BulletSprite Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/BulletSprite/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SpuGatheringCollisionTask.h" //#define DEBUG_SPU_COLLISION_DETECTION 1 #include "../SpuDoubleBuffer.h" #include "../SpuCollisionTaskProcess.h" #include "../SpuGatheringCollisionDispatcher.h" //for SPU_BATCHSIZE_BROADPHASE_PAIRS #include "bullet/BulletCollision//BroadphaseCollision/btBroadphaseProxy.h" #include "../SpuContactManifoldCollisionAlgorithm.h" #include "bullet/BulletCollision//CollisionDispatch/btCollisionObject.h" #include "SpuContactResult.h" #include "bullet/BulletCollision//CollisionShapes/btOptimizedBvh.h" #include "bullet/BulletCollision//CollisionShapes/btTriangleIndexVertexArray.h" #include "bullet/BulletCollision//CollisionShapes/btSphereShape.h" #include "bullet/BulletCollision//CollisionShapes/btConvexPointCloudShape.h" #include "bullet/BulletCollision//CollisionShapes/btCapsuleShape.h" #include "bullet/BulletCollision//CollisionShapes/btConvexShape.h" #include "bullet/BulletCollision//CollisionShapes/btBvhTriangleMeshShape.h" #include "bullet/BulletCollision//CollisionShapes/btConvexHullShape.h" #include "bullet/BulletCollision//CollisionShapes/btCompoundShape.h" #include "SpuMinkowskiPenetrationDepthSolver.h" //#include "SpuEpaPenetrationDepthSolver.h" #include "bullet/BulletCollision//NarrowPhaseCollision/btGjkPairDetector.h" #include "boxBoxDistance.h" #include "bullet/BulletMultiThreaded/vectormath2bullet.h" #include "SpuCollisionShapes.h" //definition of SpuConvexPolyhedronVertexData #include "bullet/BulletCollision//CollisionDispatch/btBoxBoxDetector.h" #include "bullet/BulletCollision//NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" #include "bullet/BulletCollision//CollisionShapes/btTriangleShape.h" #ifdef __SPU__ ///Software caching from the IBM Cell SDK, it reduces 25% SPU time for our test cases #ifndef USE_LIBSPE2 //#define USE_SOFTWARE_CACHE 1 #endif #endif //__SPU__ int gSkippedCol = 0; int gProcessedCol = 0; //////////////////////////////////////////////// /// software caching #if USE_SOFTWARE_CACHE #include <spu_intrinsics.h> #include <sys/spu_thread.h> #include <sys/spu_event.h> #include <stdint.h> #define SPE_CACHE_NWAY 4 //#define SPE_CACHE_NSETS 32, 16 #define SPE_CACHE_NSETS 8 //#define SPE_CACHELINE_SIZE 512 #define SPE_CACHELINE_SIZE 128 #define SPE_CACHE_SET_TAGID(set) 15 ///make sure that spe_cache.h is below those defines! #include "../Extras/software_cache/cache/include/spe_cache.h" int g_CacheMisses=0; int g_CacheHits=0; #if 0 // Added to allow cache misses and hits to be tracked, change this to 1 to restore unmodified version #define spe_cache_read(ea) _spe_cache_lookup_xfer_wait_(ea, 0, 1) #else #define spe_cache_read(ea) \ ({ \ int set, idx, line, byte; \ _spe_cache_nway_lookup_(ea, set, idx); \ \ if (btUnlikely(idx < 0)) { \ ++g_CacheMisses; \ idx = _spe_cache_miss_(ea, set, -1); \ spu_writech(22, SPE_CACHE_SET_TAGMASK(set)); \ spu_mfcstat(MFC_TAG_UPDATE_ALL); \ } \ else \ { \ ++g_CacheHits; \ } \ line = _spe_cacheline_num_(set, idx); \ byte = _spe_cacheline_byte_offset_(ea); \ (void *) &spe_cache_mem[line + byte]; \ }) #endif #endif // USE_SOFTWARE_CACHE bool gUseEpa = false; #ifdef USE_SN_TUNER #include <LibSN_SPU.h> #endif //USE_SN_TUNER #if defined (__SPU__) && !defined (USE_LIBSPE2) #include <spu_printf.h> #elif defined (USE_LIBSPE2) #define spu_printf(a) #else #define IGNORE_ALIGNMENT 1 #include <stdio.h> #include <stdlib.h> #define spu_printf printf #endif //int gNumConvexPoints0=0; ///Make sure no destructors are called on this memory ATTRIBUTE_ALIGNED16(struct) CollisionTask_LocalStoreMemory { ///This CollisionTask_LocalStoreMemory is mainly used for the SPU version, using explicit DMA ///Other platforms can use other memory programming models. ATTRIBUTE_ALIGNED16(btBroadphasePair gBroadphasePairsBuffer[SPU_BATCHSIZE_BROADPHASE_PAIRS]); DoubleBuffer<unsigned char, MIDPHASE_WORKUNIT_PAGE_SIZE> g_workUnitTaskBuffers; ATTRIBUTE_ALIGNED16(char gSpuContactManifoldAlgoBuffer [sizeof(SpuContactManifoldCollisionAlgorithm)+16]); ATTRIBUTE_ALIGNED16(char gColObj0Buffer [sizeof(btCollisionObject)+16]); ATTRIBUTE_ALIGNED16(char gColObj1Buffer [sizeof(btCollisionObject)+16]); ///we reserve 32bit integer indices, even though they might be 16bit ATTRIBUTE_ALIGNED16(int spuIndices[16]); btPersistentManifold gPersistentManifoldBuffer; CollisionShape_LocalStoreMemory gCollisionShapes[2]; bvhMeshShape_LocalStoreMemory bvhShapeData; ATTRIBUTE_ALIGNED16(SpuConvexPolyhedronVertexData convexVertexData[2]); CompoundShape_LocalStoreMemory compoundShapeData[2]; ///The following pointers might either point into this local store memory, or to the original/other memory locations. ///See SpuFakeDma for implementation of cellDmaSmallGetReadOnly. btCollisionObject* m_lsColObj0Ptr; btCollisionObject* m_lsColObj1Ptr; btBroadphasePair* m_pairsPointer; btPersistentManifold* m_lsManifoldPtr; SpuContactManifoldCollisionAlgorithm* m_lsCollisionAlgorithmPtr; bool needsDmaPutContactManifoldAlgo; btCollisionObject* getColObj0() { return m_lsColObj0Ptr; } btCollisionObject* getColObj1() { return m_lsColObj1Ptr; } btBroadphasePair* getBroadphasePairPtr() { return m_pairsPointer; } SpuContactManifoldCollisionAlgorithm* getlocalCollisionAlgorithm() { return m_lsCollisionAlgorithmPtr; } btPersistentManifold* getContactManifoldPtr() { return m_lsManifoldPtr; } }; #if defined(__CELLOS_LV2__) || defined(USE_LIBSPE2) ATTRIBUTE_ALIGNED16(CollisionTask_LocalStoreMemory gLocalStoreMemory); void* createCollisionLocalStoreMemory() { return &gLocalStoreMemory; } void deleteCollisionLocalStoreMemory() { } #else btAlignedObjectArray<CollisionTask_LocalStoreMemory*> sLocalStorePointers; void* createCollisionLocalStoreMemory() { CollisionTask_LocalStoreMemory* localStore = (CollisionTask_LocalStoreMemory*)btAlignedAlloc( sizeof(CollisionTask_LocalStoreMemory),16); sLocalStorePointers.push_back(localStore); return localStore; } void deleteCollisionLocalStoreMemory() { for (int i=0;i<sLocalStorePointers.size();i++) { btAlignedFree(sLocalStorePointers[i]); } sLocalStorePointers.clear(); } #endif void ProcessSpuConvexConvexCollision(SpuCollisionPairInput* wuInput, CollisionTask_LocalStoreMemory* lsMemPtr, SpuContactResult& spuContacts); SIMD_FORCE_INLINE void small_cache_read(void* buffer, ppu_address_t ea, size_t size) { #if USE_SOFTWARE_CACHE // Check for alignment requirements. We need to make sure the entire request fits within one cache line, // so the first and last bytes should fall on the same cache line btAssert((ea & ~SPE_CACHELINE_MASK) == ((ea + size - 1) & ~SPE_CACHELINE_MASK)); void* ls = spe_cache_read(ea); memcpy(buffer, ls, size); #else stallingUnalignedDmaSmallGet(buffer,ea,size); #endif } SIMD_FORCE_INLINE void small_cache_read_triple( void* ls0, ppu_address_t ea0, void* ls1, ppu_address_t ea1, void* ls2, ppu_address_t ea2, size_t size) { btAssert(size<16); ATTRIBUTE_ALIGNED16(char tmpBuffer0[32]); ATTRIBUTE_ALIGNED16(char tmpBuffer1[32]); ATTRIBUTE_ALIGNED16(char tmpBuffer2[32]); uint32_t i; ///make sure last 4 bits are the same, for cellDmaSmallGet char* localStore0 = (char*)ls0; uint32_t last4BitsOffset = ea0 & 0x0f; char* tmpTarget0 = tmpBuffer0 + last4BitsOffset; #ifdef __SPU__ cellDmaSmallGet(tmpTarget0,ea0,size,DMA_TAG(1),0,0); #else tmpTarget0 = (char*)cellDmaSmallGetReadOnly(tmpTarget0,ea0,size,DMA_TAG(1),0,0); #endif char* localStore1 = (char*)ls1; last4BitsOffset = ea1 & 0x0f; char* tmpTarget1 = tmpBuffer1 + last4BitsOffset; #ifdef __SPU__ cellDmaSmallGet(tmpTarget1,ea1,size,DMA_TAG(1),0,0); #else tmpTarget1 = (char*)cellDmaSmallGetReadOnly(tmpTarget1,ea1,size,DMA_TAG(1),0,0); #endif char* localStore2 = (char*)ls2; last4BitsOffset = ea2 & 0x0f; char* tmpTarget2 = tmpBuffer2 + last4BitsOffset; #ifdef __SPU__ cellDmaSmallGet(tmpTarget2,ea2,size,DMA_TAG(1),0,0); #else tmpTarget2 = (char*)cellDmaSmallGetReadOnly(tmpTarget2,ea2,size,DMA_TAG(1),0,0); #endif cellDmaWaitTagStatusAll( DMA_MASK(1) ); //this is slowish, perhaps memcpy on SPU is smarter? for (i=0; btLikely( i<size );i++) { localStore0[i] = tmpTarget0[i]; localStore1[i] = tmpTarget1[i]; localStore2[i] = tmpTarget2[i]; } } ATTRIBUTE_ALIGNED16(class) spuNodeCallback : public btNodeOverlapCallback { SpuCollisionPairInput* m_wuInput; SpuContactResult& m_spuContacts; CollisionTask_LocalStoreMemory* m_lsMemPtr; ATTRIBUTE_ALIGNED16(btTriangleShape) m_tmpTriangleShape; ATTRIBUTE_ALIGNED16(btVector3 spuTriangleVertices[3]); ATTRIBUTE_ALIGNED16(btScalar spuUnscaledVertex[4]); public: spuNodeCallback(SpuCollisionPairInput* wuInput, CollisionTask_LocalStoreMemory* lsMemPtr,SpuContactResult& spuContacts) : m_wuInput(wuInput), m_spuContacts(spuContacts), m_lsMemPtr(lsMemPtr) { } virtual void processNode(int subPart, int triangleIndex) { ///Create a triangle on the stack, call process collision, with GJK ///DMA the vertices, can benefit from software caching // spu_printf("processNode with triangleIndex %d\n",triangleIndex); if (m_lsMemPtr->bvhShapeData.gIndexMesh.m_indexType == PHY_SHORT) { unsigned short int* indexBasePtr = (unsigned short int*)(m_lsMemPtr->bvhShapeData.gIndexMesh.m_triangleIndexBase+triangleIndex*m_lsMemPtr->bvhShapeData.gIndexMesh.m_triangleIndexStride); ATTRIBUTE_ALIGNED16(unsigned short int tmpIndices[3]); small_cache_read_triple(&tmpIndices[0],(ppu_address_t)&indexBasePtr[0], &tmpIndices[1],(ppu_address_t)&indexBasePtr[1], &tmpIndices[2],(ppu_address_t)&indexBasePtr[2], sizeof(unsigned short int)); m_lsMemPtr->spuIndices[0] = int(tmpIndices[0]); m_lsMemPtr->spuIndices[1] = int(tmpIndices[1]); m_lsMemPtr->spuIndices[2] = int(tmpIndices[2]); } else { unsigned int* indexBasePtr = (unsigned int*)(m_lsMemPtr->bvhShapeData.gIndexMesh.m_triangleIndexBase+triangleIndex*m_lsMemPtr->bvhShapeData.gIndexMesh.m_triangleIndexStride); small_cache_read_triple(&m_lsMemPtr->spuIndices[0],(ppu_address_t)&indexBasePtr[0], &m_lsMemPtr->spuIndices[1],(ppu_address_t)&indexBasePtr[1], &m_lsMemPtr->spuIndices[2],(ppu_address_t)&indexBasePtr[2], sizeof(int)); } // spu_printf("SPU index0=%d ,",spuIndices[0]); // spu_printf("SPU index1=%d ,",spuIndices[1]); // spu_printf("SPU index2=%d ,",spuIndices[2]); // spu_printf("SPU: indexBasePtr=%llx\n",indexBasePtr); const btVector3& meshScaling = m_lsMemPtr->bvhShapeData.gTriangleMeshInterfacePtr->getScaling(); for (int j=2;btLikely( j>=0 );j--) { int graphicsindex = m_lsMemPtr->spuIndices[j]; // spu_printf("SPU index=%d ,",graphicsindex); btScalar* graphicsbasePtr = (btScalar*)(m_lsMemPtr->bvhShapeData.gIndexMesh.m_vertexBase+graphicsindex*m_lsMemPtr->bvhShapeData.gIndexMesh.m_vertexStride); // spu_printf("SPU graphicsbasePtr=%llx\n",graphicsbasePtr); ///handle un-aligned vertices... //another DMA for each vertex small_cache_read_triple(&spuUnscaledVertex[0],(ppu_address_t)&graphicsbasePtr[0], &spuUnscaledVertex[1],(ppu_address_t)&graphicsbasePtr[1], &spuUnscaledVertex[2],(ppu_address_t)&graphicsbasePtr[2], sizeof(btScalar)); m_tmpTriangleShape.getVertexPtr(j).setValue(spuUnscaledVertex[0]*meshScaling.getX(), spuUnscaledVertex[1]*meshScaling.getY(), spuUnscaledVertex[2]*meshScaling.getZ()); // spu_printf("SPU:triangle vertices:%f,%f,%f\n",spuTriangleVertices[j].x(),spuTriangleVertices[j].y(),spuTriangleVertices[j].z()); } SpuCollisionPairInput triangleConcaveInput(*m_wuInput); // triangleConcaveInput.m_spuCollisionShapes[1] = &spuTriangleVertices[0]; triangleConcaveInput.m_spuCollisionShapes[1] = &m_tmpTriangleShape; triangleConcaveInput.m_shapeType1 = TRIANGLE_SHAPE_PROXYTYPE; m_spuContacts.setShapeIdentifiersB(subPart,triangleIndex); // m_spuContacts.flush(); ProcessSpuConvexConvexCollision(&triangleConcaveInput, m_lsMemPtr,m_spuContacts); ///this flush should be automatic // m_spuContacts.flush(); } }; void btConvexPlaneCollideSingleContact (SpuCollisionPairInput* wuInput,CollisionTask_LocalStoreMemory* lsMemPtr,SpuContactResult& spuContacts) { btConvexShape* convexShape = (btConvexShape*) wuInput->m_spuCollisionShapes[0]; btStaticPlaneShape* planeShape = (btStaticPlaneShape*) wuInput->m_spuCollisionShapes[1]; bool hasCollision = false; const btVector3& planeNormal = planeShape->getPlaneNormal(); const btScalar& planeConstant = planeShape->getPlaneConstant(); btTransform convexWorldTransform = wuInput->m_worldTransform0; btTransform convexInPlaneTrans; convexInPlaneTrans= wuInput->m_worldTransform1.inverse() * convexWorldTransform; btTransform planeInConvex; planeInConvex= convexWorldTransform.inverse() * wuInput->m_worldTransform1; //btVector3 vtx = convexShape->localGetSupportVertexWithoutMarginNonVirtual(planeInConvex.getBasis()*-planeNormal); btVector3 vtx = convexShape->localGetSupportVertexNonVirtual(planeInConvex.getBasis()*-planeNormal); btVector3 vtxInPlane = convexInPlaneTrans(vtx); btScalar distance = (planeNormal.dot(vtxInPlane) - planeConstant); btVector3 vtxInPlaneProjected = vtxInPlane - distance*planeNormal; btVector3 vtxInPlaneWorld = wuInput->m_worldTransform1 * vtxInPlaneProjected; hasCollision = distance < lsMemPtr->getContactManifoldPtr()->getContactBreakingThreshold(); //resultOut->setPersistentManifold(m_manifoldPtr); if (hasCollision) { /// report a contact. internally this will be kept persistent, and contact reduction is done btVector3 normalOnSurfaceB =wuInput->m_worldTransform1.getBasis() * planeNormal; btVector3 pOnB = vtxInPlaneWorld; spuContacts.addContactPoint(normalOnSurfaceB,pOnB,distance); } } void ProcessConvexPlaneSpuCollision(SpuCollisionPairInput* wuInput, CollisionTask_LocalStoreMemory* lsMemPtr, SpuContactResult& spuContacts) { register int dmaSize = 0; register ppu_address_t dmaPpuAddress2; btPersistentManifold* manifold = (btPersistentManifold*)wuInput->m_persistentManifoldPtr; ///DMA in the vertices for convex shapes ATTRIBUTE_ALIGNED16(char convexHullShape0[sizeof(btConvexHullShape)]); ATTRIBUTE_ALIGNED16(char convexHullShape1[sizeof(btConvexHullShape)]); if ( btLikely( wuInput->m_shapeType0== CONVEX_HULL_SHAPE_PROXYTYPE ) ) { // spu_printf("SPU: DMA btConvexHullShape\n"); dmaSize = sizeof(btConvexHullShape); dmaPpuAddress2 = wuInput->m_collisionShapes[0]; cellDmaGet(&convexHullShape0, dmaPpuAddress2 , dmaSize, DMA_TAG(1), 0, 0); //cellDmaWaitTagStatusAll(DMA_MASK(1)); } if ( btLikely( wuInput->m_shapeType1 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { // spu_printf("SPU: DMA btConvexHullShape\n"); dmaSize = sizeof(btConvexHullShape); dmaPpuAddress2 = wuInput->m_collisionShapes[1]; cellDmaGet(&convexHullShape1, dmaPpuAddress2 , dmaSize, DMA_TAG(1), 0, 0); //cellDmaWaitTagStatusAll(DMA_MASK(1)); } if ( btLikely( wuInput->m_shapeType0 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { cellDmaWaitTagStatusAll(DMA_MASK(1)); dmaConvexVertexData (&lsMemPtr->convexVertexData[0], (btConvexHullShape*)&convexHullShape0); lsMemPtr->convexVertexData[0].gSpuConvexShapePtr = wuInput->m_spuCollisionShapes[0]; } if ( btLikely( wuInput->m_shapeType1 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { cellDmaWaitTagStatusAll(DMA_MASK(1)); dmaConvexVertexData (&lsMemPtr->convexVertexData[1], (btConvexHullShape*)&convexHullShape1); lsMemPtr->convexVertexData[1].gSpuConvexShapePtr = wuInput->m_spuCollisionShapes[1]; } btConvexPointCloudShape cpc0,cpc1; if ( btLikely( wuInput->m_shapeType0 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { cellDmaWaitTagStatusAll(DMA_MASK(2)); lsMemPtr->convexVertexData[0].gConvexPoints = &lsMemPtr->convexVertexData[0].g_convexPointBuffer[0]; btConvexHullShape* ch = (btConvexHullShape*)wuInput->m_spuCollisionShapes[0]; const btVector3& localScaling = ch->getLocalScalingNV(); cpc0.setPoints(lsMemPtr->convexVertexData[0].gConvexPoints,lsMemPtr->convexVertexData[0].gNumConvexPoints,false,localScaling); wuInput->m_spuCollisionShapes[0] = &cpc0; } if ( btLikely( wuInput->m_shapeType1 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { cellDmaWaitTagStatusAll(DMA_MASK(2)); lsMemPtr->convexVertexData[1].gConvexPoints = &lsMemPtr->convexVertexData[1].g_convexPointBuffer[0]; btConvexHullShape* ch = (btConvexHullShape*)wuInput->m_spuCollisionShapes[1]; const btVector3& localScaling = ch->getLocalScalingNV(); cpc1.setPoints(lsMemPtr->convexVertexData[1].gConvexPoints,lsMemPtr->convexVertexData[1].gNumConvexPoints,false,localScaling); wuInput->m_spuCollisionShapes[1] = &cpc1; } // const btConvexShape* shape0Ptr = (const btConvexShape*)wuInput->m_spuCollisionShapes[0]; // const btConvexShape* shape1Ptr = (const btConvexShape*)wuInput->m_spuCollisionShapes[1]; // int shapeType0 = wuInput->m_shapeType0; // int shapeType1 = wuInput->m_shapeType1; float marginA = wuInput->m_collisionMargin0; float marginB = wuInput->m_collisionMargin1; SpuClosestPointInput cpInput; cpInput.m_convexVertexData[0] = &lsMemPtr->convexVertexData[0]; cpInput.m_convexVertexData[1] = &lsMemPtr->convexVertexData[1]; cpInput.m_transformA = wuInput->m_worldTransform0; cpInput.m_transformB = wuInput->m_worldTransform1; float sumMargin = (marginA+marginB+lsMemPtr->getContactManifoldPtr()->getContactBreakingThreshold()); cpInput.m_maximumDistanceSquared = sumMargin * sumMargin; ppu_address_t manifoldAddress = (ppu_address_t)manifold; btPersistentManifold* spuManifold=lsMemPtr->getContactManifoldPtr(); //spuContacts.setContactInfo(spuManifold,manifoldAddress,wuInput->m_worldTransform0,wuInput->m_worldTransform1,wuInput->m_isSwapped); spuContacts.setContactInfo(spuManifold,manifoldAddress,lsMemPtr->getColObj0()->getWorldTransform(), lsMemPtr->getColObj1()->getWorldTransform(), lsMemPtr->getColObj0()->getRestitution(),lsMemPtr->getColObj1()->getRestitution(), lsMemPtr->getColObj0()->getFriction(),lsMemPtr->getColObj1()->getFriction(), wuInput->m_isSwapped); btConvexPlaneCollideSingleContact(wuInput,lsMemPtr,spuContacts); } //////////////////////// /// Convex versus Concave triangle mesh collision detection (handles concave triangle mesh versus sphere, box, cylinder, triangle, cone, convex polyhedron etc) /////////////////// void ProcessConvexConcaveSpuCollision(SpuCollisionPairInput* wuInput, CollisionTask_LocalStoreMemory* lsMemPtr, SpuContactResult& spuContacts) { //order: first collision shape is convex, second concave. m_isSwapped is true, if the original order was opposite btBvhTriangleMeshShape* trimeshShape = (btBvhTriangleMeshShape*)wuInput->m_spuCollisionShapes[1]; //need the mesh interface, for access to triangle vertices dmaBvhShapeData (&lsMemPtr->bvhShapeData, trimeshShape); btVector3 aabbMin(-1,-400,-1); btVector3 aabbMax(1,400,1); //recalc aabbs btTransform convexInTriangleSpace; convexInTriangleSpace = wuInput->m_worldTransform1.inverse() * wuInput->m_worldTransform0; btConvexInternalShape* convexShape = (btConvexInternalShape*)wuInput->m_spuCollisionShapes[0]; computeAabb (aabbMin, aabbMax, convexShape, wuInput->m_collisionShapes[0], wuInput->m_shapeType0, convexInTriangleSpace); //CollisionShape* triangleShape = static_cast<btCollisionShape*>(triBody->m_collisionShape); //convexShape->getAabb(convexInTriangleSpace,m_aabbMin,m_aabbMax); // btScalar extraMargin = collisionMarginTriangle; // btVector3 extra(extraMargin,extraMargin,extraMargin); // aabbMax += extra; // aabbMin -= extra; ///quantize query AABB unsigned short int quantizedQueryAabbMin[3]; unsigned short int quantizedQueryAabbMax[3]; lsMemPtr->bvhShapeData.getOptimizedBvh()->quantizeWithClamp(quantizedQueryAabbMin,aabbMin,0); lsMemPtr->bvhShapeData.getOptimizedBvh()->quantizeWithClamp(quantizedQueryAabbMax,aabbMax,1); QuantizedNodeArray& nodeArray = lsMemPtr->bvhShapeData.getOptimizedBvh()->getQuantizedNodeArray(); //spu_printf("SPU: numNodes = %d\n",nodeArray.size()); BvhSubtreeInfoArray& subTrees = lsMemPtr->bvhShapeData.getOptimizedBvh()->getSubtreeInfoArray(); spuNodeCallback nodeCallback(wuInput,lsMemPtr,spuContacts); IndexedMeshArray& indexArray = lsMemPtr->bvhShapeData.gTriangleMeshInterfacePtr->getIndexedMeshArray(); //spu_printf("SPU:indexArray.size() = %d\n",indexArray.size()); // spu_printf("SPU: numSubTrees = %d\n",subTrees.size()); //not likely to happen if (subTrees.size() && indexArray.size() == 1) { ///DMA in the index info dmaBvhIndexedMesh (&lsMemPtr->bvhShapeData.gIndexMesh, indexArray, 0 /* index into indexArray */, 1 /* dmaTag */); cellDmaWaitTagStatusAll(DMA_MASK(1)); //display the headers int numBatch = subTrees.size(); for (int i=0;i<numBatch;) { //@todo- can reorder DMA transfers for less stall int remaining = subTrees.size() - i; int nextBatch = remaining < MAX_SPU_SUBTREE_HEADERS ? remaining : MAX_SPU_SUBTREE_HEADERS; dmaBvhSubTreeHeaders (&lsMemPtr->bvhShapeData.gSubtreeHeaders[0], (ppu_address_t)(&subTrees[i]), nextBatch, 1); cellDmaWaitTagStatusAll(DMA_MASK(1)); // spu_printf("nextBatch = %d\n",nextBatch); for (int j=0;j<nextBatch;j++) { const btBvhSubtreeInfo& subtree = lsMemPtr->bvhShapeData.gSubtreeHeaders[j]; unsigned int overlap = spuTestQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax); if (overlap) { btAssert(subtree.m_subtreeSize); //dma the actual nodes of this subtree dmaBvhSubTreeNodes (&lsMemPtr->bvhShapeData.gSubtreeNodes[0], subtree, nodeArray, 2); cellDmaWaitTagStatusAll(DMA_MASK(2)); /* Walk this subtree */ spuWalkStacklessQuantizedTree(&nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax, &lsMemPtr->bvhShapeData.gSubtreeNodes[0], 0, subtree.m_subtreeSize); } // spu_printf("subtreeSize = %d\n",gSubtreeHeaders[j].m_subtreeSize); } // unsigned short int m_quantizedAabbMin[3]; // unsigned short int m_quantizedAabbMax[3]; // int m_rootNodeIndex; // int m_subtreeSize; i+=nextBatch; } //pre-fetch first tree, then loop and double buffer } } #define MAX_DEGENERATE_STATS 15 int stats[MAX_DEGENERATE_STATS]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int degenerateStats[MAX_DEGENERATE_STATS]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //////////////////////// /// Convex versus Convex collision detection (handles collision between sphere, box, cylinder, triangle, cone, convex polyhedron etc) /////////////////// void ProcessSpuConvexConvexCollision(SpuCollisionPairInput* wuInput, CollisionTask_LocalStoreMemory* lsMemPtr, SpuContactResult& spuContacts) { register int dmaSize; register ppu_address_t dmaPpuAddress2; #ifdef DEBUG_SPU_COLLISION_DETECTION //spu_printf("SPU: ProcessSpuConvexConvexCollision\n"); #endif //DEBUG_SPU_COLLISION_DETECTION //CollisionShape* shape0 = (CollisionShape*)wuInput->m_collisionShapes[0]; //CollisionShape* shape1 = (CollisionShape*)wuInput->m_collisionShapes[1]; btPersistentManifold* manifold = (btPersistentManifold*)wuInput->m_persistentManifoldPtr; bool genericGjk = true; if (genericGjk) { //try generic GJK //SpuConvexPenetrationDepthSolver* penetrationSolver=0; btVoronoiSimplexSolver simplexSolver; btGjkEpaPenetrationDepthSolver epaPenetrationSolver2; btConvexPenetrationDepthSolver* penetrationSolver = &epaPenetrationSolver2; //SpuMinkowskiPenetrationDepthSolver minkowskiPenetrationSolver; #ifdef ENABLE_EPA if (gUseEpa) { penetrationSolver = &epaPenetrationSolver2; } else #endif { //penetrationSolver = &minkowskiPenetrationSolver; } ///DMA in the vertices for convex shapes ATTRIBUTE_ALIGNED16(char convexHullShape0[sizeof(btConvexHullShape)]); ATTRIBUTE_ALIGNED16(char convexHullShape1[sizeof(btConvexHullShape)]); if ( btLikely( wuInput->m_shapeType0== CONVEX_HULL_SHAPE_PROXYTYPE ) ) { // spu_printf("SPU: DMA btConvexHullShape\n"); dmaSize = sizeof(btConvexHullShape); dmaPpuAddress2 = wuInput->m_collisionShapes[0]; cellDmaGet(&convexHullShape0, dmaPpuAddress2 , dmaSize, DMA_TAG(1), 0, 0); //cellDmaWaitTagStatusAll(DMA_MASK(1)); } if ( btLikely( wuInput->m_shapeType1 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { // spu_printf("SPU: DMA btConvexHullShape\n"); dmaSize = sizeof(btConvexHullShape); dmaPpuAddress2 = wuInput->m_collisionShapes[1]; cellDmaGet(&convexHullShape1, dmaPpuAddress2 , dmaSize, DMA_TAG(1), 0, 0); //cellDmaWaitTagStatusAll(DMA_MASK(1)); } if ( btLikely( wuInput->m_shapeType0 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { cellDmaWaitTagStatusAll(DMA_MASK(1)); dmaConvexVertexData (&lsMemPtr->convexVertexData[0], (btConvexHullShape*)&convexHullShape0); lsMemPtr->convexVertexData[0].gSpuConvexShapePtr = wuInput->m_spuCollisionShapes[0]; } if ( btLikely( wuInput->m_shapeType1 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { cellDmaWaitTagStatusAll(DMA_MASK(1)); dmaConvexVertexData (&lsMemPtr->convexVertexData[1], (btConvexHullShape*)&convexHullShape1); lsMemPtr->convexVertexData[1].gSpuConvexShapePtr = wuInput->m_spuCollisionShapes[1]; } btConvexPointCloudShape cpc0,cpc1; if ( btLikely( wuInput->m_shapeType0 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { cellDmaWaitTagStatusAll(DMA_MASK(2)); lsMemPtr->convexVertexData[0].gConvexPoints = &lsMemPtr->convexVertexData[0].g_convexPointBuffer[0]; btConvexHullShape* ch = (btConvexHullShape*)wuInput->m_spuCollisionShapes[0]; const btVector3& localScaling = ch->getLocalScalingNV(); cpc0.setPoints(lsMemPtr->convexVertexData[0].gConvexPoints,lsMemPtr->convexVertexData[0].gNumConvexPoints,false,localScaling); wuInput->m_spuCollisionShapes[0] = &cpc0; } if ( btLikely( wuInput->m_shapeType1 == CONVEX_HULL_SHAPE_PROXYTYPE ) ) { cellDmaWaitTagStatusAll(DMA_MASK(2)); lsMemPtr->convexVertexData[1].gConvexPoints = &lsMemPtr->convexVertexData[1].g_convexPointBuffer[0]; btConvexHullShape* ch = (btConvexHullShape*)wuInput->m_spuCollisionShapes[1]; const btVector3& localScaling = ch->getLocalScalingNV(); cpc1.setPoints(lsMemPtr->convexVertexData[1].gConvexPoints,lsMemPtr->convexVertexData[1].gNumConvexPoints,false,localScaling); wuInput->m_spuCollisionShapes[1] = &cpc1; } const btConvexShape* shape0Ptr = (const btConvexShape*)wuInput->m_spuCollisionShapes[0]; const btConvexShape* shape1Ptr = (const btConvexShape*)wuInput->m_spuCollisionShapes[1]; int shapeType0 = wuInput->m_shapeType0; int shapeType1 = wuInput->m_shapeType1; float marginA = wuInput->m_collisionMargin0; float marginB = wuInput->m_collisionMargin1; SpuClosestPointInput cpInput; cpInput.m_convexVertexData[0] = &lsMemPtr->convexVertexData[0]; cpInput.m_convexVertexData[1] = &lsMemPtr->convexVertexData[1]; cpInput.m_transformA = wuInput->m_worldTransform0; cpInput.m_transformB = wuInput->m_worldTransform1; float sumMargin = (marginA+marginB+lsMemPtr->getContactManifoldPtr()->getContactBreakingThreshold()); cpInput.m_maximumDistanceSquared = sumMargin * sumMargin; ppu_address_t manifoldAddress = (ppu_address_t)manifold; btPersistentManifold* spuManifold=lsMemPtr->getContactManifoldPtr(); //spuContacts.setContactInfo(spuManifold,manifoldAddress,wuInput->m_worldTransform0,wuInput->m_worldTransform1,wuInput->m_isSwapped); spuContacts.setContactInfo(spuManifold,manifoldAddress,lsMemPtr->getColObj0()->getWorldTransform(), lsMemPtr->getColObj1()->getWorldTransform(), lsMemPtr->getColObj0()->getRestitution(),lsMemPtr->getColObj1()->getRestitution(), lsMemPtr->getColObj0()->getFriction(),lsMemPtr->getColObj1()->getFriction(), wuInput->m_isSwapped); { btGjkPairDetector gjk(shape0Ptr,shape1Ptr,shapeType0,shapeType1,marginA,marginB,&simplexSolver,penetrationSolver);//&vsSolver,penetrationSolver); gjk.getClosestPoints(cpInput,spuContacts,0);//,debugDraw); btAssert(gjk.m_lastUsedMethod <MAX_DEGENERATE_STATS); stats[gjk.m_lastUsedMethod]++; btAssert(gjk.m_degenerateSimplex <MAX_DEGENERATE_STATS); degenerateStats[gjk.m_degenerateSimplex]++; #ifdef USE_SEPDISTANCE_UTIL btScalar sepDist = gjk.getCachedSeparatingDistance()+spuManifold->getContactBreakingThreshold(); lsMemPtr->getlocalCollisionAlgorithm()->m_sepDistance.initSeparatingDistance(gjk.getCachedSeparatingAxis(),sepDist,wuInput->m_worldTransform0,wuInput->m_worldTransform1); lsMemPtr->needsDmaPutContactManifoldAlgo = true; #endif //USE_SEPDISTANCE_UTIL } } } template<typename T> void DoSwap(T& a, T& b) { char tmp[sizeof(T)]; memcpy(tmp, &a, sizeof(T)); memcpy(&a, &b, sizeof(T)); memcpy(&b, tmp, sizeof(T)); } SIMD_FORCE_INLINE void dmaAndSetupCollisionObjects(SpuCollisionPairInput& collisionPairInput, CollisionTask_LocalStoreMemory& lsMem) { register int dmaSize; register ppu_address_t dmaPpuAddress2; dmaSize = sizeof(btCollisionObject);//btTransform); dmaPpuAddress2 = /*collisionPairInput.m_isSwapped ? (ppu_address_t)lsMem.gProxyPtr1->m_clientObject :*/ (ppu_address_t)lsMem.getlocalCollisionAlgorithm()->getCollisionObject0(); lsMem.m_lsColObj0Ptr = (btCollisionObject*)cellDmaGetReadOnly(&lsMem.gColObj0Buffer, dmaPpuAddress2 , dmaSize, DMA_TAG(1), 0, 0); dmaSize = sizeof(btCollisionObject);//btTransform); dmaPpuAddress2 = /*collisionPairInput.m_isSwapped ? (ppu_address_t)lsMem.gProxyPtr0->m_clientObject :*/ (ppu_address_t)lsMem.getlocalCollisionAlgorithm()->getCollisionObject1(); lsMem.m_lsColObj1Ptr = (btCollisionObject*)cellDmaGetReadOnly(&lsMem.gColObj1Buffer, dmaPpuAddress2 , dmaSize, DMA_TAG(2), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(1) | DMA_MASK(2)); btCollisionObject* ob0 = lsMem.getColObj0(); btCollisionObject* ob1 = lsMem.getColObj1(); collisionPairInput.m_worldTransform0 = ob0->getWorldTransform(); collisionPairInput.m_worldTransform1 = ob1->getWorldTransform(); } void handleCollisionPair(SpuCollisionPairInput& collisionPairInput, CollisionTask_LocalStoreMemory& lsMem, SpuContactResult &spuContacts, ppu_address_t collisionShape0Ptr, void* collisionShape0Loc, ppu_address_t collisionShape1Ptr, void* collisionShape1Loc, bool dmaShapes = true) { if (btBroadphaseProxy::isConvex(collisionPairInput.m_shapeType0) && btBroadphaseProxy::isConvex(collisionPairInput.m_shapeType1)) { if (dmaShapes) { dmaCollisionShape (collisionShape0Loc, collisionShape0Ptr, 1, collisionPairInput.m_shapeType0); dmaCollisionShape (collisionShape1Loc, collisionShape1Ptr, 2, collisionPairInput.m_shapeType1); cellDmaWaitTagStatusAll(DMA_MASK(1) | DMA_MASK(2)); } btConvexInternalShape* spuConvexShape0 = (btConvexInternalShape*)collisionShape0Loc; btConvexInternalShape* spuConvexShape1 = (btConvexInternalShape*)collisionShape1Loc; btVector3 dim0 = spuConvexShape0->getImplicitShapeDimensions(); btVector3 dim1 = spuConvexShape1->getImplicitShapeDimensions(); collisionPairInput.m_primitiveDimensions0 = dim0; collisionPairInput.m_primitiveDimensions1 = dim1; collisionPairInput.m_collisionShapes[0] = collisionShape0Ptr; collisionPairInput.m_collisionShapes[1] = collisionShape1Ptr; collisionPairInput.m_spuCollisionShapes[0] = spuConvexShape0; collisionPairInput.m_spuCollisionShapes[1] = spuConvexShape1; ProcessSpuConvexConvexCollision(&collisionPairInput,&lsMem,spuContacts); } else if (btBroadphaseProxy::isCompound(collisionPairInput.m_shapeType0) && btBroadphaseProxy::isCompound(collisionPairInput.m_shapeType1)) { //snPause(); dmaCollisionShape (collisionShape0Loc, collisionShape0Ptr, 1, collisionPairInput.m_shapeType0); dmaCollisionShape (collisionShape1Loc, collisionShape1Ptr, 2, collisionPairInput.m_shapeType1); cellDmaWaitTagStatusAll(DMA_MASK(1) | DMA_MASK(2)); // Both are compounds, do N^2 CD for now ///@todo: add some AABB-based pruning (probably not -> slower) btCompoundShape* spuCompoundShape0 = (btCompoundShape*)collisionShape0Loc; btCompoundShape* spuCompoundShape1 = (btCompoundShape*)collisionShape1Loc; dmaCompoundShapeInfo (&lsMem.compoundShapeData[0], spuCompoundShape0, 1); dmaCompoundShapeInfo (&lsMem.compoundShapeData[1], spuCompoundShape1, 2); cellDmaWaitTagStatusAll(DMA_MASK(1) | DMA_MASK(2)); dmaCompoundSubShapes (&lsMem.compoundShapeData[0], spuCompoundShape0, 1); cellDmaWaitTagStatusAll(DMA_MASK(1)); dmaCompoundSubShapes (&lsMem.compoundShapeData[1], spuCompoundShape1, 1); cellDmaWaitTagStatusAll(DMA_MASK(1)); int childShapeCount0 = spuCompoundShape0->getNumChildShapes(); btAssert(childShapeCount0< MAX_SPU_COMPOUND_SUBSHAPES); int childShapeCount1 = spuCompoundShape1->getNumChildShapes(); btAssert(childShapeCount1< MAX_SPU_COMPOUND_SUBSHAPES); // Start the N^2 for (int i = 0; i < childShapeCount0; ++i) { btCompoundShapeChild& childShape0 = lsMem.compoundShapeData[0].gSubshapes[i]; btAssert(!btBroadphaseProxy::isCompound(childShape0.m_childShapeType)); for (int j = 0; j < childShapeCount1; ++j) { btCompoundShapeChild& childShape1 = lsMem.compoundShapeData[1].gSubshapes[j]; btAssert(!btBroadphaseProxy::isCompound(childShape1.m_childShapeType)); /* Create a new collision pair input struct using the two child shapes */ SpuCollisionPairInput cinput (collisionPairInput); cinput.m_worldTransform0 = collisionPairInput.m_worldTransform0 * childShape0.m_transform; cinput.m_shapeType0 = childShape0.m_childShapeType; cinput.m_collisionMargin0 = childShape0.m_childMargin; cinput.m_worldTransform1 = collisionPairInput.m_worldTransform1 * childShape1.m_transform; cinput.m_shapeType1 = childShape1.m_childShapeType; cinput.m_collisionMargin1 = childShape1.m_childMargin; /* Recursively call handleCollisionPair () with new collision pair input */ handleCollisionPair(cinput, lsMem, spuContacts, (ppu_address_t)childShape0.m_childShape, lsMem.compoundShapeData[0].gSubshapeShape[i], (ppu_address_t)childShape1.m_childShape, lsMem.compoundShapeData[1].gSubshapeShape[j], false); } } } else if (btBroadphaseProxy::isCompound(collisionPairInput.m_shapeType0) ) { //snPause(); dmaCollisionShape (collisionShape0Loc, collisionShape0Ptr, 1, collisionPairInput.m_shapeType0); dmaCollisionShape (collisionShape1Loc, collisionShape1Ptr, 2, collisionPairInput.m_shapeType1); cellDmaWaitTagStatusAll(DMA_MASK(1) | DMA_MASK(2)); // object 0 compound, object 1 non-compound btCompoundShape* spuCompoundShape = (btCompoundShape*)collisionShape0Loc; dmaCompoundShapeInfo (&lsMem.compoundShapeData[0], spuCompoundShape, 1); cellDmaWaitTagStatusAll(DMA_MASK(1)); int childShapeCount = spuCompoundShape->getNumChildShapes(); btAssert(childShapeCount< MAX_SPU_COMPOUND_SUBSHAPES); for (int i = 0; i < childShapeCount; ++i) { btCompoundShapeChild& childShape = lsMem.compoundShapeData[0].gSubshapes[i]; btAssert(!btBroadphaseProxy::isCompound(childShape.m_childShapeType)); // Dma the child shape dmaCollisionShape (&lsMem.compoundShapeData[0].gSubshapeShape[i], (ppu_address_t)childShape.m_childShape, 1, childShape.m_childShapeType); cellDmaWaitTagStatusAll(DMA_MASK(1)); SpuCollisionPairInput cinput (collisionPairInput); cinput.m_worldTransform0 = collisionPairInput.m_worldTransform0 * childShape.m_transform; cinput.m_shapeType0 = childShape.m_childShapeType; cinput.m_collisionMargin0 = childShape.m_childMargin; handleCollisionPair(cinput, lsMem, spuContacts, (ppu_address_t)childShape.m_childShape, lsMem.compoundShapeData[0].gSubshapeShape[i], collisionShape1Ptr, collisionShape1Loc, false); } } else if (btBroadphaseProxy::isCompound(collisionPairInput.m_shapeType1) ) { //snPause(); dmaCollisionShape (collisionShape0Loc, collisionShape0Ptr, 1, collisionPairInput.m_shapeType0); dmaCollisionShape (collisionShape1Loc, collisionShape1Ptr, 2, collisionPairInput.m_shapeType1); cellDmaWaitTagStatusAll(DMA_MASK(1) | DMA_MASK(2)); // object 0 non-compound, object 1 compound btCompoundShape* spuCompoundShape = (btCompoundShape*)collisionShape1Loc; dmaCompoundShapeInfo (&lsMem.compoundShapeData[0], spuCompoundShape, 1); cellDmaWaitTagStatusAll(DMA_MASK(1)); int childShapeCount = spuCompoundShape->getNumChildShapes(); btAssert(childShapeCount< MAX_SPU_COMPOUND_SUBSHAPES); for (int i = 0; i < childShapeCount; ++i) { btCompoundShapeChild& childShape = lsMem.compoundShapeData[0].gSubshapes[i]; btAssert(!btBroadphaseProxy::isCompound(childShape.m_childShapeType)); // Dma the child shape dmaCollisionShape (&lsMem.compoundShapeData[0].gSubshapeShape[i], (ppu_address_t)childShape.m_childShape, 1, childShape.m_childShapeType); cellDmaWaitTagStatusAll(DMA_MASK(1)); SpuCollisionPairInput cinput (collisionPairInput); cinput.m_worldTransform1 = collisionPairInput.m_worldTransform1 * childShape.m_transform; cinput.m_shapeType1 = childShape.m_childShapeType; cinput.m_collisionMargin1 = childShape.m_childMargin; handleCollisionPair(cinput, lsMem, spuContacts, collisionShape0Ptr, collisionShape0Loc, (ppu_address_t)childShape.m_childShape, lsMem.compoundShapeData[0].gSubshapeShape[i], false); } } else { //a non-convex shape is involved bool handleConvexConcave = false; //snPause(); if (btBroadphaseProxy::isConcave(collisionPairInput.m_shapeType0) && btBroadphaseProxy::isConvex(collisionPairInput.m_shapeType1)) { // Swap stuff DoSwap(collisionShape0Ptr, collisionShape1Ptr); DoSwap(collisionShape0Loc, collisionShape1Loc); DoSwap(collisionPairInput.m_shapeType0, collisionPairInput.m_shapeType1); DoSwap(collisionPairInput.m_worldTransform0, collisionPairInput.m_worldTransform1); DoSwap(collisionPairInput.m_collisionMargin0, collisionPairInput.m_collisionMargin1); collisionPairInput.m_isSwapped = true; } if (btBroadphaseProxy::isConvex(collisionPairInput.m_shapeType0)&& btBroadphaseProxy::isConcave(collisionPairInput.m_shapeType1)) { handleConvexConcave = true; } if (handleConvexConcave) { if (dmaShapes) { dmaCollisionShape (collisionShape0Loc, collisionShape0Ptr, 1, collisionPairInput.m_shapeType0); dmaCollisionShape (collisionShape1Loc, collisionShape1Ptr, 2, collisionPairInput.m_shapeType1); cellDmaWaitTagStatusAll(DMA_MASK(1) | DMA_MASK(2)); } if (collisionPairInput.m_shapeType1 == STATIC_PLANE_PROXYTYPE) { btConvexInternalShape* spuConvexShape0 = (btConvexInternalShape*)collisionShape0Loc; btStaticPlaneShape* planeShape= (btStaticPlaneShape*)collisionShape1Loc; btVector3 dim0 = spuConvexShape0->getImplicitShapeDimensions(); collisionPairInput.m_primitiveDimensions0 = dim0; collisionPairInput.m_collisionShapes[0] = collisionShape0Ptr; collisionPairInput.m_collisionShapes[1] = collisionShape1Ptr; collisionPairInput.m_spuCollisionShapes[0] = spuConvexShape0; collisionPairInput.m_spuCollisionShapes[1] = planeShape; ProcessConvexPlaneSpuCollision(&collisionPairInput,&lsMem,spuContacts); } else { btConvexInternalShape* spuConvexShape0 = (btConvexInternalShape*)collisionShape0Loc; btBvhTriangleMeshShape* trimeshShape = (btBvhTriangleMeshShape*)collisionShape1Loc; btVector3 dim0 = spuConvexShape0->getImplicitShapeDimensions(); collisionPairInput.m_primitiveDimensions0 = dim0; collisionPairInput.m_collisionShapes[0] = collisionShape0Ptr; collisionPairInput.m_collisionShapes[1] = collisionShape1Ptr; collisionPairInput.m_spuCollisionShapes[0] = spuConvexShape0; collisionPairInput.m_spuCollisionShapes[1] = trimeshShape; ProcessConvexConcaveSpuCollision(&collisionPairInput,&lsMem,spuContacts); } } } spuContacts.flush(); } void processCollisionTask(void* userPtr, void* lsMemPtr) { SpuGatherAndProcessPairsTaskDesc* taskDescPtr = (SpuGatherAndProcessPairsTaskDesc*)userPtr; SpuGatherAndProcessPairsTaskDesc& taskDesc = *taskDescPtr; CollisionTask_LocalStoreMemory* colMemPtr = (CollisionTask_LocalStoreMemory*)lsMemPtr; CollisionTask_LocalStoreMemory& lsMem = *(colMemPtr); gUseEpa = taskDesc.m_useEpa; // spu_printf("taskDescPtr=%llx\n",taskDescPtr); SpuContactResult spuContacts; //////////////////// ppu_address_t dmaInPtr = taskDesc.m_inPairPtr; unsigned int numPages = taskDesc.numPages; unsigned int numOnLastPage = taskDesc.numOnLastPage; // prefetch first set of inputs and wait lsMem.g_workUnitTaskBuffers.init(); unsigned int nextNumOnPage = (numPages > 1)? MIDPHASE_NUM_WORKUNITS_PER_PAGE : numOnLastPage; lsMem.g_workUnitTaskBuffers.backBufferDmaGet(dmaInPtr, nextNumOnPage*sizeof(SpuGatherAndProcessWorkUnitInput), DMA_TAG(3)); dmaInPtr += MIDPHASE_WORKUNIT_PAGE_SIZE; register unsigned char *inputPtr; register unsigned int numOnPage; register unsigned int j; SpuGatherAndProcessWorkUnitInput* wuInputs; register int dmaSize; register ppu_address_t dmaPpuAddress; register ppu_address_t dmaPpuAddress2; int numPairs; register int p; SpuCollisionPairInput collisionPairInput; for (unsigned int i = 0; btLikely(i < numPages); i++) { // wait for back buffer dma and swap buffers inputPtr = lsMem.g_workUnitTaskBuffers.swapBuffers(); // number on current page is number prefetched last iteration numOnPage = nextNumOnPage; // prefetch next set of inputs #if MIDPHASE_NUM_WORKUNIT_PAGES > 2 if ( btLikely( i < numPages-1 ) ) #else if ( btUnlikely( i < numPages-1 ) ) #endif { nextNumOnPage = (i == numPages-2)? numOnLastPage : MIDPHASE_NUM_WORKUNITS_PER_PAGE; lsMem.g_workUnitTaskBuffers.backBufferDmaGet(dmaInPtr, nextNumOnPage*sizeof(SpuGatherAndProcessWorkUnitInput), DMA_TAG(3)); dmaInPtr += MIDPHASE_WORKUNIT_PAGE_SIZE; } wuInputs = reinterpret_cast<SpuGatherAndProcessWorkUnitInput *>(inputPtr); for (j = 0; btLikely( j < numOnPage ); j++) { #ifdef DEBUG_SPU_COLLISION_DETECTION // printMidphaseInput(&wuInputs[j]); #endif //DEBUG_SPU_COLLISION_DETECTION numPairs = wuInputs[j].m_endIndex - wuInputs[j].m_startIndex; if ( btLikely( numPairs ) ) { dmaSize = numPairs*sizeof(btBroadphasePair); dmaPpuAddress = wuInputs[j].m_pairArrayPtr+wuInputs[j].m_startIndex * sizeof(btBroadphasePair); lsMem.m_pairsPointer = (btBroadphasePair*)cellDmaGetReadOnly(&lsMem.gBroadphasePairsBuffer, dmaPpuAddress , dmaSize, DMA_TAG(1), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(1)); for (p=0;p<numPairs;p++) { //for each broadphase pair, do something btBroadphasePair& pair = lsMem.getBroadphasePairPtr()[p]; #ifdef DEBUG_SPU_COLLISION_DETECTION spu_printf("pair->m_userInfo = %d\n",pair.m_userInfo); spu_printf("pair->m_algorithm = %d\n",pair.m_algorithm); spu_printf("pair->m_pProxy0 = %d\n",pair.m_pProxy0); spu_printf("pair->m_pProxy1 = %d\n",pair.m_pProxy1); #endif //DEBUG_SPU_COLLISION_DETECTION if (pair.m_internalTmpValue == 2 && pair.m_algorithm && pair.m_pProxy0 && pair.m_pProxy1) { dmaSize = sizeof(SpuContactManifoldCollisionAlgorithm); dmaPpuAddress2 = (ppu_address_t)pair.m_algorithm; lsMem.m_lsCollisionAlgorithmPtr = (SpuContactManifoldCollisionAlgorithm*)cellDmaGetReadOnly(&lsMem.gSpuContactManifoldAlgoBuffer, dmaPpuAddress2 , dmaSize, DMA_TAG(1), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(1)); lsMem.needsDmaPutContactManifoldAlgo = false; collisionPairInput.m_persistentManifoldPtr = (ppu_address_t) lsMem.getlocalCollisionAlgorithm()->getContactManifoldPtr(); collisionPairInput.m_isSwapped = false; if (1) { ///can wait on the combined DMA_MASK, or dma on the same tag #ifdef DEBUG_SPU_COLLISION_DETECTION // spu_printf("SPU collisionPairInput->m_shapeType0 = %d\n",collisionPairInput->m_shapeType0); // spu_printf("SPU collisionPairInput->m_shapeType1 = %d\n",collisionPairInput->m_shapeType1); #endif //DEBUG_SPU_COLLISION_DETECTION dmaSize = sizeof(btPersistentManifold); dmaPpuAddress2 = collisionPairInput.m_persistentManifoldPtr; lsMem.m_lsManifoldPtr = (btPersistentManifold*)cellDmaGetReadOnly(&lsMem.gPersistentManifoldBuffer, dmaPpuAddress2 , dmaSize, DMA_TAG(1), 0, 0); collisionPairInput.m_shapeType0 = lsMem.getlocalCollisionAlgorithm()->getShapeType0(); collisionPairInput.m_shapeType1 = lsMem.getlocalCollisionAlgorithm()->getShapeType1(); collisionPairInput.m_collisionMargin0 = lsMem.getlocalCollisionAlgorithm()->getCollisionMargin0(); collisionPairInput.m_collisionMargin1 = lsMem.getlocalCollisionAlgorithm()->getCollisionMargin1(); //??cellDmaWaitTagStatusAll(DMA_MASK(1)); if (1) { //snPause(); // Get the collision objects dmaAndSetupCollisionObjects(collisionPairInput, lsMem); if (lsMem.getColObj0()->isActive() || lsMem.getColObj1()->isActive()) { lsMem.needsDmaPutContactManifoldAlgo = true; #ifdef USE_SEPDISTANCE_UTIL lsMem.getlocalCollisionAlgorithm()->m_sepDistance.updateSeparatingDistance(collisionPairInput.m_worldTransform0,collisionPairInput.m_worldTransform1); #endif //USE_SEPDISTANCE_UTIL #define USE_DEDICATED_BOX_BOX 1 #ifdef USE_DEDICATED_BOX_BOX bool boxbox = ((lsMem.getlocalCollisionAlgorithm()->getShapeType0()==BOX_SHAPE_PROXYTYPE)&& (lsMem.getlocalCollisionAlgorithm()->getShapeType1()==BOX_SHAPE_PROXYTYPE)); if (boxbox) { //spu_printf("boxbox dist = %f\n",distance); btPersistentManifold* spuManifold=lsMem.getContactManifoldPtr(); btPersistentManifold* manifold = (btPersistentManifold*)collisionPairInput.m_persistentManifoldPtr; ppu_address_t manifoldAddress = (ppu_address_t)manifold; spuContacts.setContactInfo(spuManifold,manifoldAddress,lsMem.getColObj0()->getWorldTransform(), lsMem.getColObj1()->getWorldTransform(), lsMem.getColObj0()->getRestitution(),lsMem.getColObj1()->getRestitution(), lsMem.getColObj0()->getFriction(),lsMem.getColObj1()->getFriction(), collisionPairInput.m_isSwapped); //float distance=0.f; btVector3 normalInB; if (//!gUseEpa && #ifdef USE_SEPDISTANCE_UTIL lsMem.getlocalCollisionAlgorithm()->m_sepDistance.getConservativeSeparatingDistance()<=0.f #else 1 #endif ) { //#define USE_PE_BOX_BOX 1 #ifdef USE_PE_BOX_BOX { //getCollisionMargin0 btScalar margin0 = lsMem.getlocalCollisionAlgorithm()->getCollisionMargin0(); btScalar margin1 = lsMem.getlocalCollisionAlgorithm()->getCollisionMargin1(); btVector3 shapeDim0 = lsMem.getlocalCollisionAlgorithm()->getShapeDimensions0()+btVector3(margin0,margin0,margin0); btVector3 shapeDim1 = lsMem.getlocalCollisionAlgorithm()->getShapeDimensions1()+btVector3(margin1,margin1,margin1); /* //Box boxA(shapeDim0.getX(),shapeDim0.getY(),shapeDim0.getZ()); vmVector3 vmPos0 = getVmVector3(collisionPairInput.m_worldTransform0.getOrigin()); vmVector3 vmPos1 = getVmVector3(collisionPairInput.m_worldTransform1.getOrigin()); vmMatrix3 vmMatrix0 = getVmMatrix3(collisionPairInput.m_worldTransform0.getBasis()); vmMatrix3 vmMatrix1 = getVmMatrix3(collisionPairInput.m_worldTransform1.getBasis()); vmTransform3 transformA(vmMatrix0,vmPos0); Box boxB(shapeDim1.getX(),shapeDim1.getY(),shapeDim1.getZ()); vmTransform3 transformB(vmMatrix1,vmPos1); BoxPoint resultClosestBoxPointA; BoxPoint resultClosestBoxPointB; vmVector3 resultNormal; */ #ifdef USE_SEPDISTANCE_UTIL float distanceThreshold = FLT_MAX #else //float distanceThreshold = 0.f; #endif vmVector3 n; Box boxA; vmVector3 hA(shapeDim0.getX(),shapeDim0.getY(),shapeDim0.getZ()); vmVector3 hB(shapeDim1.getX(),shapeDim1.getY(),shapeDim1.getZ()); boxA.mHalf= hA; vmTransform3 trA; trA.setTranslation(getVmVector3(collisionPairInput.m_worldTransform0.getOrigin())); trA.setUpper3x3(getVmMatrix3(collisionPairInput.m_worldTransform0.getBasis())); Box boxB; boxB.mHalf = hB; vmTransform3 trB; trB.setTranslation(getVmVector3(collisionPairInput.m_worldTransform1.getOrigin())); trB.setUpper3x3(getVmMatrix3(collisionPairInput.m_worldTransform1.getBasis())); float distanceThreshold = spuManifold->getContactBreakingThreshold();//0.001f; BoxPoint ptA,ptB; float dist = boxBoxDistance(n, ptA, ptB, boxA, trA, boxB, trB, distanceThreshold ); // float distance = boxBoxDistance(resultNormal,resultClosestBoxPointA,resultClosestBoxPointB, boxA, transformA, boxB,transformB,distanceThreshold); normalInB = -getBtVector3(n);//resultNormal); //if(dist < distanceThreshold)//spuManifold->getContactBreakingThreshold()) if(dist < spuManifold->getContactBreakingThreshold()) { btVector3 pointOnB = collisionPairInput.m_worldTransform1(getBtVector3(ptB.localPoint)); spuContacts.addContactPoint( normalInB, pointOnB, dist); } } #else { btScalar margin0 = lsMem.getlocalCollisionAlgorithm()->getCollisionMargin0(); btScalar margin1 = lsMem.getlocalCollisionAlgorithm()->getCollisionMargin1(); btVector3 shapeDim0 = lsMem.getlocalCollisionAlgorithm()->getShapeDimensions0()+btVector3(margin0,margin0,margin0); btVector3 shapeDim1 = lsMem.getlocalCollisionAlgorithm()->getShapeDimensions1()+btVector3(margin1,margin1,margin1); btBoxShape box0(shapeDim0); btBoxShape box1(shapeDim1); struct SpuBridgeContactCollector : public btDiscreteCollisionDetectorInterface::Result { SpuContactResult& m_spuContacts; virtual void setShapeIdentifiersA(int partId0,int index0) { m_spuContacts.setShapeIdentifiersA(partId0,index0); } virtual void setShapeIdentifiersB(int partId1,int index1) { m_spuContacts.setShapeIdentifiersB(partId1,index1); } virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth) { m_spuContacts.addContactPoint(normalOnBInWorld,pointInWorld,depth); } SpuBridgeContactCollector(SpuContactResult& spuContacts) :m_spuContacts(spuContacts) { } }; SpuBridgeContactCollector bridgeOutput(spuContacts); btDiscreteCollisionDetectorInterface::ClosestPointInput input; input.m_maximumDistanceSquared = BT_LARGE_FLOAT; input.m_transformA = collisionPairInput.m_worldTransform0; input.m_transformB = collisionPairInput.m_worldTransform1; btBoxBoxDetector detector(&box0,&box1); detector.getClosestPoints(input,bridgeOutput,0); } #endif //USE_PE_BOX_BOX lsMem.needsDmaPutContactManifoldAlgo = true; #ifdef USE_SEPDISTANCE_UTIL btScalar sepDist2 = distance+spuManifold->getContactBreakingThreshold(); lsMem.getlocalCollisionAlgorithm()->m_sepDistance.initSeparatingDistance(normalInB,sepDist2,collisionPairInput.m_worldTransform0,collisionPairInput.m_worldTransform1); #endif //USE_SEPDISTANCE_UTIL gProcessedCol++; } else { gSkippedCol++; } spuContacts.flush(); } else #endif //USE_DEDICATED_BOX_BOX { if ( #ifdef USE_SEPDISTANCE_UTIL lsMem.getlocalCollisionAlgorithm()->m_sepDistance.getConservativeSeparatingDistance()<=0.f #else 1 #endif //USE_SEPDISTANCE_UTIL ) { handleCollisionPair(collisionPairInput, lsMem, spuContacts, (ppu_address_t)lsMem.getColObj0()->getCollisionShape(), &lsMem.gCollisionShapes[0].collisionShape, (ppu_address_t)lsMem.getColObj1()->getCollisionShape(), &lsMem.gCollisionShapes[1].collisionShape); } else { //spu_printf("boxbox dist = %f\n",distance); btPersistentManifold* spuManifold=lsMem.getContactManifoldPtr(); btPersistentManifold* manifold = (btPersistentManifold*)collisionPairInput.m_persistentManifoldPtr; ppu_address_t manifoldAddress = (ppu_address_t)manifold; spuContacts.setContactInfo(spuManifold,manifoldAddress,lsMem.getColObj0()->getWorldTransform(), lsMem.getColObj1()->getWorldTransform(), lsMem.getColObj0()->getRestitution(),lsMem.getColObj1()->getRestitution(), lsMem.getColObj0()->getFriction(),lsMem.getColObj1()->getFriction(), collisionPairInput.m_isSwapped); spuContacts.flush(); } } } } } #ifdef USE_SEPDISTANCE_UTIL #if defined (__SPU__) || defined (USE_LIBSPE2) if (lsMem.needsDmaPutContactManifoldAlgo) { dmaSize = sizeof(SpuContactManifoldCollisionAlgorithm); dmaPpuAddress2 = (ppu_address_t)pair.m_algorithm; cellDmaLargePut(&lsMem.gSpuContactManifoldAlgoBuffer, dmaPpuAddress2 , dmaSize, DMA_TAG(1), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(1)); } #endif #endif //#ifdef USE_SEPDISTANCE_UTIL } } } } //end for (j = 0; j < numOnPage; j++) }// for return; }
/* file: pca_result_v2_fpt.cpp */ /******************************************************************************* * Copyright 2014-2019 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. *******************************************************************************/ /* //++ // Implementation of PCA algorithm interface. //-- */ #include "pca/inner/pca_types_v2.h" #include "pca/inner/pca_result_v2.h" namespace daal { namespace algorithms { namespace pca { namespace interface2 { /** * Allocates memory for storing partial results of the PCA algorithm * \param[in] input Pointer to an object containing input data * \param[in] parameter Algorithm parameter * \param[in] method Computation method */ template<typename algorithmFPType> DAAL_EXPORT services::Status Result::allocate(const daal::algorithms::Input *input, daal::algorithms::Parameter *parameter, const Method method) { size_t nComponents = 0; DAAL_UINT64 resultsToCompute = eigenvalue; const auto* par = dynamic_cast<const interface2::BaseBatchParameter*>(parameter); if (par != NULL) { nComponents = par->nComponents; resultsToCompute = par->resultsToCompute; } auto impl = ResultImpl::cast(getStorage(*this)); DAAL_CHECK(impl, services::ErrorNullPtr); return impl->allocate<algorithmFPType>(input, nComponents, resultsToCompute); } /** * Allocates memory for storing partial results of the PCA algorithm * \param[in] partialResult Pointer to an object containing input data * \param[in] parameter Parameter of the algorithm * \param[in] method Computation method */ template<typename algorithmFPType> DAAL_EXPORT services::Status Result::allocate(const daal::algorithms::PartialResult *partialResult, daal::algorithms::Parameter *parameter, const Method method) { size_t nComponents = 0; DAAL_UINT64 resultsToCompute = eigenvalue; auto impl = ResultImpl::cast(getStorage(*this)); DAAL_CHECK(impl, services::ErrorNullPtr); return impl->allocate<algorithmFPType>(partialResult, nComponents, resultsToCompute); } template DAAL_EXPORT services::Status Result::allocate<DAAL_FPTYPE>(const daal::algorithms::Input *input, daal::algorithms::Parameter *parameter, const Method method); template DAAL_EXPORT services::Status Result::allocate<DAAL_FPTYPE>(const daal::algorithms::PartialResult *partialResult, daal::algorithms::Parameter *parameter, const Method method); }// interface2 }// namespace pca }// namespace algorithms }// namespace daal
/*! @file */ /* Copyright (C) 2018-2021, Sakura Editor Organization This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "StdAfx.h" #include "CharsetDetector.h" // https://www.freedesktop.org/wiki/Software/uchardet/ // https://docs.microsoft.com/en-us/windows/win32/intl/code-page-identifiers static const std::unordered_map<std::string, uint16_t> map_charsetToCodePage = { // International (Unicode) { "UTF-32BE", 12001, }, { "UTF-32LE", 12000, }, // Arabic { "ISO-8859-6", 28596, }, { "WINDOWS-1256", 1256, }, // Bulgarian { "ISO-8859-5", 28595, }, { "WINDOWS-1251", 1251, }, // Chinese { "ISO-2022-CN", 50227, }, { "BIG5", 950, }, { "EUC-TW", 51950, }, { "GB18030", 54936, }, { "HZ-GB-2312", 52936, }, // Croatian { "ISO-8859-2", 28592, }, { "ISO-8859-13", 28603, }, { "ISO-8859-16", 28606, }, { "WINDOWS-1250", 1250, }, { "IBM852", 852, }, { "MAC-CENTRALEUROPE", 10029, }, // Czech { "WINDOWS-1250", 1250, }, { "ISO-8859-2", 28592, }, { "IBM852", 852, }, { "MAC-CENTRALEUROPE", 10029, }, // Danish { "ISO-8859-1", 28591, }, { "ISO-8859-15", 28605, }, { "WINDOWS-1252", 1252, }, // English { "ASCII", 20127, }, // Esperanto { "ISO-8859-3", 28593, }, // Estonian { "ISO-8859-4", 28594, }, { "ISO-8859-13", 28603, }, { "ISO-8859-13", 28603, }, { "WINDOWS-1252", 1252, }, { "WINDOWS-1257", 1257, }, // Finnish { "ISO-8859-1", 28591, }, { "ISO-8859-4", 28594, }, { "ISO-8859-9", 28599, }, { "ISO-8859-13", 28603, }, { "ISO-8859-15", 28605, }, { "WINDOWS-1252", 1252, }, // French { "ISO-8859-1", 28591, }, { "ISO-8859-15", 28605, }, { "WINDOWS-1252", 1252, }, // German { "ISO-8859-1", 28591, }, { "WINDOWS-1252", 1252, }, // Greek { "ISO-8859-7", 28597, }, { "WINDOWS-1253", 1253, }, // Hebrew { "ISO-8859-8", 28598, }, { "WINDOWS-1255", 1255, }, // Hungarian { "ISO-8859-2", 28592, }, { "WINDOWS-1250", 1250, }, // Irish Gaelic { "ISO-8859-1", 28591, }, { "ISO-8859-9", 28599, }, { "ISO-8859-15", 28605, }, { "WINDOWS-1252", 1252, }, // Italian { "ISO-8859-1", 28591, }, { "ISO-8859-3", 28593, }, { "ISO-8859-9", 28599, }, { "ISO-8859-15", 28605, }, { "WINDOWS-1252", 1252, }, // Japanese { "ISO-2022-JP", 50220, }, { "SHIFT_JIS", 932, }, { "EUC-JP", 20932, }, // Korean { "ISO-2022-KR", 50225, }, { "EUC-KR", 51949, }, // Lithuanian { "ISO-8859-4", 28594, }, { "ISO-8859-10", 28600, }, { "ISO-8859-13", 28603, }, // Latvian { "ISO-8859-4", 28594, }, { "ISO-8859-10", 28600, }, { "ISO-8859-13", 28603, }, // Maltese { "ISO-8859-3", 28593, }, // Polish { "ISO-8859-2", 28592, }, { "ISO-8859-13", 28603, }, { "ISO-8859-16", 28606, }, { "WINDOWS-1250", 1250, }, { "IBM852", 852, }, { "MAC-CENTRALEUROPE", 10029, }, // Portuguese { "ISO-8859-1", 28591, }, { "ISO-8859-9", 28599, }, { "ISO-8859-15", 28605, }, { "WINDOWS-1252", 1252, }, // Romanian { "ISO-8859-2", 28592, }, { "ISO-8859-16", 28606, }, { "WINDOWS-1250", 1250, }, { "IBM852", 852, }, // Russian { "ISO-8859-5", 28595, }, { "KOI8-R", 20866, }, { "WINDOWS-1251", 1251, }, { "MAC-CYRILLIC", 10007, }, { "IBM866", 866, }, { "IBM855", 855, }, // Slovak { "WINDOWS-1250", 1250, }, { "ISO-8859-2", 28592, }, { "IBM852", 852, }, { "MAC-CENTRALEUROPE", 10029, }, // Slovene { "ISO-8859-2", 28592, }, { "ISO-8859-16", 28606, }, { "WINDOWS-1250", 1250, }, { "IBM852", 852, }, { "MAC-CENTRALEUROPE", 10029, }, // Spanish { "ISO-8859-1", 28591, }, { "ISO-8859-15", 28605, }, { "WINDOWS-1252", 1252, }, // Swedish { "ISO-8859-1", 28591, }, { "ISO-8859-4", 28594, }, { "ISO-8859-9", 28599, }, { "ISO-8859-15", 28605, }, { "WINDOWS-1252", 1252, }, // Thai { "TIS-620", 874, }, { "ISO-8859-11", 28601, }, // Turkish { "ISO-8859-3", 28593, }, { "ISO-8859-9", 28599, }, // Vietnamese //{ "VISCII", , }, { "Windows-1258", 1258, }, // Others { "WINDOWS-1252", 1252, }, }; CharsetDetector::CharsetDetector() noexcept : _icuin() , _csd(nullptr) { _icuin.InitDll(); _uchardet.InitDll(); } CharsetDetector::~CharsetDetector() noexcept { if (_icuin.IsAvailable()) { _icuin.ucsdet_close(_csd); } if (_uchardet.IsAvailable()) { _uchardet.uchardet_delete(_ud); } } ECodeType CharsetDetector::Detect(const std::string_view& bytes) { if (_icuin.IsAvailable()) { UErrorCode status = U_ZERO_ERROR; _csd = _icuin.ucsdet_open(&status); if (status != U_ZERO_ERROR) { return CODE_ERROR; } _icuin.ucsdet_setText(_csd, bytes.data(), bytes.length(), &status); if (status != U_ZERO_ERROR) { return CODE_ERROR; } const auto csm = _icuin.ucsdet_detect(_csd, &status); if (status != U_ZERO_ERROR) { return CODE_ERROR; } std::string_view name = _icuin.ucsdet_getName(csm, &status); if (status != U_ZERO_ERROR) { return CODE_ERROR; } // 文字セット名⇒サクラエディタ内部コードの変換 if (name == "UTF-8") return CODE_UTF8; if (name == "SHIFT_JIS") return CODE_SJIS; if (name == "UTF-16BE") return CODE_UNICODEBE; if (name == "UTF-16LE") return CODE_UNICODE; if (name == "EUC-JP") return CODE_EUC; if (name == "ISO-2022-JP") return CODE_JIS; if (name == "UTF-7") return CODE_UTF7; if (name == "ISO-8859-1") return CODE_LATIN1; return CODE_ERROR; } if (_uchardet.IsAvailable()) { if (!_ud) { _ud = _uchardet.uchardet_new(); } if (!_ud) { return CODE_ERROR; } _uchardet.uchardet_reset(_ud); if (_uchardet.uchardet_handle_data(_ud, bytes.data(), bytes.length()) != 0) { return CODE_ERROR; } _uchardet.uchardet_data_end(_ud); std::string_view name = _uchardet.uchardet_get_charset(_ud); std::string str(name); std::transform(str.begin(), str.end(), str.begin(), ::toupper); auto it = map_charsetToCodePage.find(str); if (it == map_charsetToCodePage.end()) { return CODE_ERROR; }else { return (ECodeType)it->second; } } return CODE_ERROR; }
// // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com) // // 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) // // Official repository: https://github.com/boostorg/beast // #include <boost/config.hpp> #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable: 4459) // declaration hides global declaration #endif #include <boost/beast/_experimental/unit_test/suite.hpp> #include <boost/beast.hpp> #include <boost/beast/ssl.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> namespace { #include "websocket_common.ipp" //[code_websocket_3_1 void set_user_agent(request_type& req) { // Set the User-Agent on the request req.set(http::field::user_agent, "My User Agent"); } //] void snippets() { { //[code_websocket_3_2 stream<tcp_stream> ws(ioc); // The function `set_user_agent` will be invoked with // every upgrade request before it is sent by the stream. ws.set_option(stream_base::decorator(&set_user_agent)); //] } stream<tcp_stream> ws(ioc); { //[code_websocket_3_3 struct set_server { void operator()(response_type& res) { // Set the Server field on the response res.set(http::field::user_agent, "My Server"); } }; ws.set_option(stream_base::decorator(set_server{})); //] } { //[code_websocket_3_4 ws.set_option(stream_base::decorator( [](response_type& res) { // Set the Server field on the response res.set(http::field::user_agent, "My Server"); })); //] } { //[code_websocket_3_5 struct set_message_fields { void operator()(request_type& req) { // Set the User-Agent on the request req.set(http::field::user_agent, "My User Agent"); } void operator()(response_type& res) { // Set the Server field on the response res.set(http::field::user_agent, "My Server"); } }; ws.set_option(stream_base::decorator(set_message_fields{})); //] } { //[code_websocket_3_6 struct set_auth { std::unique_ptr<std::string> key; void operator()(request_type& req) { // Set the authorization field req.set(http::field::authorization, *key); } }; // The stream takes ownership of the decorator object ws.set_option(stream_base::decorator( set_auth{boost::make_unique<std::string>("Basic QWxhZGRpbjpPcGVuU2VzYW1l")})); //] } } struct websocket_3_test : public boost::beast::unit_test::suite { void run() override { BEAST_EXPECT(&snippets); } }; BEAST_DEFINE_TESTSUITE(beast,doc,websocket_3); } // (anon) #ifdef BOOST_MSVC #pragma warning(pop) #endif
// Copyright (c) 2001-2008 Hartmut Kaiser // Copyright (c) 2001-2007 Joel de Guzman // // 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) #if !defined(BOOST_SPIRIT_LEX_TERMINAL_DIRECTOR_MAR_22_2007_0846PM) #define BOOST_SPIRIT_LEX_TERMINAL_DIRECTOR_MAR_22_2007_0846PM #include <boost/spirit/home/lex/lexer/terminal_holder.hpp> #include <boost/spirit/home/lex/domain.hpp> #include <boost/spirit/home/support/component.hpp> namespace boost { namespace spirit { namespace lex { // this is the director for all lexer related proto terminals struct terminal_director { // Qi interface: return value of the parser template <typename Component, typename Context, typename Iterator> struct attribute { typedef typename result_of::subject<Component>::type terminal_holder; typedef typename terminal_holder::terminal_type terminal_type; typedef typename terminal_type::template attribute< terminal_holder, Context, Iterator >::type type; }; // Qi interface: parse functionality, delegates back to the // corresponding lexer terminal template <typename Component, typename Iterator, typename Context, typename Skipper, typename Attribute> static bool parse(Component const& component, Iterator& first, Iterator const& last, Context& context, Skipper const& skipper, Attribute& attr) { // main entry point, just forward to the lexer terminal return subject(component).held->parse( first, last, context, skipper, attr); } template <typename Component, typename Context> static std::string what(Component const& component, Context const& ctx) { return subject(component).held->what(); } // Lex interface: collect functionality, delegates back to the // corresponding lexer terminal template <typename Component, typename LexerDef, typename String> static void collect (Component const& component, LexerDef& lexdef, String const& state) { subject(component).held->collect(lexdef, state); } // Lex interface: return the token id of the associated token_def template <typename Component> static std::size_t id(Component const& component) { return subject(component).held->id(); } }; }}} #endif
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: inline TreeNode* clone(TreeNode* origin){ if(NULL == origin) return NULL; TreeNode* ret = new TreeNode(origin->val); ret->left = clone(origin->left); ret->right = clone(origin->right); return ret; } inline vector<TreeNode*> aux(int n, vector<vector<TreeNode*>>& dp){ vector<TreeNode*>& ret = dp[n]; if(n == 0 || !ret.empty()){ return ret; }else if(n == 1){ ret.push_back(new TreeNode(n)); }else{ vector<TreeNode*> children = aux(n-1, dp); for(auto child : children){ //as parent auto current = new TreeNode(n); current->left = clone(child); ret.push_back(current); //as right child int level = 0; auto p = clone(child); while(p){ auto root = clone(child); auto parent = root; for(int i=0;i<level;i++){ parent = parent->right; } auto current2 = new TreeNode(n); if(parent->right) current2->left = parent->right; parent->right = current2; ret.push_back(root); level++; p = p->right; } } } return ret; } vector<TreeNode*> generateTrees(int n) { vector<vector<TreeNode*>> dp(n+1, vector<TreeNode*>()); return aux(n, dp); } };
// Copyright 2017 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/metrics/browser_window_histogram_helper.h" #include "components/startup_metric_utils/browser/startup_metric_utils.h" #include "ui/compositor/compositor.h" BrowserWindowHistogramHelper::~BrowserWindowHistogramHelper() {} // static std::unique_ptr<BrowserWindowHistogramHelper> BrowserWindowHistogramHelper::MaybeRecordValueAndCreateInstanceOnBrowserPaint( ui::Compositor* compositor) { static bool did_first_paint = false; if (did_first_paint) return std::unique_ptr<BrowserWindowHistogramHelper>(); did_first_paint = true; return std::unique_ptr<BrowserWindowHistogramHelper>( new BrowserWindowHistogramHelper(compositor)); } BrowserWindowHistogramHelper::BrowserWindowHistogramHelper( ui::Compositor* compositor) : scoped_observer_(this) { startup_metric_utils::RecordBrowserWindowFirstPaint(base::TimeTicks::Now()); #if defined(OS_MACOSX) if (!compositor) { // In Cocoa version of Chromium, UI is rendered inside the main process // using CoreAnimation compositor, and at this point everything is already // visible to the user. startup_metric_utils::RecordBrowserWindowFirstPaintCompositingEnded( base::TimeTicks::Now()); return; } #endif // OS_MACOSX scoped_observer_.Add(compositor); } void BrowserWindowHistogramHelper::OnCompositingEnded( ui::Compositor* compositor) { startup_metric_utils::RecordBrowserWindowFirstPaintCompositingEnded( base::TimeTicks::Now()); scoped_observer_.RemoveAll(); } void BrowserWindowHistogramHelper::OnCompositingShuttingDown( ui::Compositor* compositor) { scoped_observer_.RemoveAll(); }
// cFile.cpp // Implements the cFile class providing an OS-independent abstraction of a file. #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "File.h" #include <fstream> #ifdef _WIN32 #include <share.h> // for _SH_DENYWRITE #endif // _WIN32 cFile::cFile(void) : #ifdef USE_STDIO_FILE m_File(NULL) #else m_File(INVALID_HANDLE_VALUE) #endif // USE_STDIO_FILE { // Nothing needed yet } cFile::cFile(const AString & iFileName, eMode iMode) : #ifdef USE_STDIO_FILE m_File(NULL) #else m_File(INVALID_HANDLE_VALUE) #endif // USE_STDIO_FILE { Open(iFileName, iMode); } cFile::~cFile() { if (IsOpen()) { Close(); } } bool cFile::Open(const AString & iFileName, eMode iMode) { ASSERT(!IsOpen()); // You should close the file before opening another one if (IsOpen()) { Close(); } const char * Mode = NULL; switch (iMode) { case fmRead: Mode = "rb"; break; case fmWrite: Mode = "wb"; break; case fmReadWrite: Mode = "rb+"; break; } if (Mode == NULL) { ASSERT(!"Unhandled file mode"); return false; } #ifdef _WIN32 m_File = _fsopen((FILE_IO_PREFIX + iFileName).c_str(), Mode, _SH_DENYWR); #else m_File = fopen((FILE_IO_PREFIX + iFileName).c_str(), Mode); #endif // _WIN32 if ((m_File == NULL) && (iMode == fmReadWrite)) { // Fix for MS not following C spec, opening "a" mode files for writing at the end only // The file open operation has been tried with "read update", fails if file not found // So now we know either the file doesn't exist or we don't have rights, no need to worry about file contents. // Simply re-open for read-writing, erasing existing contents: #ifdef _WIN32 m_File = _fsopen((FILE_IO_PREFIX + iFileName).c_str(), "wb+", _SH_DENYWR); #else m_File = fopen((FILE_IO_PREFIX + iFileName).c_str(), "wb+"); #endif // _WIN32 } return (m_File != NULL); } void cFile::Close(void) { if (!IsOpen()) { // Closing an unopened file is a legal nop return; } fclose(m_File); m_File = NULL; } bool cFile::IsOpen(void) const { return (m_File != NULL); } bool cFile::IsEOF(void) const { ASSERT(IsOpen()); if (!IsOpen()) { // Unopened files behave as at EOF return true; } return (feof(m_File) != 0); } int cFile::Read (void * iBuffer, size_t iNumBytes) { ASSERT(IsOpen()); if (!IsOpen()) { return -1; } return (int)fread(iBuffer, 1, (size_t)iNumBytes, m_File); // fread() returns the portion of Count parameter actually read, so we need to send iNumBytes as Count } int cFile::Write(const void * iBuffer, size_t iNumBytes) { ASSERT(IsOpen()); if (!IsOpen()) { return -1; } int res = (int)fwrite(iBuffer, 1, (size_t)iNumBytes, m_File); // fwrite() returns the portion of Count parameter actually written, so we need to send iNumBytes as Count return res; } int cFile::Seek (int iPosition) { ASSERT(IsOpen()); if (!IsOpen()) { return -1; } if (fseek(m_File, iPosition, SEEK_SET) != 0) { return -1; } return (int)ftell(m_File); } int cFile::Tell (void) const { ASSERT(IsOpen()); if (!IsOpen()) { return -1; } return (int)ftell(m_File); } int cFile::GetSize(void) const { ASSERT(IsOpen()); if (!IsOpen()) { return -1; } int CurPos = Tell(); if (CurPos < 0) { return -1; } if (fseek(m_File, 0, SEEK_END) != 0) { return -1; } int res = Tell(); if (fseek(m_File, (long)CurPos, SEEK_SET) != 0) { return -1; } return res; } int cFile::ReadRestOfFile(AString & a_Contents) { ASSERT(IsOpen()); if (!IsOpen()) { return -1; } int DataSize = GetSize() - Tell(); // HACK: This depends on the internal knowledge that AString's data() function returns the internal buffer directly a_Contents.assign((size_t)DataSize, '\0'); return Read((void *)a_Contents.data(), DataSize); } bool cFile::Exists(const AString & a_FileName) { cFile test(a_FileName, fmRead); return test.IsOpen(); } bool cFile::Delete(const AString & a_FileName) { return (remove(a_FileName.c_str()) == 0); } bool cFile::Rename(const AString & a_OrigFileName, const AString & a_NewFileName) { return (rename(a_OrigFileName.c_str(), a_NewFileName.c_str()) == 0); } bool cFile::Copy(const AString & a_SrcFileName, const AString & a_DstFileName) { #ifdef _WIN32 return (CopyFile(a_SrcFileName.c_str(), a_DstFileName.c_str(), true) != 0); #else // Other OSs don't have a direct CopyFile equivalent, do it the harder way: std::ifstream src(a_SrcFileName.c_str(), std::ios::binary); std::ofstream dst(a_DstFileName.c_str(), std::ios::binary); if (dst.good()) { dst << src.rdbuf(); return true; } else { return false; } #endif } bool cFile::IsFolder(const AString & a_Path) { #ifdef _WIN32 DWORD FileAttrib = GetFileAttributes(a_Path.c_str()); return ((FileAttrib != INVALID_FILE_ATTRIBUTES) && ((FileAttrib & FILE_ATTRIBUTE_DIRECTORY) != 0)); #else struct stat st; return ((stat(a_Path.c_str(), &st) == 0) && S_ISDIR(st.st_mode)); #endif } bool cFile::IsFile(const AString & a_Path) { #ifdef _WIN32 DWORD FileAttrib = GetFileAttributes(a_Path.c_str()); return ((FileAttrib != INVALID_FILE_ATTRIBUTES) && ((FileAttrib & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)); #else struct stat st; return ((stat(a_Path.c_str(), &st) == 0) && S_ISREG(st.st_mode)); #endif } int cFile::GetSize(const AString & a_FileName) { struct stat st; if (stat(a_FileName.c_str(), &st) == 0) { return (int)st.st_size; } return -1; } bool cFile::CreateFolder(const AString & a_FolderPath) { #ifdef _WIN32 return (CreateDirectory(a_FolderPath.c_str(), NULL) != 0); #else return (mkdir(a_FolderPath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0); #endif } AStringVector cFile::GetFolderContents(const AString & a_Folder) { AStringVector AllFiles; #ifdef _WIN32 // If the folder name doesn't contain the terminating slash / backslash, add it: AString FileFilter = a_Folder; if ( !FileFilter.empty() && (FileFilter[FileFilter.length() - 1] != '\\') && (FileFilter[FileFilter.length() - 1] != '/') ) { FileFilter.push_back('\\'); } // Find all files / folders: FileFilter.append("*.*"); HANDLE hFind; WIN32_FIND_DATA FindFileData; if ((hFind = FindFirstFile(FileFilter.c_str(), &FindFileData)) != INVALID_HANDLE_VALUE) { do { AllFiles.push_back(FindFileData.cFileName); } while (FindNextFile(hFind, &FindFileData)); FindClose(hFind); } #else // _WIN32 DIR * dp; struct dirent *dirp; AString Folder = a_Folder; if (Folder.empty()) { Folder = "."; } if ((dp = opendir(Folder.c_str())) == NULL) { LOGERROR("Error (%i) opening directory \"%s\"\n", errno, Folder.c_str()); } else { while ((dirp = readdir(dp)) != NULL) { AllFiles.push_back(dirp->d_name); } closedir(dp); } #endif // else _WIN32 return AllFiles; } AString cFile::ReadWholeFile(const AString & a_FileName) { cFile f; if (!f.Open(a_FileName, fmRead)) { return ""; } AString Contents; f.ReadRestOfFile(Contents); return Contents; } int cFile::Printf(const char * a_Fmt, ...) { AString buf; va_list args; va_start(args, a_Fmt); AppendVPrintf(buf, a_Fmt, args); va_end(args); return Write(buf.c_str(), (int)buf.length()); } void cFile::Flush(void) { fflush(m_File); }
#include "memorymodule.h" MemoryModule::~MemoryModule() { }
/* * RegisterIO.cpp * * Created on: Jul 29, 2015 * Author: Scott */ #include "RegisterIO.h" #include "../include/IMURegisters.h" #include "delay.h" RegisterIO::RegisterIO( IRegisterIO *io_provider, uint8_t update_rate_hz, IIOCompleteNotification *notify_sink, IBoardCapabilities *board_capabilities ) { this->io_provider = io_provider; this->update_rate_hz = update_rate_hz; this->board_capabilities = board_capabilities; this->notify_sink = notify_sink; this->last_sensor_timestamp = 0; this->update_count = 0; this->byte_count = 0; this->last_update_time = 0; this->stop = false; raw_data_update = {0}; ahrs_update = {}; ahrspos_update = {}; board_state = {0}; board_id = {0}; } static const double IO_TIMEOUT_SECONDS = 1.0; static const double DELAY_OVERHEAD_MILLISECONDS = 4.0; RegisterIO::~RegisterIO() { } bool RegisterIO::IsConnected() { double time_since_last_update = Timer::GetFPGATimestamp() - this->last_update_time; return time_since_last_update <= IO_TIMEOUT_SECONDS; } double RegisterIO::GetByteCount() { return byte_count; } double RegisterIO::GetUpdateCount() { return update_count; } void RegisterIO::SetUpdateRateHz(uint8_t update_rate) { io_provider->Write( NAVX_REG_UPDATE_RATE_HZ, update_rate); } void RegisterIO::ZeroYaw() { io_provider->Write( NAVX_REG_INTEGRATION_CTL, NAVX_INTEGRATION_CTL_RESET_YAW ); notify_sink->YawResetComplete(); } void RegisterIO::ZeroDisplacement() { io_provider->Write( NAVX_REG_INTEGRATION_CTL, NAVX_INTEGRATION_CTL_RESET_DISP_X | NAVX_INTEGRATION_CTL_RESET_DISP_Y | NAVX_INTEGRATION_CTL_RESET_DISP_Z ); } void RegisterIO::Run() { io_provider->Init(); /* Initial Device Configuration */ SetUpdateRateHz(this->update_rate_hz); GetConfiguration(); double update_rate_ms = 1.0/(double)this->update_rate_hz; if ( update_rate_ms > DELAY_OVERHEAD_MILLISECONDS) { update_rate_ms -= DELAY_OVERHEAD_MILLISECONDS; } /* IO Loop */ while (!stop) { if ( board_state.update_rate_hz != this->update_rate_hz ) { SetUpdateRateHz(this->update_rate_hz); } GetCurrentData(); delayMillis(update_rate_ms); } } void RegisterIO::Stop() { stop = true; } void RegisterIO::EnableLogging(bool enable) { io_provider->EnableLogging(enable); } bool RegisterIO::GetConfiguration() { bool success = false; int retry_count = 0; while ( retry_count < 3 && !success ) { char config[NAVX_REG_SENSOR_STATUS_H+1] = {0}; if ( io_provider->Read(NAVX_REG_WHOAMI, (uint8_t *)config, sizeof(config)) ) { board_id.hw_rev = config[NAVX_REG_HW_REV]; board_id.fw_ver_major = config[NAVX_REG_FW_VER_MAJOR]; board_id.fw_ver_minor = config[NAVX_REG_FW_VER_MINOR]; board_id.type = config[NAVX_REG_WHOAMI]; notify_sink->SetBoardID(board_id); board_state.cal_status = config[NAVX_REG_CAL_STATUS]; board_state.op_status = config[NAVX_REG_OP_STATUS]; board_state.selftest_status = config[NAVX_REG_SELFTEST_STATUS]; board_state.sensor_status = IMURegisters::decodeProtocolUint16(config + NAVX_REG_SENSOR_STATUS_L); board_state.gyro_fsr_dps = IMURegisters::decodeProtocolUint16(config + NAVX_REG_GYRO_FSR_DPS_L); board_state.accel_fsr_g = (int16_t)config[NAVX_REG_ACCEL_FSR_G]; board_state.update_rate_hz = config[NAVX_REG_UPDATE_RATE_HZ]; board_state.capability_flags = IMURegisters::decodeProtocolUint16(config + NAVX_REG_CAPABILITY_FLAGS_L); notify_sink->SetBoardState(board_state); success = true; } else { success = false; delayMillis(50); } retry_count++; } return success; } void RegisterIO::GetCurrentData() { uint8_t first_address = NAVX_REG_UPDATE_RATE_HZ; bool displacement_registers = board_capabilities->IsDisplacementSupported(); uint8_t buffer_len; char curr_data[NAVX_REG_LAST + 1]; /* If firmware supports displacement data, acquire it - otherwise implement */ /* similar (but potentially less accurate) calculations on this processor. */ if ( displacement_registers ) { buffer_len = NAVX_REG_LAST + 1 - first_address; } else { buffer_len = NAVX_REG_QUAT_OFFSET_Z_H + 1 - first_address; } if ( io_provider->Read(first_address,(uint8_t *)curr_data, buffer_len) ) { long sensor_timestamp = IMURegisters::decodeProtocolUint32(curr_data + NAVX_REG_TIMESTAMP_L_L-first_address); if ( sensor_timestamp == last_sensor_timestamp ) { return; } last_sensor_timestamp = sensor_timestamp; ahrspos_update.op_status = curr_data[NAVX_REG_OP_STATUS - first_address]; ahrspos_update.selftest_status = curr_data[NAVX_REG_SELFTEST_STATUS - first_address]; ahrspos_update.cal_status = curr_data[NAVX_REG_CAL_STATUS]; ahrspos_update.sensor_status = curr_data[NAVX_REG_SENSOR_STATUS_L - first_address]; ahrspos_update.yaw = IMURegisters::decodeProtocolSignedHundredthsFloat(curr_data + NAVX_REG_YAW_L-first_address); ahrspos_update.pitch = IMURegisters::decodeProtocolSignedHundredthsFloat(curr_data + NAVX_REG_PITCH_L-first_address); ahrspos_update.roll = IMURegisters::decodeProtocolSignedHundredthsFloat(curr_data + NAVX_REG_ROLL_L-first_address); ahrspos_update.compass_heading = IMURegisters::decodeProtocolUnsignedHundredthsFloat(curr_data + NAVX_REG_HEADING_L-first_address); ahrspos_update.mpu_temp = IMURegisters::decodeProtocolSignedHundredthsFloat(curr_data + NAVX_REG_MPU_TEMP_C_L - first_address); ahrspos_update.linear_accel_x = IMURegisters::decodeProtocolSignedThousandthsFloat(curr_data + NAVX_REG_LINEAR_ACC_X_L-first_address); ahrspos_update.linear_accel_y = IMURegisters::decodeProtocolSignedThousandthsFloat(curr_data + NAVX_REG_LINEAR_ACC_Y_L-first_address); ahrspos_update.linear_accel_z = IMURegisters::decodeProtocolSignedThousandthsFloat(curr_data + NAVX_REG_LINEAR_ACC_Z_L-first_address); ahrspos_update.altitude = IMURegisters::decodeProtocol1616Float(curr_data + NAVX_REG_ALTITUDE_D_L - first_address); ahrspos_update.barometric_pressure = IMURegisters::decodeProtocol1616Float(curr_data + NAVX_REG_PRESSURE_DL - first_address); ahrspos_update.fused_heading = IMURegisters::decodeProtocolUnsignedHundredthsFloat(curr_data + NAVX_REG_FUSED_HEADING_L-first_address); ahrspos_update.quat_w = ((float)IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_QUAT_W_L-first_address)) / 32768.0f; ahrspos_update.quat_x = ((float)IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_QUAT_X_L-first_address)) / 32768.0f; ahrspos_update.quat_y = ((float)IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_QUAT_Y_L-first_address)) / 32768.0f; ahrspos_update.quat_z = ((float)IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_QUAT_Z_L-first_address)) / 32768.0f; if ( displacement_registers ) { ahrspos_update.vel_x = IMURegisters::decodeProtocol1616Float(curr_data + NAVX_REG_VEL_X_I_L-first_address); ahrspos_update.vel_y = IMURegisters::decodeProtocol1616Float(curr_data + NAVX_REG_VEL_Y_I_L-first_address); ahrspos_update.vel_z = IMURegisters::decodeProtocol1616Float(curr_data + NAVX_REG_VEL_Z_I_L-first_address); ahrspos_update.disp_x = IMURegisters::decodeProtocol1616Float(curr_data + NAVX_REG_DISP_X_I_L-first_address); ahrspos_update.disp_y = IMURegisters::decodeProtocol1616Float(curr_data + NAVX_REG_DISP_Y_I_L-first_address); ahrspos_update.disp_z = IMURegisters::decodeProtocol1616Float(curr_data + NAVX_REG_DISP_Z_I_L-first_address); notify_sink->SetAHRSPosData(ahrspos_update, sensor_timestamp); } else { ahrs_update.op_status = ahrspos_update.op_status; ahrs_update.selftest_status = ahrspos_update.selftest_status; ahrs_update.cal_status = ahrspos_update.cal_status; ahrs_update.sensor_status = ahrspos_update.sensor_status; ahrs_update.yaw = ahrspos_update.yaw; ahrs_update.pitch = ahrspos_update.pitch; ahrs_update.roll = ahrspos_update.roll; ahrs_update.compass_heading = ahrspos_update.compass_heading; ahrs_update.mpu_temp = ahrspos_update.mpu_temp; ahrs_update.linear_accel_x = ahrspos_update.linear_accel_x; ahrs_update.linear_accel_y = ahrspos_update.linear_accel_y; ahrs_update.linear_accel_z = ahrspos_update.linear_accel_z; ahrs_update.altitude = ahrspos_update.altitude; ahrs_update.barometric_pressure = ahrspos_update.barometric_pressure; ahrs_update.fused_heading = ahrspos_update.fused_heading; notify_sink->SetAHRSData( ahrs_update, sensor_timestamp ); } board_state.cal_status = curr_data[NAVX_REG_CAL_STATUS-first_address]; board_state.op_status = curr_data[NAVX_REG_OP_STATUS-first_address]; board_state.selftest_status = curr_data[NAVX_REG_SELFTEST_STATUS-first_address]; board_state.sensor_status = IMURegisters::decodeProtocolUint16(curr_data + NAVX_REG_SENSOR_STATUS_L-first_address); board_state.update_rate_hz = curr_data[NAVX_REG_UPDATE_RATE_HZ-first_address]; board_state.gyro_fsr_dps = IMURegisters::decodeProtocolUint16(curr_data + NAVX_REG_GYRO_FSR_DPS_L); board_state.accel_fsr_g = (int16_t)curr_data[NAVX_REG_ACCEL_FSR_G]; board_state.capability_flags= IMURegisters::decodeProtocolUint16(curr_data + NAVX_REG_CAPABILITY_FLAGS_L-first_address); notify_sink->SetBoardState(board_state); raw_data_update.gyro_x = IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_GYRO_X_L-first_address); raw_data_update.gyro_y = IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_GYRO_Y_L-first_address); raw_data_update.gyro_z = IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_GYRO_Z_L-first_address); raw_data_update.accel_x = IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_ACC_X_L-first_address); raw_data_update.accel_y = IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_ACC_Y_L-first_address); raw_data_update.accel_z = IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_ACC_Z_L-first_address); raw_data_update.mag_x = IMURegisters::decodeProtocolInt16(curr_data + NAVX_REG_MAG_X_L-first_address); raw_data_update.temp_c = ahrspos_update.mpu_temp; notify_sink->SetRawData(raw_data_update, sensor_timestamp); this->last_update_time = Timer::GetFPGATimestamp(); byte_count += buffer_len; update_count++; } }
#include <ruckig/ruckig.hpp> #include <ruckig/roots.hpp> namespace ruckig { PositionStep1::PositionStep1(double p0, double v0, double a0, double pf, double vf, double af, double vMax, double vMin, double aMax, double aMin, double jMax): v0(v0), a0(a0), vf(vf), af(af), _vMax(vMax), _vMin(vMin), _aMax(aMax), _aMin(aMin), _jMax(jMax) { pd = pf - p0; v0_v0 = v0 * v0; vf_vf = vf * vf; a0_a0 = a0 * a0; af_af = af * af; a0_p3 = a0 * a0_a0; a0_p4 = a0_a0 * a0_a0; af_p3 = af * af_af; af_p4 = af_af * af_af; // max values needs to be invariant to plus minus sign change jMax_jMax = jMax * jMax; } void PositionStep1::time_all_vel(Profile& profile, double vMax, double vMin, double aMax, double aMin, double jMax, bool) { // ACC0_ACC1_VEL profile.t[0] = (-a0 + aMax)/jMax; profile.t[1] = (a0_a0/2 - aMax*aMax - jMax*(v0 - vMax))/(aMax*jMax); profile.t[2] = aMax/jMax; profile.t[3] = (3*(a0_p4*aMin - af_p4*aMax) + 8*aMax*aMin*(af_p3 - a0_p3 + 3*jMax*(a0*v0 - af*vf)) + 6*a0_a0*aMin*(aMax*aMax - 2*jMax*v0) - 6*af_af*aMax*(aMin*aMin - 2*jMax*vf) - 12*jMax*(aMax*aMin*(aMax*(v0 + vMax) - aMin*(vf + vMax) - 2*jMax*pd) + (aMin - aMax)*jMax*vMax*vMax + jMax*(aMax*vf_vf - aMin*v0_v0)))/(24*aMax*aMin*jMax_jMax*vMax); profile.t[4] = -aMin/jMax; profile.t[5] = -(af_af/2 - aMin*aMin - jMax*(vf - vMax))/(aMin*jMax); profile.t[6] = profile.t[4] + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::ACC0_ACC1_VEL>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } // ACC1_VEL const double t_acc0 = std::sqrt(a0_a0/(2*jMax_jMax) + (vMax - v0)/jMax); profile.t[0] = t_acc0 - a0/jMax; profile.t[1] = 0; profile.t[2] = t_acc0; profile.t[3] = -(3*af_p4 - 8*aMin*(af_p3 - a0_p3) - 24*aMin*jMax*(a0*v0 - af*vf) + 6*af_af*(aMin*aMin - 2*jMax*vf) - 12*jMax*(2*aMin*jMax*pd + aMin*aMin*(vf + vMax) + jMax*(vMax*vMax - vf_vf) + aMin*t_acc0*(a0_a0 - 2*jMax*(v0 + vMax))))/(24*aMin*jMax_jMax*vMax); // profile.t[4] = -aMin/jMax; // profile.t[5] = -(af_af/2 - aMin*aMin + jMax*(vMax - vf))/(aMin*jMax); // profile.t[6] = profile.t[4] + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::ACC1_VEL>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } // ACC0_VEL const double t_acc1 = std::sqrt(af_af/(2*jMax_jMax) + (vMax - vf)/jMax); profile.t[0] = (-a0 + aMax)/jMax; profile.t[1] = (a0_a0/2 - aMax*aMax - jMax*(v0 - vMax))/(aMax*jMax); profile.t[2] = aMax/jMax; profile.t[3] = (3*a0_p4 + 8*aMax*(af_p3 - a0_p3) + 24*aMax*jMax*(a0*v0 - af*vf) + 6*a0_a0*(aMax*aMax - 2*jMax*v0) - 12*jMax*(-2*aMax*jMax*pd + aMax*aMax*(v0 + vMax) + jMax*(vMax*vMax - v0_v0) + aMax*t_acc1*(-af_af + 2*(vf + vMax)*jMax)))/(24*aMax*jMax_jMax*vMax); profile.t[4] = t_acc1; profile.t[5] = 0; profile.t[6] = t_acc1 + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::ACC0_VEL>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } // VEL // Solution 3/4 profile.t[0] = t_acc0 - a0/jMax; profile.t[1] = 0; profile.t[2] = t_acc0; profile.t[3] = (af_p3 - a0_p3)/(3*jMax_jMax*vMax) + (a0*v0 - af*vf + (af_af*t_acc1 + a0_a0*t_acc0)/2)/(jMax*vMax) - (v0/vMax + 1.0)*t_acc0 - (vf/vMax + 1.0)*t_acc1 + pd/vMax; // profile.t[4] = t_acc1; // profile.t[5] = 0; // profile.t[6] = t_acc1 + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::VEL>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); } } void PositionStep1::time_acc0_acc1(Profile& profile, double vMax, double vMin, double aMax, double aMin, double jMax, bool return_after_found) { double h1 = (3*(af_p4*aMax - a0_p4*aMin) + aMax*aMin*(8*(a0_p3 - af_p3) + 3*aMax*aMin*(aMax - aMin) + 6*aMin*af_af - 6*aMax*a0_a0) + 12*jMax*(aMax*aMin*((aMax - 2*a0)*v0 - (aMin - 2*af)*vf) + aMin*a0_a0*v0 - aMax*af_af*vf))/(3*(aMax - aMin)*jMax_jMax) + 4*(aMax*vf_vf - aMin*v0_v0 - 2*aMin*aMax*pd)/(aMax - aMin); if (h1 >= 0) { h1 = std::sqrt(h1) / 2; const double h2 = a0_a0/(2*aMax*jMax) + (aMin - 2*aMax)/(2*jMax) - v0/aMax; const double h3 = -af_af/(2*aMin*jMax) - (aMax - 2*aMin)/(2*jMax) + vf/aMin; // UDDU: Solution 2 if (h2 > h1/aMax && h3 > -h1/aMin) { profile.t[0] = (-a0 + aMax)/jMax; profile.t[1] = h2 - h1/aMax; profile.t[2] = aMax/jMax; profile.t[3] = 0; profile.t[4] = -aMin/jMax; profile.t[5] = h3 + h1/aMin; profile.t[6] = profile.t[4] + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::ACC0_ACC1, true>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); if (return_after_found) { return; } } } // UDDU: Solution 1 if (h2 > -h1/aMax && h3 > h1/aMin) { profile.t[0] = (-a0 + aMax)/jMax; profile.t[1] = h2 + h1/aMax; profile.t[2] = aMax/jMax; profile.t[3] = 0; profile.t[4] = -aMin/jMax; profile.t[5] = h3 - h1/aMin; profile.t[6] = profile.t[4] + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::ACC0_ACC1, true>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); } } } } void PositionStep1::time_all_none_acc0_acc1(Profile& profile, double vMax, double vMin, double aMax, double aMin, double jMax, bool return_after_found) { // NONE UDDU / UDUD Strategy: t7 == 0 (equals UDDU), this one is in particular prone to numerical issues const double h2_none = (a0_a0 - af_af)/(2*jMax) + (vf - v0); const double h2_h2 = h2_none*h2_none; const double t_min_none = (a0 - af)/jMax; const double t_max_none = (aMax - aMin)/jMax; std::array<double, 4> polynom_none; polynom_none[0] = 0; polynom_none[1] = (-2*(a0_a0 + af_af - 2*jMax*(v0 + vf)))/jMax_jMax; polynom_none[2] = 4*(a0_p3 - af_p3 + 3*jMax*(af*vf - a0*v0))/(3*jMax*jMax_jMax) - 4*pd/jMax; polynom_none[3] = -h2_h2/jMax_jMax; // ACC0 const double h3_acc0 = (a0_a0 - af_af)/(2*aMax*jMax) + (vf - v0)/aMax; const double t_min_acc0 = (aMax - af)/jMax; const double t_max_acc0 = (aMax - aMin)/jMax; const double h0_acc0 = 3*(af_p4 - a0_p4) + 8*(a0_p3 - af_p3)*aMax + 24*aMax*jMax*(af*vf - a0*v0) - 6*a0_a0*(aMax*aMax - 2*jMax*v0) + 6*af_af*(aMax*aMax - 2*jMax*vf) + 12*jMax*(jMax*(vf_vf - v0_v0 - 2*aMax*pd) - aMax*aMax*(vf - v0)); const double h2_acc0 = -af_af + aMax*aMax + 2*jMax*vf; std::array<double, 4> polynom_acc0; polynom_acc0[0] = -2*aMax/jMax; polynom_acc0[1] = h2_acc0/jMax_jMax; polynom_acc0[2] = 0; polynom_acc0[3] = h0_acc0/(12*jMax_jMax*jMax_jMax); // ACC1 const double h3_acc1 = -(a0_a0 + af_af)/(2*jMax*aMin) + aMin/jMax + (vf - v0)/aMin; const double t_min_acc1 = -(a0 - aMin)/jMax; const double t_max_acc1 = (-a0 + aMax)/jMax; const double h0_acc1 = (a0_p4 - af_p4)/4 + 2*(af_p3 - a0_p3)*aMin/3 + (a0_a0 - af_af)*aMin*aMin/2 + jMax*(af_af*vf + a0_a0*v0 + 2*aMin*(jMax*pd - a0*v0 - af*vf) + aMin*aMin*(v0 + vf) + jMax*(v0_v0 - vf_vf)); const double h2_acc1 = a0_a0 - a0*aMin + 2*jMax*v0; std::array<double, 4> polynom_acc1; polynom_acc1[0] = 2*(2*a0 - aMin)/jMax; polynom_acc1[1] = (5*a0_a0 + aMin*(aMin - 6*a0) + 2*jMax*v0)/jMax_jMax; polynom_acc1[2] = 2*(a0 - aMin)*h2_acc1/(jMax_jMax*jMax); polynom_acc1[3] = h0_acc1/(jMax_jMax*jMax_jMax); auto roots_none = roots::solveQuartMonic(polynom_none); auto roots_acc0 = roots::solveQuartMonic(polynom_acc0); auto roots_acc1 = roots::solveQuartMonic(polynom_acc1); for (double t: roots_none) { if (t < t_min_none || t > t_max_none) { continue; } // Single Newton-step (regarding pd) if (t > DBL_EPSILON) { const double h1 = jMax*t*t; const double orig = -h2_h2/(4*jMax*t) + h2_none*(af/jMax + t) + (4*a0_p3 + 2*af_p3 - 6*a0_a0*(af + 2*jMax*t) + 12*(af - a0)*jMax*v0 + 3*jMax_jMax*(-4*pd + (h1 + 8*v0)*t))/(12*jMax_jMax); const double deriv = h2_none + 2*v0 - a0_a0/jMax + h2_h2/(4*h1) + (3*h1)/4; t -= orig / deriv; } const double h0 = h2_none/(2*jMax*t); profile.t[0] = h0 + t/2 - a0/jMax; profile.t[1] = 0; profile.t[2] = t; profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = 0; profile.t[6] = -h0 + t/2 + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::NONE>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); if (return_after_found) { return; } } } for (double t: roots_acc0) { if (t < t_min_acc0 || t > t_max_acc0) { continue; } // Single Newton step (regarding pd) if (t > DBL_EPSILON) { const double h1 = jMax*t; const double orig = h0_acc0/(24*aMax*jMax_jMax) + t*t*(h2_acc0 + h1*(h1 - 2*aMax))/(2*aMax); const double deriv = t*(h2_acc0 + h1*(2*h1 - 3*aMax))/aMax; t -= orig / deriv; } profile.t[0] = (-a0 + aMax)/jMax; profile.t[1] = h3_acc0 - 2*t + jMax/aMax*t*t; profile.t[2] = t; profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = 0; profile.t[6] = (af - aMax)/jMax + t; if (profile.check<JerkSigns::UDDU, Limits::ACC0>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); if (return_after_found) { return; } } } for (double t: roots_acc1) { if (t < t_min_acc1 || t > t_max_acc1) { continue; } // Double Newton step (regarding pd) if (t > DBL_EPSILON) { const double h5 = a0_p3 + 2*jMax*a0*v0; double h1 = jMax*t; double orig = -(h0_acc1/2 + h1*(h5 + a0*(aMin - 2*h1)*(aMin - h1) + a0_a0*(5*h1/2 - 2*aMin) + aMin*aMin*h1/2 + jMax*(h1/2 - aMin)*(h1*t + 2*v0)))/(aMin*jMax_jMax); double deriv = (aMin - a0 - h1)*(h2_acc1 + h1*(4*a0 - aMin + 2*h1))/(aMin*jMax); t -= std::min(orig / deriv, t); h1 = jMax*t; orig = -(h0_acc1/2 + h1*(h5 + a0*(aMin - 2*h1)*(aMin - h1) + a0_a0*(5*h1/2 - 2*aMin) + aMin*aMin*h1/2 + jMax*(h1/2 - aMin)*(h1*t + 2*v0)))/(aMin*jMax_jMax); if (std::abs(orig) > 1e-9) { deriv = (aMin - a0 - h1)*(h2_acc1 + h1*(4*a0 - aMin + 2*h1))/(aMin*jMax); t -= orig / deriv; h1 = jMax*t; orig = -(h0_acc1/2 + h1*(h5 + a0*(aMin - 2*h1)*(aMin - h1) + a0_a0*(5*h1/2 - 2*aMin) + aMin*aMin*h1/2 + jMax*(h1/2 - aMin)*(h1*t + 2*v0)))/(aMin*jMax_jMax); if (std::abs(orig) > 1e-9) { deriv = (aMin - a0 - h1)*(h2_acc1 + h1*(4*a0 - aMin + 2*h1))/(aMin*jMax); t -= orig / deriv; } } } profile.t[0] = t; profile.t[1] = 0; profile.t[2] = (a0 - aMin)/jMax + t; profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = h3_acc1 - (2*a0 + jMax*t)*t/aMin; profile.t[6] = (af - aMin)/jMax; if (profile.check<JerkSigns::UDDU, Limits::ACC1, true>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); if (return_after_found) { return; } } } } void PositionStep1::time_acc1_vel_two_step(Profile& profile, double vMax, double vMin, double aMax, double aMin, double jMax) { profile.t[0] = 0; profile.t[1] = 0; profile.t[2] = a0/jMax; profile.t[3] = -(3*af_p4 - 8*aMin*(af_p3 - a0_p3) - 24*aMin*jMax*(a0*v0 - af*vf) + 6*af_af*(aMin*aMin - 2*jMax*vf) - 12*jMax*(2*aMin*jMax*pd + aMin*aMin*(vf + vMax) + jMax*(vMax*vMax - vf_vf) + aMin*a0*(a0_a0 - 2*jMax*(v0 + vMax))/jMax))/(24*aMin*jMax_jMax*vMax); profile.t[4] = -aMin/jMax; profile.t[5] = -(af_af/2 - aMin*aMin + jMax*(vMax - vf))/(aMin*jMax); profile.t[6] = profile.t[4] + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::ACC1_VEL>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); } } void PositionStep1::time_acc0_two_step(Profile& profile, double vMax, double vMin, double aMax, double aMin, double jMax) { // Two step { profile.t[0] = 0; profile.t[1] = (af_af - a0_a0 + 2*jMax*(vf - v0))/(2*a0*jMax); profile.t[2] = (a0 - af)/jMax; profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = 0; profile.t[6] = 0; if (profile.check<JerkSigns::UDDU, Limits::ACC0>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } } // Three step - Removed pf { profile.t[0] = (-a0 + aMax)/jMax; profile.t[1] = (a0_a0 + af_af - 2*aMax*aMax + 2*jMax*(vf - v0))/(2*aMax*jMax); profile.t[2] = (-af + aMax)/jMax; profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = 0; profile.t[6] = 0; if (profile.check<JerkSigns::UDDU, Limits::ACC0>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } } // Three step - Removed aMax { const double h0 = 3*(af_af - a0_a0 + 2*jMax*(v0 + vf)); const double h2 = a0_p3 + 2*af_p3 + 6*jMax_jMax*pd + 6*(af - a0)*jMax*vf - 3*a0*af_af; const double h1 = std::sqrt(2*(2*h2*h2 + h0*(a0_p4 - 6*a0_a0*(af_af + 2*jMax*vf) + 8*a0*(af_p3 + 3*jMax_jMax*pd + 3*af*jMax*vf) - 3*(af_p4 + 4*af_af*jMax*vf + 4*jMax_jMax*(vf_vf - v0_v0))))) * Abs(jMax) / jMax; profile.t[0] = (4*af_p3 + 2*a0_p3 - 6*a0*af_af + 12*jMax_jMax*pd + 12*(af - a0)*jMax*vf + h1)/(2*jMax*h0); profile.t[1] = -h1/(jMax*h0); profile.t[2] = (-4*a0_p3 - 2*af_p3 + 6*a0_a0*af + 12*jMax_jMax*pd - 12*(af - a0)*jMax*v0 + h1)/(2*jMax*h0); profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = 0; profile.t[6] = 0; if (profile.check<JerkSigns::UDDU, Limits::ACC0>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } } // Three step - t=(aMax - aMin)/jMax { const double t = (aMax - aMin)/jMax; profile.t[0] = (-a0 + aMax)/jMax; profile.t[1] = (a0_a0 - af_af)/(2*aMax*jMax) + (vf - v0 + jMax*t*t)/aMax - 2*t; profile.t[2] = t; profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = 0; profile.t[6] = (af - aMin)/jMax; if (profile.check<JerkSigns::UDDU, Limits::ACC0>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } } } void PositionStep1::time_vel_two_step(Profile& profile, double vMax, double vMin, double aMax, double aMin, double jMax) { const double h1 = std::sqrt(af_af/(2*jMax_jMax) + (vMax - vf)/jMax); // Four step { // Solution 3/4 profile.t[0] = -a0/jMax; profile.t[1] = 0; profile.t[2] = 0; profile.t[3] = (af_p3 - a0_p3)/(3*jMax_jMax*vMax) + (a0*v0 - af*vf + (af_af*h1)/2)/(jMax*vMax) - (vf/vMax + 1.0)*h1 + pd/vMax; profile.t[4] = h1; profile.t[5] = 0; profile.t[6] = h1 + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::VEL>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } } // Four step { profile.t[0] = 0; profile.t[1] = 0; profile.t[2] = a0/jMax; profile.t[3] = (af_p3 - a0_p3)/(3*jMax_jMax*vMax) + (a0*v0 - af*vf + (af_af*h1 + a0_p3/jMax)/2)/(jMax*vMax) - (v0/vMax + 1.0)*a0/jMax - (vf/vMax + 1.0)*h1 + pd/vMax; profile.t[4] = h1; profile.t[5] = 0; profile.t[6] = h1 + af/jMax; if (profile.check<JerkSigns::UDDU, Limits::VEL>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } } } void PositionStep1::time_none_two_step(Profile& profile, double vMax, double vMin, double aMax, double aMin, double jMax) { // Two step { const double h0 = std::sqrt((a0_a0 + af_af)/2 + jMax*(vf - v0)) * Abs(jMax) / jMax; profile.t[0] = (h0 - a0)/jMax; profile.t[1] = 0; profile.t[2] = (h0 - af)/jMax; profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = 0; profile.t[6] = 0; if (profile.check<JerkSigns::UDDU, Limits::NONE>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } } // Single step { profile.t[0] = (af - a0)/jMax; profile.t[1] = 0; profile.t[2] = 0; profile.t[3] = 0; profile.t[4] = 0; profile.t[5] = 0; profile.t[6] = 0; if (profile.check<JerkSigns::UDDU, Limits::NONE>(jMax, vMax, vMin, aMax, aMin)) { add_profile(profile, jMax); return; } } } bool PositionStep1::get_profile(const Profile& input, Block& block) { Profile profile = input; valid_profile_counter = 0; if (std::abs(vf) < DBL_EPSILON && std::abs(af) < DBL_EPSILON) { const double vMax = (pd >= 0) ? _vMax : _vMin; const double vMin = (pd >= 0) ? _vMin : _vMax; const double aMax = (pd >= 0) ? _aMax : _aMin; const double aMin = (pd >= 0) ? _aMin : _aMax; const double jMax = (pd >= 0) ? _jMax : -_jMax; if (std::abs(v0) < DBL_EPSILON && std::abs(a0) < DBL_EPSILON && std::abs(pd) < DBL_EPSILON) { time_all_none_acc0_acc1(profile, vMax, vMin, aMax, aMin, jMax, true); } else { // There is no blocked interval when vf==0 && af==0, so return after first found profile time_all_vel(profile, vMax, vMin, aMax, aMin, jMax, true); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_all_none_acc0_acc1(profile, vMax, vMin, aMax, aMin, jMax, true); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_acc0_acc1(profile, vMax, vMin, aMax, aMin, jMax, true); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_all_vel(profile, vMin, vMax, aMin, aMax, -jMax, true); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_all_none_acc0_acc1(profile, vMin, vMax, aMin, aMax, -jMax, true); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_acc0_acc1(profile, vMin, vMax, aMin, aMax, -jMax, true); } } else { time_all_vel(profile, _vMax, _vMin, _aMax, _aMin, _jMax, false); time_all_vel(profile, _vMin, _vMax, _aMin, _aMax, -_jMax, false); time_all_none_acc0_acc1(profile, _vMax, _vMin, _aMax, _aMin, _jMax, false); time_all_none_acc0_acc1(profile, _vMin, _vMax, _aMin, _aMax, -_jMax, false); time_acc0_acc1(profile, _vMax, _vMin, _aMax, _aMin, _jMax, false); time_acc0_acc1(profile, _vMin, _vMax, _aMin, _aMax, -_jMax, false); } if (valid_profile_counter == 0) { time_none_two_step(profile, _vMax, _vMin, _aMax, _aMin, _jMax); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_none_two_step(profile, _vMin, _vMax, _aMin, _aMax, -_jMax); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_acc0_two_step(profile, _vMax, _vMin, _aMax, _aMin, _jMax); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_acc0_two_step(profile, _vMin, _vMax, _aMin, _aMax, -_jMax); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_vel_two_step(profile, _vMax, _vMin, _aMax, _aMin, _jMax); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_vel_two_step(profile, _vMin, _vMax, _aMin, _aMax, -_jMax); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_acc1_vel_two_step(profile, _vMax, _vMin, _aMax, _aMin, _jMax); if (valid_profile_counter > 0) { return Block::calculate_block(block, valid_profiles, valid_profile_counter); } time_acc1_vel_two_step(profile, _vMin, _vMax, _aMin, _aMax, -_jMax); } return Block::calculate_block(block, valid_profiles, valid_profile_counter); } } // namespace ruckig
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *testcurrency_strings[] = { QT_TRANSLATE_NOOP("testcurrency-core", " mints deleted\n"), QT_TRANSLATE_NOOP("testcurrency-core", " mints updated, "), QT_TRANSLATE_NOOP("testcurrency-core", " unconfirmed transactions removed\n"), QT_TRANSLATE_NOOP("testcurrency-core", "" "(1 = keep tx meta data e.g. account owner and payment request information, 2 " "= drop tx meta data)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Allow JSON-RPC connections from specified source. Valid for <ip> are a " "single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or " "a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"), QT_TRANSLATE_NOOP("testcurrency-core", "" "An error occurred while setting up the RPC address %s port %u for listening: " "%s"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Bind to given address and always listen on it. Use [host]:port notation for " "IPv6"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Bind to given address and whitelist peers connecting to it. Use [host]:port " "notation for IPv6"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Bind to given address to listen for JSON-RPC connections. Use [host]:port " "notation for IPv6. This option can be specified multiple times (default: " "bind to all interfaces)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Calculated accumulator checkpoint is not what is recorded by block index"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Cannot obtain a lock on data directory %s. Testcurrency Core is probably already " "running."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Change automatic finalized budget voting behavior. mode=auto: Vote for only " "exact finalized budget match to my generated budget. (string, default: auto)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Continuously rate-limit free transactions to <n>*1000 bytes per minute " "(default:%u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Create new files with system default permissions, instead of umask 077 (only " "effective with disabled wallet functionality)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Delete all wallet transactions and only recover those parts of the " "blockchain through -rescan on startup"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Disable all Testcurrency specific functionality (Masternodes, Obfuscation, SwiftX, " "Budgeting) (0-1, default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Distributed under the MIT software license, see the accompanying file " "COPYING or <http://www.opensource.org/licenses/mit-license.php>."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Enable automatic wallet backups triggered after each zPhr minting (0-1, " "default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Enable spork administration functionality with the appropriate private key."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Enable SwiftX, show confirmations for locked transactions (bool, default: " "%s)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Enter regression test mode, which uses a special chain in which blocks can " "be solved instantly."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Error: Listening for incoming connections failed (listen returned error %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Error: The transaction was rejected! This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds!"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Error: Unsupported argument -checklevel found. Checklevel must be level 4."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Error: Unsupported argument -socks found. Setting SOCKS version isn't " "possible anymore, only SOCKS5 proxies are supported."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Execute command when a relevant alert is received or we see a really long " "fork (%s in cmd is replaced by message)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Fees (in TEST/Kb) smaller than this are considered zero fee for relaying " "(default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Fees (in TEST/Kb) smaller than this are considered zero fee for transaction " "creation (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Flush database activity from memory pool to disk log every <n> megabytes " "(default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Found unconfirmed denominated outputs, will wait till they confirm to " "continue."), QT_TRANSLATE_NOOP("testcurrency-core", "" "If paytxfee is not set, include enough fee so transactions begin " "confirmation on average within n blocks (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "In this mode -genproclimit controls how many blocks are generated " "immediately."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Insufficient or insufficient confirmed funds, you might need to wait a few " "minutes and try again."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay " "fee of %s to prevent stuck transactions)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Keep the specified amount available for spending at all times (default: 0)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Log transaction priority and fee per kB when mining blocks (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Maintain a full transaction index, used by the getrawtransaction rpc call " "(default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Maximum size of data in data carrier transactions we relay and mine " "(default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Maximum total fees to use in a single wallet transaction, setting too low " "may abort large transactions (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Obfuscation uses exact denominated amounts to send funds, you might simply " "need to anonymize some more coins."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Output debugging information (default: %u, supplying <category> is optional)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Preferred Denomination for automatically minted Zerocoin " "(1/5/10/50/100/500/1000/5000), 0 for no preference. default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Query for peer addresses via DNS lookup, if low on addresses (default: 1 " "unless -connect)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Randomize credentials for every proxy connection. This enables Tor stream " "isolation (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Require high priority for relaying free or low-fee transactions (default:%u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Send trace/debug info to console instead of debug.log file (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Set the number of script verification threads (%u to %d, 0 = auto, <0 = " "leave that many cores free, default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Set the number of threads for coin generation if enabled (-1 = all cores, " "default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Show N confirmations for a successfully locked transaction (0-9999, default: " "%u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Support filtering of blocks and transaction with bloom filters (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "SwiftX requires inputs with at least 6 confirmations, you might need to " "wait a few minutes and try again."), QT_TRANSLATE_NOOP("testcurrency-core", "" "This is a pre-release test build - use at your own risk - do not use for " "staking or merchant applications!"), QT_TRANSLATE_NOOP("testcurrency-core", "" "This product includes software developed by the OpenSSL Project for use in " "the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software " "written by Eric Young and UPnP software written by Thomas Bernard."), QT_TRANSLATE_NOOP("testcurrency-core", "" "To use testcurrencyd, or the -server option to testcurrency-qt, you must set an rpcpassword " "in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=testcurrencyrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Testcurrency Alert\" admin@foo.com\n"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Unable to bind to %s on this computer. Testcurrency Core is probably already running."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Unable to locate enough Obfuscation denominated funds for this transaction."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Unable to locate enough Obfuscation non-denominated funds for this " "transaction that are not equal 10000 TEST."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Unable to locate enough funds for this transaction that are not equal 10000 " "TEST."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: " "%s)"), QT_TRANSLATE_NOOP("testcurrency-core", "" "Warning: -maxtxfee is set very high! Fees this large could be paid on a " "single transaction."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong Testcurrency Core will not work properly."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Warning: The network does not appear to fully agree! Some miners appear to " "be experiencing issues."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Warning: We do not appear to fully agree with our peers! You may need to " "upgrade, or other nodes may need to upgrade."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Whitelist peers connecting from the given netmask or IP address. Can be " "specified multiple times."), QT_TRANSLATE_NOOP("testcurrency-core", "" "Whitelisted peers cannot be DoS banned and their transactions are always " "relayed, even if they are already in the mempool, useful e.g. for a gateway"), QT_TRANSLATE_NOOP("testcurrency-core", "" "You must specify a masternodeprivkey in the configuration. Please see " "documentation for help."), QT_TRANSLATE_NOOP("testcurrency-core", "(46003 could be used only on mainnet)"), QT_TRANSLATE_NOOP("testcurrency-core", "(default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "(default: 1)"), QT_TRANSLATE_NOOP("testcurrency-core", "(must be 46003 for mainnet)"), QT_TRANSLATE_NOOP("testcurrency-core", "<category> can be:"), QT_TRANSLATE_NOOP("testcurrency-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("testcurrency-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("testcurrency-core", "Accept public REST requests (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Acceptable ciphers (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("testcurrency-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("testcurrency-core", "Already have that input."), QT_TRANSLATE_NOOP("testcurrency-core", "Always query for peer addresses via DNS lookup (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Attempt to force blockchain corruption recovery"), QT_TRANSLATE_NOOP("testcurrency-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("testcurrency-core", "Automatically create Tor hidden service (default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "Block creation options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Calculating missing accumulators..."), QT_TRANSLATE_NOOP("testcurrency-core", "Can't denominate: no compatible inputs left."), QT_TRANSLATE_NOOP("testcurrency-core", "Can't find random Masternode."), QT_TRANSLATE_NOOP("testcurrency-core", "Can't mix while sync in progress."), QT_TRANSLATE_NOOP("testcurrency-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("testcurrency-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Cannot resolve -whitebind address: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Cannot write default address"), QT_TRANSLATE_NOOP("testcurrency-core", "Collateral not valid."), QT_TRANSLATE_NOOP("testcurrency-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Connect through SOCKS5 proxy"), QT_TRANSLATE_NOOP("testcurrency-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("testcurrency-core", "Connection options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"), QT_TRANSLATE_NOOP("testcurrency-core", "Copyright (C) 2014-%i The Dash Core Developers"), QT_TRANSLATE_NOOP("testcurrency-core", "Copyright (C) 2015-%i The PIVX Core Developers"), QT_TRANSLATE_NOOP("testcurrency-core", "Copyright (C) 2017-%i The Testcurrency Core Developers"), QT_TRANSLATE_NOOP("testcurrency-core", "Corrupted block database detected"), QT_TRANSLATE_NOOP("testcurrency-core", "Could not parse -rpcbind value %s as network address"), QT_TRANSLATE_NOOP("testcurrency-core", "Could not parse masternode.conf"), QT_TRANSLATE_NOOP("testcurrency-core", "Debugging/Testing options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Delete blockchain folders and resync from scratch"), QT_TRANSLATE_NOOP("testcurrency-core", "Disable OS notifications for incoming transactions (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Disable safemode, override a real safe mode event (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("testcurrency-core", "Display the stake modifier calculations in the debug.log file."), QT_TRANSLATE_NOOP("testcurrency-core", "Display verbose coin stake messages in the debug.log file."), QT_TRANSLATE_NOOP("testcurrency-core", "Do not load the wallet and disable wallet RPC calls"), QT_TRANSLATE_NOOP("testcurrency-core", "Do you want to rebuild the block database now?"), QT_TRANSLATE_NOOP("testcurrency-core", "Done loading"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable automatic Zerocoin minting (0-1, default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable publish hash block in <address>"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable publish hash transaction (locked via SwiftX) in <address>"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable publish hash transaction in <address>"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable publish raw block in <address>"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable publish raw transaction (locked via SwiftX) in <address>"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable publish raw transaction in <address>"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable staking functionality (0-1, default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Enable the client to act as a masternode (0-1, default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Entries are full."), QT_TRANSLATE_NOOP("testcurrency-core", "Error connecting to Masternode."), QT_TRANSLATE_NOOP("testcurrency-core", "Error initializing block database"), QT_TRANSLATE_NOOP("testcurrency-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("testcurrency-core", "Error loading block database"), QT_TRANSLATE_NOOP("testcurrency-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("testcurrency-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("testcurrency-core", "Error loading wallet.dat: Wallet requires newer version of Testcurrency Core"), QT_TRANSLATE_NOOP("testcurrency-core", "Error opening block database"), QT_TRANSLATE_NOOP("testcurrency-core", "Error reading from database, shutting down."), QT_TRANSLATE_NOOP("testcurrency-core", "Error recovering public key."), QT_TRANSLATE_NOOP("testcurrency-core", "Error"), QT_TRANSLATE_NOOP("testcurrency-core", "Error: A fatal internal error occured, see debug.log for details"), QT_TRANSLATE_NOOP("testcurrency-core", "Error: Can't select current denominated inputs"), QT_TRANSLATE_NOOP("testcurrency-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("testcurrency-core", "Error: Unsupported argument -tor found, use -onion."), QT_TRANSLATE_NOOP("testcurrency-core", "Error: Wallet locked, unable to create transaction!"), QT_TRANSLATE_NOOP("testcurrency-core", "Error: You already have pending entries in the Obfuscation pool"), QT_TRANSLATE_NOOP("testcurrency-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("testcurrency-core", "Failed to read block index"), QT_TRANSLATE_NOOP("testcurrency-core", "Failed to read block"), QT_TRANSLATE_NOOP("testcurrency-core", "Failed to write block index"), QT_TRANSLATE_NOOP("testcurrency-core", "Fee (in TEST/kB) to add to transactions you send (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Finalizing transaction."), QT_TRANSLATE_NOOP("testcurrency-core", "Force safe mode (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Found enough users, signing ( waiting %s )"), QT_TRANSLATE_NOOP("testcurrency-core", "Found enough users, signing ..."), QT_TRANSLATE_NOOP("testcurrency-core", "Generate coins (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "How many blocks to check at startup (default: %u, 0 = all)"), QT_TRANSLATE_NOOP("testcurrency-core", "If <category> is not supplied, output all debugging information."), QT_TRANSLATE_NOOP("testcurrency-core", "Importing..."), QT_TRANSLATE_NOOP("testcurrency-core", "Imports blocks from external blk000??.dat file"), QT_TRANSLATE_NOOP("testcurrency-core", "Include IP addresses in debug output (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Incompatible mode."), QT_TRANSLATE_NOOP("testcurrency-core", "Incompatible version."), QT_TRANSLATE_NOOP("testcurrency-core", "Incorrect or no genesis block found. Wrong datadir for network?"), QT_TRANSLATE_NOOP("testcurrency-core", "Information"), QT_TRANSLATE_NOOP("testcurrency-core", "Initialization sanity check failed. Testcurrency Core is shutting down."), QT_TRANSLATE_NOOP("testcurrency-core", "Input is not valid."), QT_TRANSLATE_NOOP("testcurrency-core", "Insufficient funds"), QT_TRANSLATE_NOOP("testcurrency-core", "Insufficient funds."), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid -onion address or hostname: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid -proxy address or hostname: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid amount for -maxtxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid amount for -mintxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid amount for -reservebalance=<amount>"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid amount"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid masternodeprivkey. Please see documenation."), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid netmask specified in -whitelist: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid port detected in masternode.conf"), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid private key."), QT_TRANSLATE_NOOP("testcurrency-core", "Invalid script detected."), QT_TRANSLATE_NOOP("testcurrency-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Last Obfuscation was too recent."), QT_TRANSLATE_NOOP("testcurrency-core", "Last successful Obfuscation action was too recent."), QT_TRANSLATE_NOOP("testcurrency-core", "Less than 3 mints added, unable to create spend"), QT_TRANSLATE_NOOP("testcurrency-core", "Limit size of signature cache to <n> entries (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Line: %d"), QT_TRANSLATE_NOOP("testcurrency-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Listen for connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Loading addresses..."), QT_TRANSLATE_NOOP("testcurrency-core", "Loading block index..."), QT_TRANSLATE_NOOP("testcurrency-core", "Loading budget cache..."), QT_TRANSLATE_NOOP("testcurrency-core", "Loading masternode cache..."), QT_TRANSLATE_NOOP("testcurrency-core", "Loading masternode payment cache..."), QT_TRANSLATE_NOOP("testcurrency-core", "Loading sporks..."), QT_TRANSLATE_NOOP("testcurrency-core", "Loading wallet... (%3.2f %%)"), QT_TRANSLATE_NOOP("testcurrency-core", "Loading wallet..."), QT_TRANSLATE_NOOP("testcurrency-core", "Lock is already in place."), QT_TRANSLATE_NOOP("testcurrency-core", "Lock masternodes from masternode configuration file (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Maintain at most <n> connections to peers (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Masternode options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Masternode queue is full."), QT_TRANSLATE_NOOP("testcurrency-core", "Masternode:"), QT_TRANSLATE_NOOP("testcurrency-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Missing input transaction information."), QT_TRANSLATE_NOOP("testcurrency-core", "Mixing in progress..."), QT_TRANSLATE_NOOP("testcurrency-core", "Need to specify a port with -whitebind: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "No Masternodes detected."), QT_TRANSLATE_NOOP("testcurrency-core", "No compatible Masternode found."), QT_TRANSLATE_NOOP("testcurrency-core", "No funds detected in need of denominating."), QT_TRANSLATE_NOOP("testcurrency-core", "No matching denominations found for mixing."), QT_TRANSLATE_NOOP("testcurrency-core", "Node relay options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Non-standard public key detected."), QT_TRANSLATE_NOOP("testcurrency-core", "Not compatible with existing transactions."), QT_TRANSLATE_NOOP("testcurrency-core", "Not enough file descriptors available."), QT_TRANSLATE_NOOP("testcurrency-core", "Not in the Masternode list."), QT_TRANSLATE_NOOP("testcurrency-core", "Number of automatic wallet backups (default: 10)"), QT_TRANSLATE_NOOP("testcurrency-core", "Obfuscation is idle."), QT_TRANSLATE_NOOP("testcurrency-core", "Obfuscation request complete:"), QT_TRANSLATE_NOOP("testcurrency-core", "Obfuscation request incomplete:"), QT_TRANSLATE_NOOP("testcurrency-core", "Only accept block chain matching built-in checkpoints (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"), QT_TRANSLATE_NOOP("testcurrency-core", "Options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("testcurrency-core", "Percentage of automatically minted Zerocoin (10-100, default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Preparing for resync..."), QT_TRANSLATE_NOOP("testcurrency-core", "Prepend debug output with timestamp (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Print version and exit"), QT_TRANSLATE_NOOP("testcurrency-core", "RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("testcurrency-core", "RPC server options:"), QT_TRANSLATE_NOOP("testcurrency-core", "RPC support for HTTP persistent connections (default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "Randomly drop 1 of every <n> network messages"), QT_TRANSLATE_NOOP("testcurrency-core", "Randomly fuzz 1 of every <n> network messages"), QT_TRANSLATE_NOOP("testcurrency-core", "Rebuild block chain index from current blk000??.dat files"), QT_TRANSLATE_NOOP("testcurrency-core", "Recalculating coin supply may take 30-60 minutes..."), QT_TRANSLATE_NOOP("testcurrency-core", "Recalculating supply statistics may take 30-60 minutes..."), QT_TRANSLATE_NOOP("testcurrency-core", "Receive and display P2P network alerts (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Relay and mine data carrier transactions (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Relay non-P2SH multisig (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("testcurrency-core", "Rescanning..."), QT_TRANSLATE_NOOP("testcurrency-core", "ResetMintZerocoin finished: "), QT_TRANSLATE_NOOP("testcurrency-core", "ResetSpentZerocoin finished: "), QT_TRANSLATE_NOOP("testcurrency-core", "Run a thread to flush wallet periodically (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("testcurrency-core", "Send transactions as zero-fee transactions if possible (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Server certificate file (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Server private key (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Session not complete!"), QT_TRANSLATE_NOOP("testcurrency-core", "Session timed out."), QT_TRANSLATE_NOOP("testcurrency-core", "Set database cache size in megabytes (%d to %d, default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "Set external address:port to get to this masternode (example: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Set key pool size to <n> (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Set maximum block size in bytes (default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "Set minimum block size in bytes (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Set the Maximum reorg depth (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Set the masternode private key"), QT_TRANSLATE_NOOP("testcurrency-core", "Set the number of threads to service RPC calls (default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Show all debugging options (usage: --help -help-debug)"), QT_TRANSLATE_NOOP("testcurrency-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("testcurrency-core", "Signing failed."), QT_TRANSLATE_NOOP("testcurrency-core", "Signing timed out."), QT_TRANSLATE_NOOP("testcurrency-core", "Signing transaction failed"), QT_TRANSLATE_NOOP("testcurrency-core", "Specify configuration file (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"), QT_TRANSLATE_NOOP("testcurrency-core", "Specify data directory"), QT_TRANSLATE_NOOP("testcurrency-core", "Specify masternode configuration file (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Specify pid file (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Specify wallet file (within data directory)"), QT_TRANSLATE_NOOP("testcurrency-core", "Specify your own public address"), QT_TRANSLATE_NOOP("testcurrency-core", "Spend unconfirmed change when sending transactions (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Staking options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Stop running after importing blocks from disk (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Submitted following entries to masternode: %u / %d"), QT_TRANSLATE_NOOP("testcurrency-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"), QT_TRANSLATE_NOOP("testcurrency-core", "Submitted to masternode, waiting in queue %s"), QT_TRANSLATE_NOOP("testcurrency-core", "SwiftX options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Synchronization failed"), QT_TRANSLATE_NOOP("testcurrency-core", "Synchronization finished"), QT_TRANSLATE_NOOP("testcurrency-core", "Synchronization pending..."), QT_TRANSLATE_NOOP("testcurrency-core", "Synchronizing budgets..."), QT_TRANSLATE_NOOP("testcurrency-core", "Synchronizing masternode winners..."), QT_TRANSLATE_NOOP("testcurrency-core", "Synchronizing masternodes..."), QT_TRANSLATE_NOOP("testcurrency-core", "Synchronizing sporks..."), QT_TRANSLATE_NOOP("testcurrency-core", "This help message"), QT_TRANSLATE_NOOP("testcurrency-core", "This is experimental software."), QT_TRANSLATE_NOOP("testcurrency-core", "This is intended for regression testing tools and app development."), QT_TRANSLATE_NOOP("testcurrency-core", "This is not a Masternode."), QT_TRANSLATE_NOOP("testcurrency-core", "Threshold for disconnecting misbehaving peers (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Tor control port password (default: empty)"), QT_TRANSLATE_NOOP("testcurrency-core", "Tor control port to use if onion listening enabled (default: %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Transaction amount too small"), QT_TRANSLATE_NOOP("testcurrency-core", "Transaction amounts must be positive"), QT_TRANSLATE_NOOP("testcurrency-core", "Transaction created successfully."), QT_TRANSLATE_NOOP("testcurrency-core", "Transaction fees are too high."), QT_TRANSLATE_NOOP("testcurrency-core", "Transaction not valid."), QT_TRANSLATE_NOOP("testcurrency-core", "Transaction too large for fee policy"), QT_TRANSLATE_NOOP("testcurrency-core", "Transaction too large"), QT_TRANSLATE_NOOP("testcurrency-core", "Transmitting final transaction."), QT_TRANSLATE_NOOP("testcurrency-core", "Unable to bind to %s on this computer (bind returned error %s)"), QT_TRANSLATE_NOOP("testcurrency-core", "Unable to sign spork message, wrong key?"), QT_TRANSLATE_NOOP("testcurrency-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("testcurrency-core", "Unknown state: id = %u"), QT_TRANSLATE_NOOP("testcurrency-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("testcurrency-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("testcurrency-core", "Use UPnP to map the listening port (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("testcurrency-core", "Use a custom max chain reorganization depth (default: %u)"), QT_TRANSLATE_NOOP("testcurrency-core", "Use the test network"), QT_TRANSLATE_NOOP("testcurrency-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("testcurrency-core", "Value more than Obfuscation pool maximum allows."), QT_TRANSLATE_NOOP("testcurrency-core", "Verifying blocks..."), QT_TRANSLATE_NOOP("testcurrency-core", "Verifying wallet..."), QT_TRANSLATE_NOOP("testcurrency-core", "Wallet %s resides outside data directory %s"), QT_TRANSLATE_NOOP("testcurrency-core", "Wallet is locked."), QT_TRANSLATE_NOOP("testcurrency-core", "Wallet needed to be rewritten: restart Testcurrency Core to complete"), QT_TRANSLATE_NOOP("testcurrency-core", "Wallet options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Wallet window title"), QT_TRANSLATE_NOOP("testcurrency-core", "Warning"), QT_TRANSLATE_NOOP("testcurrency-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("testcurrency-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."), QT_TRANSLATE_NOOP("testcurrency-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."), QT_TRANSLATE_NOOP("testcurrency-core", "Will retry..."), QT_TRANSLATE_NOOP("testcurrency-core", "You need to rebuild the database using -reindex to change -txindex"), QT_TRANSLATE_NOOP("testcurrency-core", "Your entries added successfully."), QT_TRANSLATE_NOOP("testcurrency-core", "Your transaction was accepted into the pool!"), QT_TRANSLATE_NOOP("testcurrency-core", "Zapping all transactions from wallet..."), QT_TRANSLATE_NOOP("testcurrency-core", "ZeroMQ notification options:"), QT_TRANSLATE_NOOP("testcurrency-core", "Zerocoin options:"), QT_TRANSLATE_NOOP("testcurrency-core", "failed to validate zerocoin"), QT_TRANSLATE_NOOP("testcurrency-core", "on startup"), QT_TRANSLATE_NOOP("testcurrency-core", "wallet.dat corrupt, salvage failed"), };
/**************************************************************************** ** ** This file is part of the Ponder library, formerly CAMP. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company. ** Copyright (C) 2015-2018 Nick Trout. ** ** 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 <ponder/classget.hpp> #include <ponder/class.hpp> #include <ponder/enum.hpp> #include <ponder/classbuilder.hpp> #include <ponder/uses/runtime.hpp> #include "test.hpp" #include <string> #include <string.h> // memset namespace ConstructorTest { enum MyEnum { zero = 0, one = 1, two = 2, three = 3, four = 4, five = 5 }; struct MyType { MyType(int x_) : x(x_) {} int x; }; struct MyBase1 { MyBase1() : base1("base1") {} virtual ~MyBase1() {} ponder::String base1; }; struct MyBase2 { MyBase2() : base2("base2") {} virtual ~MyBase2() {} ponder::String base2; }; struct MyClass : MyBase1, MyBase2 { static int instCount; MyClass() : l(0), r(0.), s("0"), e(zero), u(0) {++instCount;} MyClass(long l_) : l(l_), r(1.), s("1"), e(one), u(1) {++instCount;} MyClass(long l_, double r_) : l(l_), r(r_), s("2"), e(two), u(2) {++instCount;} MyClass(long l_, double r_, ponder::String s_) : l(l_), r(r_), s(s_), e(three), u(3) {++instCount;} MyClass(long l_, double r_, ponder::String s_, MyEnum e_) : l(l_), r(r_), s(s_), e(e_), u(4) {++instCount;} MyClass(long l_, double r_, ponder::String s_, MyEnum e_, MyType t_) : l(l_), r(r_), s(s_), e(e_), u(t_) {++instCount;} ~MyClass() {--instCount;} long l; double r; ponder::String s; MyEnum e; MyType u; }; int MyClass::instCount = 0; void declare() { ponder::Enum::declare<MyEnum>("ConstructorTest::MyEnum") .value("zero", zero) .value("one", one) .value("two", two) .value("three", three) .value("four", four) .value("five", five); ponder::Class::declare<MyType>("ConstructorTest::MyType"); ponder::Class::declare<MyBase1>("ConstructorTest::MyBase1"); ponder::Class::declare<MyBase2>("ConstructorTest::MyBase2"); ponder::Class::declare<MyClass>("ConstructorTest::MyClass") .base<MyBase1>() .base<MyBase2>() .constructor() .constructor<long>() .constructor<long, double>() .constructor<long, double, ponder::String>() .constructor<long, double, ponder::String, MyEnum>() // trying types that don't exactly match those declared .constructor<unsigned short, float, ponder::String, MyEnum, int>(); } } PONDER_AUTO_TYPE(ConstructorTest::MyEnum, &ConstructorTest::declare) PONDER_AUTO_TYPE(ConstructorTest::MyType, &ConstructorTest::declare) PONDER_AUTO_TYPE(ConstructorTest::MyBase1, &ConstructorTest::declare) PONDER_AUTO_TYPE(ConstructorTest::MyBase2, &ConstructorTest::declare) PONDER_AUTO_TYPE(ConstructorTest::MyClass, &ConstructorTest::declare) using namespace ConstructorTest; //----------------------------------------------------------------------------- // Tests for ponder::Class::construct //----------------------------------------------------------------------------- TEST_CASE("Object factories can be used to create class instances") // and allocate dynamically { const ponder::Class& metaclass = ponder::classByType<MyClass>(); const std::size_t sz = metaclass.sizeOf(); REQUIRE(sz > 0); REQUIRE(sz == sizeof(MyClass)); SECTION("using constuct/destroy") { REQUIRE(MyClass::instCount == 0); { ponder::UserObject object; REQUIRE(MyClass::instCount == 0); IS_TRUE( object == ponder::UserObject::nothing ); ponder::runtime::ObjectFactory fact(metaclass); object = fact.construct(ponder::Args(777, 99.05f, "wow")); REQUIRE(MyClass::instCount == 1); IS_TRUE( object != ponder::UserObject::nothing ); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance->l == 777); REQUIRE(instance->r == Approx(99.05).epsilon(1E-5)); REQUIRE(instance->s == "wow"); REQUIRE(instance->e == three); REQUIRE(instance->u.x == 3); fact.destroy(object); } REQUIRE(MyClass::instCount == 0); } SECTION("using placement new") { REQUIRE(MyClass::instCount == 0); { char buff[sizeof(MyClass) + 20]; const char c_guard{ (char)0xcd }; memset(buff, c_guard, sizeof(buff)); char *p = buff + 4; REQUIRE(buff[0] == c_guard); REQUIRE(*p == c_guard); REQUIRE(p[sz] == c_guard); ponder::runtime::ObjectFactory fact(metaclass); ponder::UserObject object = fact.construct(ponder::Args(), p); // placement new IS_TRUE( object != ponder::UserObject::nothing ); REQUIRE(MyClass::instCount == 1); REQUIRE(buff[0] == c_guard); REQUIRE(*p != c_guard); REQUIRE(p[sz] == c_guard); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance == reinterpret_cast<MyClass*>(p)); REQUIRE(instance->l == 0); REQUIRE(instance->r == Approx(0.).epsilon(1E-5)); REQUIRE(instance->s == "0"); REQUIRE(instance->e == zero); REQUIRE(instance->u.x == 0); fact.destruct(object); // not destroy() } REQUIRE(MyClass::instCount == 0); } SECTION("using create/destroy") { REQUIRE(MyClass::instCount == 0); { ponder::UserObject object; IS_TRUE( object == ponder::UserObject::nothing ); ponder::runtime::ObjectFactory fact(metaclass); object = fact.create(777, 99.05f, "wow"); IS_TRUE( object != ponder::UserObject::nothing ); REQUIRE(MyClass::instCount == 1); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance->l == 777); REQUIRE(instance->r == Approx(99.05).epsilon(1E-5)); REQUIRE(instance->s == "wow"); REQUIRE(instance->e == three); REQUIRE(instance->u.x == 3); fact.destroy(object); } REQUIRE(MyClass::instCount == 0); } SECTION("using create & auto pointer") { REQUIRE(MyClass::instCount == 0); { auto object = ponder::runtime::createUnique(metaclass, 777, 99.05f, "wow"); IS_TRUE( *object.get() != ponder::UserObject::nothing ); MyClass* instance = object.get()->get<MyClass*>(); REQUIRE(instance->l == 777); REQUIRE(instance->r == Approx(99.05).epsilon(1E-5)); REQUIRE(instance->s == "wow"); REQUIRE(instance->e == three); REQUIRE(instance->u.x == 3); } REQUIRE(MyClass::instCount == 0); } } //----------------------------------------------------------------------------- // Tests for ponder::Class::construct //----------------------------------------------------------------------------- TEST_CASE("Classes can have constructors") // and allocate dynamically { const ponder::Class* metaclass = &ponder::classByType<MyClass>(); REQUIRE(metaclass != nullptr); SECTION("with no parameters") { ponder::UserObject object; IS_TRUE( object == ponder::UserObject::nothing ); ponder::runtime::ObjectFactory fact(*metaclass); object = fact.construct(); IS_TRUE( object != ponder::UserObject::nothing ); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance->l == 0); REQUIRE(instance->r == Approx(0.).epsilon(1E-5)); REQUIRE(instance->s == "0"); REQUIRE(instance->e == zero); REQUIRE(instance->u.x == 0); fact.destroy(object); } SECTION("with one parameter") { ponder::UserObject object; IS_TRUE( object == ponder::UserObject::nothing ); ponder::runtime::ObjectFactory fact(*metaclass); object = fact.construct(ponder::Args(1)); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance->l == 1); REQUIRE(instance->r == Approx(1.).epsilon(1E-5)); REQUIRE(instance->s == "1"); REQUIRE(instance->e == one); REQUIRE(instance->u.x == 1); fact.destroy(object); } SECTION("with two parameters") { ponder::UserObject object; IS_TRUE( object == ponder::UserObject::nothing ); ponder::runtime::ObjectFactory fact(*metaclass); object = fact.construct(ponder::Args(2, 2.)); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance->l == 2); REQUIRE(instance->r == Approx(2.).epsilon(1E-5)); REQUIRE(instance->s == "2"); REQUIRE(instance->e == two); REQUIRE(instance->u.x == 2); fact.destroy(object); } SECTION("with three parameters") { ponder::UserObject object; IS_TRUE( object == ponder::UserObject::nothing ); ponder::runtime::ObjectFactory fact(*metaclass); object = fact.construct(ponder::Args(3, 3., "3")); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance->l == 3); REQUIRE(instance->r == Approx(3.).epsilon(1E-5)); REQUIRE(instance->s == "3"); REQUIRE(instance->e == three); REQUIRE(instance->u.x == 3); fact.destroy(object); } SECTION("with four parameters") { ponder::UserObject object; IS_TRUE( object == ponder::UserObject::nothing ); ponder::runtime::ObjectFactory fact(*metaclass); object = fact.construct(ponder::Args(4, 4., "4", four)); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance->l == 4); REQUIRE(instance->r == Approx(4.).epsilon(1E-5)); REQUIRE(instance->s == "4"); REQUIRE(instance->e == four); REQUIRE(instance->u.x == 4); fact.destroy(object); } SECTION("with five parameters") { ponder::UserObject object; IS_TRUE( object == ponder::UserObject::nothing ); ponder::runtime::ObjectFactory fact(*metaclass); object = fact.construct(ponder::Args(5, 5., "5", five, 5)); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance->l == 5); REQUIRE(instance->r == Approx(5.).epsilon(1E-5)); REQUIRE(instance->s == "5"); REQUIRE(instance->e == five); REQUIRE(instance->u.x == 5); fact.destroy(object); } SECTION("with invalid parameters") { ponder::runtime::ObjectFactory fact(*metaclass); IS_TRUE( fact.construct(ponder::Args("hello")) == ponder::UserObject::nothing ); IS_TRUE( fact.construct(ponder::Args(MyType(10))) == ponder::UserObject::nothing ); IS_TRUE( fact.construct(ponder::Args(two, MyType(10))) == ponder::UserObject::nothing ); IS_TRUE( fact.construct(ponder::Args(5., "hello")) == ponder::UserObject::nothing ); } } //TEST_CASE("Object factories can be used to create class instances") // and allocate dynamically //{ // const ponder::Class &metaclass = ponder::classByType<MyClass>(); // // SECTION("with no parameters") // { //// ponder::UserObject object; // auto object = ponder::runtime::createUnique(const ponder::Class &cls, A args...) // // IS_TRUE( object == ponder::UserObject::nothing ); // // ponder::runtime::ObjectFactory fact(metaclass); // object = fact.create(); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 0); // REQUIRE(instance->r == Approx(0.).epsilon(1E-5)); // REQUIRE(instance->s == "0"); // REQUIRE(instance->e == zero); // REQUIRE(instance->u.x == 0); // // fact.destroy(object); // } // // SECTION("with one parameter") // { // ponder::runtime::ObjectFactory fact(metaclass); // ponder::UserObject object = fact.construct(ponder::Args(1)); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 1); // REQUIRE(instance->r == Approx(1.).epsilon(1E-5)); // REQUIRE(instance->s == "1"); // REQUIRE(instance->e == one); // REQUIRE(instance->u.x == 1); // // fact.destroy(object); // } // SECTION("with two parameters") // { // ponder::UserObject object = metaclass->construct(ponder::Args(2, 2.)); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 2); // REQUIRE(instance->r == Approx(2.).epsilon(1E-5)); // REQUIRE(instance->s == "2"); // REQUIRE(instance->e == two); // REQUIRE(instance->u.x == 2); // // metaclass->destroy(object); // } // // // SECTION("with three parameters") // { // ponder::UserObject object = metaclass->construct(ponder::Args(3, 3., "3")); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 3); // REQUIRE(instance->r == Approx(3.).epsilon(1E-5)); // REQUIRE(instance->s == "3"); // REQUIRE(instance->e == three); // REQUIRE(instance->u.x == 3); // // metaclass->destroy(object); // } // // SECTION("with four parameters") // { // ponder::UserObject object = metaclass->construct(ponder::Args(4, 4., "4", four)); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 4); // REQUIRE(instance->r == Approx(4.).epsilon(1E-5)); // REQUIRE(instance->s == "4"); // REQUIRE(instance->e == four); // REQUIRE(instance->u.x == 4); // // metaclass->destroy(object); // } // // SECTION("with five parameters") // { // ponder::UserObject object = metaclass->construct(ponder::Args(5, 5., "5", five, 5)); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 5); // REQUIRE(instance->r == Approx(5.).epsilon(1E-5)); // REQUIRE(instance->s == "5"); // REQUIRE(instance->e == five); // REQUIRE(instance->u.x == 5); // // metaclass->destroy(object); // } //} TEST_CASE("Object factory constructors can use placement new") { const ponder::Class &metaclass = ponder::classByType<MyClass>(); const std::size_t sz = metaclass.sizeOf(); REQUIRE(sz > 0); REQUIRE(sz == sizeof(MyClass)); SECTION("with no parameters") { char buff[sizeof(MyClass) + 20]; const char c_guard{ (char)0xcd }; memset(buff, c_guard, sizeof(buff)); char *p = buff + 4; REQUIRE(buff[0] == c_guard); REQUIRE(*p == c_guard); REQUIRE(p[sz] == c_guard); ponder::runtime::ObjectFactory fact(metaclass); ponder::UserObject object = fact.construct(ponder::Args(), p); // placement new IS_TRUE( object != ponder::UserObject::nothing ); REQUIRE(buff[0] == c_guard); REQUIRE(*p != c_guard); REQUIRE(p[sz] == c_guard); MyClass* instance = object.get<MyClass*>(); REQUIRE(instance == reinterpret_cast<MyClass*>(p)); REQUIRE(instance->l == 0); REQUIRE(instance->r == Approx(0.).epsilon(1E-5)); REQUIRE(instance->s == "0"); REQUIRE(instance->e == zero); REQUIRE(instance->u.x == 0); fact.destruct(object); // not destroy() } } //----------------------------------------------------------------------------- // Tests for ponder::Class::create //----------------------------------------------------------------------------- //TEST_CASE("Classes can create object") // no arg list //{ // const ponder::Class* metaclass = &ponder::classByType<MyClass>(); // // REQUIRE(metaclass != nullptr); // // SECTION("with no parameters") // { // ponder::UserObject object; // // IS_TRUE( object == ponder::UserObject::nothing ); // // object = metaclass->create(); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass *instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 0); // REQUIRE(instance->r == Approx(0.).epsilon(1E-5)); // REQUIRE(instance->s == "0"); // REQUIRE(instance->e == zero); // REQUIRE(instance->u.x == 0); // // metaclass->destroy(object); // } // // SECTION("with one parameter") // { // ponder::UserObject object = metaclass->create(1); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 1); // REQUIRE(instance->r == Approx(1.).epsilon(1E-5)); // REQUIRE(instance->s == "1"); // REQUIRE(instance->e == one); // REQUIRE(instance->u.x == 1); // // metaclass->destroy(object); // } // // SECTION("with two parameters") // { // ponder::UserObject object = metaclass->create(2, 2.); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 2); // REQUIRE(instance->r == Approx(2.).epsilon(1E-5)); // REQUIRE(instance->s == "2"); // REQUIRE(instance->e == two); // REQUIRE(instance->u.x == 2); // // metaclass->destroy(object); // } // // // SECTION("with three parameters") // { // ponder::UserObject object = metaclass->create(3, 3., "3"); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 3); // REQUIRE(instance->r == Approx(3.).epsilon(1E-5)); // REQUIRE(instance->s == "3"); // REQUIRE(instance->e == three); // REQUIRE(instance->u.x == 3); // // metaclass->destroy(object); // } // // SECTION("with four parameters") // { // ponder::UserObject object = metaclass->create(4, 4., "4", four); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 4); // REQUIRE(instance->r == Approx(4.).epsilon(1E-5)); // REQUIRE(instance->s == "4"); // REQUIRE(instance->e == four); // REQUIRE(instance->u.x == 4); // // metaclass->destroy(object); // } // // SECTION("with five parameters") // { // ponder::UserObject object = metaclass->create(5, 5., "5", five, 5); // // IS_TRUE( object != ponder::UserObject::nothing ); // // MyClass* instance = object.get<MyClass*>(); // // REQUIRE(instance->l == 5); // REQUIRE(instance->r == Approx(5.).epsilon(1E-5)); // REQUIRE(instance->s == "5"); // REQUIRE(instance->e == five); // REQUIRE(instance->u.x == 5); // // metaclass->destroy(object); // } // // SECTION("with invalid parameters") // { // IS_TRUE( metaclass->create("hello") == ponder::UserObject::nothing ); // IS_TRUE( metaclass->create(MyType(10)) == ponder::UserObject::nothing ); // IS_TRUE( metaclass->create(two, MyType(10)) == ponder::UserObject::nothing ); // IS_TRUE( metaclass->create(5., "hello") == ponder::UserObject::nothing ); // } //}
#include <stan/math/mix/scal.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/scal/fun/util.hpp> #include <test/unit/math/mix/scal/fun/nan_util.hpp> TEST(AgradFwdRisingFactorial, FvarVar_1stDeriv) { using stan::math::digamma; using stan::math::fvar; using stan::math::rising_factorial; using stan::math::var; fvar<var> a(5.0, 1.0); fvar<var> c = rising_factorial(a, 3); EXPECT_FLOAT_EQ(rising_factorial(5, 3), c.val_.val()); EXPECT_FLOAT_EQ(rising_factorial(5, 3) * (digamma(5 + 3) - digamma(5)), c.d_.val()); AVEC y = createAVEC(a.val_, 3); VEC g; c.val_.grad(y, g); EXPECT_FLOAT_EQ(rising_factorial(5, 3) * (digamma(5 + 3) - digamma(5)), g[0]); EXPECT_FLOAT_EQ(0, g[1]); } TEST(AgradFwdRisingFactorial, FvarVar_2ndDeriv_x) { using stan::math::digamma; using stan::math::fvar; using stan::math::rising_factorial; using stan::math::trigamma; using stan::math::var; using std::pow; fvar<var> a(5.0, 1.0); fvar<var> c = rising_factorial(a, 3); AVEC y = createAVEC(a.val_, 3); VEC g; c.d_.grad(y, g); ASSERT_NEAR(rising_factorial(5, 3) * (pow((digamma(5 + 3) - digamma(5)), 2) + trigamma(5 + 3) - trigamma(5)), g[0], 0.1); } TEST(AgradFwdRisingFactorial, FvarVar_2ndDeriv_y) { using stan::math::fvar; using stan::math::rising_factorial; using stan::math::var; /** * Second derivative w.r.t. n should return 0, * since n is an integer. */ fvar<var> a(5.0, 0.0); fvar<var> c = rising_factorial(a, 3); AVEC y = createAVEC(a.val_, 3); VEC g; c.d_.grad(y, g); ASSERT_NEAR(0, g[1], 0.1); } TEST(AgradFwdRisingFactorial, FvarFvarVar_1stDeriv) { using stan::math::digamma; using stan::math::fvar; using stan::math::rising_factorial; using stan::math::var; fvar<fvar<var> > x; x.val_.val_ = 5.0; x.val_.d_ = 1.0; fvar<fvar<var> > a = rising_factorial(x, 3); EXPECT_FLOAT_EQ(rising_factorial(5, 3), a.val_.val_.val()); EXPECT_FLOAT_EQ(107.0, a.val_.d_.val()); EXPECT_FLOAT_EQ(0, a.d_.val_.val()); ASSERT_NEAR(0, a.d_.d_.val(), .01); AVEC p = createAVEC(x.val_.val_, 3); VEC g; a.val_.val_.grad(p, g); EXPECT_FLOAT_EQ(rising_factorial(5, 3) * (digamma(5 + 3) - digamma(5)), g[0]); EXPECT_FLOAT_EQ(0, g[1]); } TEST(AgradFwdRisingFactorial, FvarFvarVar_2ndDeriv_x) { using stan::math::digamma; using stan::math::fvar; using stan::math::rising_factorial; using stan::math::trigamma; using stan::math::var; using std::pow; fvar<fvar<var> > x; x.val_.val_ = 5.0; x.val_.d_ = 1.0; fvar<fvar<var> > a = rising_factorial(x, 3); AVEC p = createAVEC(x.val_.val_, 3); VEC g; a.val_.d_.grad(p, g); ASSERT_NEAR(rising_factorial(5, 3) * (pow((digamma(5 + 3) - digamma(5)), 2) + trigamma(5 + 3) - trigamma(5)), g[0], 0.01); ASSERT_NEAR(0, g[1], 0.01); } TEST(AgradFwdRisingFactorial, FvarFvarVar_2ndDeriv_y) { using stan::math::fvar; using stan::math::rising_factorial; using stan::math::var; fvar<fvar<var> > x; x.val_.val_ = 5.0; x.val_.d_ = 1.0; fvar<fvar<var> > a = rising_factorial(x, 3); AVEC p = createAVEC(x.val_.val_, 3); VEC g; a.d_.val_.grad(p, g); ASSERT_NEAR(0, g[0], 0.01); ASSERT_NEAR(0, g[1], 0.01); } TEST(AgradFwdRisingFactorial, FvarFvarVar_3rdDeriv) { using stan::math::fvar; using stan::math::rising_factorial; using stan::math::var; fvar<fvar<var> > x; x.val_.val_ = 5.0; x.val_.d_ = 1.0; fvar<fvar<var> > a = rising_factorial(x, 3); AVEC p = createAVEC(x.val_.val_, 3); VEC g; a.d_.d_.grad(p, g); ASSERT_NEAR(0, g[0], 0.03); ASSERT_NEAR(0, g[1], 0.03); } struct rising_factorial_fun { template <typename T> inline typename boost::math::tools::promote_args<T>::type operator()( const T arg1, int arg2) const { return rising_factorial(arg1, arg2); } };
#ifndef STAN_MATH_OPENCL_PRIM_FUN_CROSSPROD_HPP #define STAN_MATH_OPENCL_PRIM_FUN_CROSSPROD_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/matrix_cl.hpp> #include <stan/math/opencl/prim/multiply.hpp> #include <stan/math/opencl/kernel_generator.hpp> namespace stan { namespace math { /** * Returns the result of pre-multiplying a matrix by its * own transpose. * * @tparam T type of elements in A * @param A input matrix * @return transpose(A) * A */ template <typename T_A, typename = require_all_kernel_expressions_and_none_scalar_t<T_A>> inline matrix_cl<typename std::decay_t<T_A>::Scalar> crossprod(T_A&& A) { const matrix_cl<typename std::decay_t<T_A>::Scalar>& A_eval = transpose(std::forward<T_A>(A)); return multiply_transpose(A_eval); } } // namespace math } // namespace stan #endif #endif
/******************************************************************************/ /* Mednafen - Multi-system Emulator */ /******************************************************************************/ /* nnx.h: ** Copyright (C) 2005-2016 Mednafen Team ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the GNU General Public License ** as published by the Free Software Foundation; either version 2 ** of the License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software Foundation, Inc., ** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Nearest-neighbor simple scalers */ // FIXME: non-32bpp scaling not working yet. #include "main.h" #include "nnx.h" template<typename T> static void t_nnx(int factor, const MDFN_Surface *src, const MDFN_Rect *src_rect, MDFN_Surface *dest, const MDFN_Rect *dest_rect) { const T *source_pixies = src->pix<T>() + src_rect->y * src->pitchinpix; source_pixies += src_rect->x; int source_pitch = src->pitchinpix; int source_pitch_diff = source_pitch - src_rect->w; T *dest_pixies = dest->pix<T>() + dest_rect->y * dest->pitchinpix; dest_pixies += dest_rect->x; int dest_pitch = dest->pitchinpix; int dest_pitch_diff = dest_pitch - dest_rect->w + dest_pitch * (factor - 1); int max_x = src_rect->w; switch(factor) { case 2: for(int y = src_rect->h; y; y--) { for(int x = max_x; x; x--) { dest_pixies[0] = dest_pixies[1] = dest_pixies[dest_pitch] = dest_pixies[dest_pitch + 1] = *source_pixies; source_pixies++; dest_pixies += 2; } dest_pixies += dest_pitch_diff; source_pixies += source_pitch_diff; } break; case 3: for(int y = src_rect->h; y; y--) { for(int x = max_x; x; x--) { dest_pixies[0] = dest_pixies[1] = dest_pixies[2] = dest_pixies[dest_pitch] = dest_pixies[dest_pitch + 1] = dest_pixies[dest_pitch + 2] = dest_pixies[dest_pitch << 1] = dest_pixies[(dest_pitch << 1) + 1] = dest_pixies[(dest_pitch << 1) + 2] = *source_pixies; source_pixies++; dest_pixies += 3; } dest_pixies += dest_pitch_diff; source_pixies += source_pitch_diff; } break; case 4: for(int y = src_rect->h; y; y--) { for(int x = max_x; x; x--) { dest_pixies[0] = dest_pixies[1] = dest_pixies[2] = dest_pixies[3] = dest_pixies[dest_pitch] = dest_pixies[dest_pitch + 1] = dest_pixies[dest_pitch + 2] = dest_pixies[dest_pitch + 3] = dest_pixies[dest_pitch << 1] = dest_pixies[(dest_pitch << 1) + 1] = dest_pixies[(dest_pitch << 1) + 2] = dest_pixies[(dest_pitch << 1) + 3] = dest_pixies[(dest_pitch << 1) + dest_pitch] = dest_pixies[(dest_pitch << 1) + dest_pitch + 1] = dest_pixies[(dest_pitch << 1) + dest_pitch + 2] = dest_pixies[(dest_pitch << 1) + dest_pitch + 3] = *source_pixies; source_pixies++; dest_pixies += 4; } dest_pixies += dest_pitch_diff; source_pixies += source_pitch_diff; } break; case 5: for(int y = src_rect->h; y; y--) { for(int x = max_x; x; x--) { // Line 0 dest_pixies[0] = dest_pixies[1] = dest_pixies[2] = dest_pixies[3] = dest_pixies[4] = // Line 1 dest_pixies[dest_pitch] = dest_pixies[dest_pitch + 1] = dest_pixies[dest_pitch + 2] = dest_pixies[dest_pitch + 3] = dest_pixies[dest_pitch + 4] = // Line 2 dest_pixies[dest_pitch << 1] = dest_pixies[(dest_pitch << 1) + 1] = dest_pixies[(dest_pitch << 1) + 2] = dest_pixies[(dest_pitch << 1) + 3] = dest_pixies[(dest_pitch << 1) + 4] = // Line 3 dest_pixies[(dest_pitch << 1) + dest_pitch] = dest_pixies[(dest_pitch << 1) + dest_pitch + 1] = dest_pixies[(dest_pitch << 1) + dest_pitch + 2] = dest_pixies[(dest_pitch << 1) + dest_pitch + 3] = dest_pixies[(dest_pitch << 1) + dest_pitch + 4] = *source_pixies; // Line 4 dest_pixies[(dest_pitch << 2)] = dest_pixies[(dest_pitch << 2) + 1] = dest_pixies[(dest_pitch << 2) + 2] = dest_pixies[(dest_pitch << 2) + 3] = dest_pixies[(dest_pitch << 2) + 4] = *source_pixies; source_pixies++; dest_pixies += 5; } dest_pixies += dest_pitch_diff; source_pixies += source_pitch_diff; } break; } } template<typename T> static void t_nnyx(int factor, const MDFN_Surface *src, const MDFN_Rect *src_rect, MDFN_Surface *dest, const MDFN_Rect *dest_rect) { const T *source_pixies = src->pix<T>() + src_rect->y * src->pitchinpix; source_pixies += src_rect->x; int source_pitch = src->pitchinpix; int source_pitch_diff = source_pitch - src_rect->w; T *dest_pixies = dest->pix<T>() + dest_rect->y * dest->pitchinpix; dest_pixies += dest_rect->x; int dest_pitch = dest->pitchinpix; int dest_pitch_diff = dest_pitch - dest_rect->w + dest_pitch * (factor - 1); int max_x = src_rect->w; switch(factor) { case 2: for(int y = src_rect->h; y; y--) { for(int x = max_x; x; x--) { dest_pixies[0] = dest_pixies[dest_pitch] = *source_pixies; source_pixies++; dest_pixies ++; } dest_pixies += dest_pitch_diff; source_pixies += source_pitch_diff; } break; case 3: for(int y = src_rect->h; y; y--) { for(int x = max_x; x; x--) { dest_pixies[0] = dest_pixies[dest_pitch] = dest_pixies[dest_pitch << 1] = *source_pixies; source_pixies++; dest_pixies ++; } dest_pixies += dest_pitch_diff; source_pixies += source_pitch_diff; } break; case 4: for(int y = src_rect->h; y; y--) { for(int x = max_x; x; x--) { dest_pixies[0] = dest_pixies[dest_pitch] = dest_pixies[dest_pitch << 1] = dest_pixies[(dest_pitch << 1) + dest_pitch] = *source_pixies; source_pixies++; dest_pixies ++; } dest_pixies += dest_pitch_diff; source_pixies += source_pitch_diff; } break; } } void nnx(int factor, const MDFN_Surface* src, const MDFN_Rect& src_rect, MDFN_Surface* dest, const MDFN_Rect& dest_rect) { switch(src->format.opp) { /* case 1: t_nnx<uint8>(factor, src, src_rect, dest, dest_rect); break; */ case 2: t_nnx<uint16>(factor, src, &src_rect, dest, &dest_rect); break; case 4: t_nnx<uint32>(factor, src, &src_rect, dest, &dest_rect); break; } } void nnyx(int factor, const MDFN_Surface* src, const MDFN_Rect& src_rect, MDFN_Surface* dest, const MDFN_Rect& dest_rect) { switch(src->format.opp) { /* case 1: t_nnyx<uint8>(factor, src, src_rect, dest, dest_rect); break; */ case 2: t_nnyx<uint16>(factor, src, &src_rect, dest, &dest_rect); break; case 4: t_nnyx<uint32>(factor, src, &src_rect, dest, &dest_rect); break; } }
//$Id: Publisher.cpp 9876 2011-09-16 20:58:50Z lindajun $ //------------------------------------------------------------------------------ // Publisher //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: LaMont Ruley // Created: 2003/09/21 // /** * Implementation code for the Publisher class. */ //------------------------------------------------------------------------------ #include "Publisher.hpp" #include "PublisherException.hpp" #include "MessageInterface.hpp" #include "Moderator.hpp" #include <string> #include <algorithm> // for find() //#define DBGLVL_PUBLISHER_SUBSCRIBE 1 //#define DBGLVL_PUBLISHER_REGISTER 1 //#define DBGLVL_PUBLISHER_PUBLISH 1 //#define DBGLVL_PUBLISHER_CLEAR 1 //#define DEBUG_PUBLISHER_RUN_STATE //#define DEBUG_PUBLISHER_BUFFERS //#ifndef DEBUG_MEMORY //#define DEBUG_MEMORY //#endif #ifdef DEBUG_MEMORY #include "MemoryTracker.hpp" #endif // Initialize the singleton Publisher* Publisher::instance = NULL; //------------------------------------------------------------------------------ // Publisher* Instance(void) //------------------------------------------------------------------------------ Publisher* Publisher::Instance() { if (instance == NULL) instance = new Publisher; return instance; } //------------------------------------------------------------------------------ // Publisher(void) //------------------------------------------------------------------------------ Publisher::Publisher() : providerId (-1), currProviderId (-1), runState (Gmat::IDLE), maneuvering (false), internalCoordSystem (NULL), dataCoordSystem (NULL), dataMJ2000EqOrigin (NULL) { } //------------------------------------------------------------------------------ // ~Publisher(void) //------------------------------------------------------------------------------ Publisher::~Publisher() { subscriberList.clear(); coordSysMap.clear(); // Clear registered pub data std::map<GmatBase*, std::vector<DataType>* >::iterator iter = providerMap.begin(); while (iter != providerMap.end()) { std::vector<DataType>* dataList = iter->second; if (dataList != NULL) { #ifdef DEBUG_MEMORY MemoryTracker::Instance()->Remove (dataList, "dataList", "Publisher::UnregisterPublishedData()", "deleting dataList"); #endif delete dataList; } iter++; } } //------------------------------------------------------------------------------ // bool Subscribe(Subscriber *s) //------------------------------------------------------------------------------ bool Publisher::Subscribe(Subscriber *s) { #if DBGLVL_PUBLISHER_SUBSCRIBE MessageInterface::ShowMessage ("Publisher::Subscribe() sub = <%p><%s>'%s'\n", s, s->GetTypeName().c_str(), s->GetName().c_str()); #endif if (!s) return false; if (s->GetType() != Gmat::SUBSCRIBER) { MessageInterface::ShowMessage ("**** ERROR **** Publisher::Subscribe() Cannot add non-Subscriber object " "'%s'. It is type of '%s'\n", s->GetName().c_str(), s->GetTypeName().c_str()); return false; } // Add if subscriber is already not in the list (LOJ: 2009.04.08) if (find(subscriberList.begin(), subscriberList.end(), s) == subscriberList.end()) { subscriberList.push_back(s); s->SetProviderId(currProviderId); #if DBGLVL_PUBLISHER_SUBSCRIBE MessageInterface::ShowMessage (" Adding <%p>'%s' to subscriber list\n", s, s->GetName().c_str()); ShowSubscribers(); #endif } else { #if DBGLVL_PUBLISHER_SUBSCRIBE MessageInterface::ShowMessage (" <%p>'%s' was already added\n", s, s->GetName().c_str()); #endif } return true; } //------------------------------------------------------------------------------ // bool Unsubscribe(Subscriber *s) //------------------------------------------------------------------------------ bool Publisher::Unsubscribe(Subscriber *s) { if (!s) return false; if (subscriberList.empty()) { #if DBGLVL_PUBLISHER_SUBSCRIBE MessageInterface::ShowMessage ("Publisher::Unsubscribe() sub = <%p>'%s' returning false, " "the subscriber list is empty\n", s, s->GetName().c_str()); #endif return false; } #if DBGLVL_PUBLISHER_SUBSCRIBE MessageInterface::ShowMessage ("Publisher::Unsubscribe() sub = <%p>'%s'\n", s, s->GetName().c_str()); #endif #if DBGLVL_PUBLISHER_SUBSCRIBE MessageInterface::ShowMessage(" About to remove <%p> from the list\n", s); ShowSubscribers(); #endif subscriberList.remove(s); #if DBGLVL_PUBLISHER_SUBSCRIBE MessageInterface::ShowMessage("Publisher::Unsubscribe() returning true\n"); #endif return true; } //------------------------------------------------------------------------------ // bool UnsubscribeAll() //------------------------------------------------------------------------------ bool Publisher::UnsubscribeAll() { #if DBGLVL_PUBLISHER_SUBSCRIBE MessageInterface::ShowMessage ("Publisher::UnsubscribeAll() entered. Clearing %d subscribers\n", subscriberList.size()); #endif subscriberList.clear(); ClearPublishedData(); // delete locally created coordinate systems std::map<std::string, CoordinateSystem*>::iterator iter; for (iter = coordSysMap.begin(); iter != coordSysMap.end(); ++iter) { if ((iter->first).find("Local-") != std::string::npos) { #if DBGLVL_PUBLISHER MessageInterface::ShowMessage ("Publisher::UnsubscribeAll() deleting %s\n", iter->first.c_str()); #endif delete iter->second; } } coordSysMap.clear(); return true; } //------------------------------------------------------------------------------ // bool Publish(GmatBase *provider, Real *data, Integer count = false) //------------------------------------------------------------------------------ bool Publisher::Publish(GmatBase *provider, Integer id, Real *data, Integer count) { #if DBGLVL_PUBLISHER_PUBLISH MessageInterface::ShowMessage ("Publisher::Publish(Real) entered, provider=<%p><%s>, id=%d, " "currProviderId=%d, count=%d\n", provider, provider->GetTypeName().c_str(), id, currProviderId, count); MessageInterface::ShowMessage(" providerMap.size()=%d\n", providerMap.size()); #endif // No subscribers if (subscriberList.empty()) { #if DBGLVL_PUBLISHER_PUBLISH MessageInterface::ShowMessage ("*** WARNING *** Publisher::Publish() There are no subscribers, " "so just returning false\n"); #endif return false; } // Check for no providers std::map<GmatBase*, std::vector<DataType>* >::iterator iter = providerMap.find(provider); if (iter == providerMap.end()) { #if DBGLVL_PUBLISHER_PUBLISH MessageInterface::ShowMessage ("*** WARNING *** Publisher::Publish() There are no registered providers, " "so just returning false\n"); #endif return false; } if (id != currProviderId) { currProviderId = id; UpdateProviderId(id); } // Get data labels std::vector<DataType>* dataList = iter->second; #if DBGLVL_PUBLISHER_PUBLISH > 1 MessageInterface::ShowMessage(" dataList->size()=%d\n", dataList->size()); #endif // Convert the data into a string for distribution Integer length = count*25 + 1; char *stream = new char[length]; #ifdef DEBUG_PUBLISHER_BUFFERS MessageInterface::ShowMessage("Allocated %d chars at %p\n", length, stream); #endif stream[0] = '\0'; // Init to empty string for (Integer i = 0; i < count; ++i) { #ifdef DEBUG_PUBLISHER_BUFFERS MessageInterface::ShowMessage(" %d: %12lf\n", i, data[i]); #endif sprintf(stream, "%s%16le", stream, data[i]); if (i < count - 1) strcat(stream, ", "); else strcat(stream, "\n"); #ifdef DEBUG_PUBLISHER_BUFFERS MessageInterface::ShowMessage(" used %d\n", strlen(stream)); #endif } #ifdef DEBUG_PUBLISHER_BUFFERS MessageInterface::ShowMessage(" Data: %s\n", stream); #endif #if DBGLVL_PUBLISHER_PUBLISH MessageInterface::ShowMessage ("Publisher::Publish() calling ReceiveData() number of subsbribers = %d\n", subscriberList.size()); #endif std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { #ifdef DEBUG_PUBLISHER_BUFFERS MessageInterface::ShowMessage(" Publishing to %s\n", (*current)->GetName().c_str()); #endif #if DBGLVL_PUBLISHER_PUBLISH > 1 MessageInterface::ShowMessage ("Publisher::Publish() sub = <%p><%p>'%s'\n", (*current), (*current)->GetTypeName().c_str(), (*current)->GetName().c_str()); #endif // Set labels (*current)->SetDataLabels((*dataList)[id].labels); // Set provider (*current)->SetProvider(provider); if (!(*current)->ReceiveData(stream)) return false; if (!(*current)->ReceiveData(data, count)) return false; current++; } #ifdef DEBUG_PUBLISHER_BUFFERS MessageInterface::ShowMessage(" Cleaning up\n"); #endif delete [] stream; #if DBGLVL_PUBLISHER_PUBLISH MessageInterface::ShowMessage("Publisher::Publish() returning true\n"); #endif return true; } //------------------------------------------------------------------------------ // bool Publish(char *data, Integer count = 0) //------------------------------------------------------------------------------ bool Publisher::Publish(Integer id, char *data, Integer count) { Integer i; // No subscribers if (subscriberList.empty()) return false; #if DBGLVL_PUBLISHER_PUBLISH > 1 MessageInterface::ShowMessage("Publisher::Publish(char) id = %d\n", id); #endif if ((id < 0) || (id > providerId)) { throw PublisherException ("Character data provider has not registered with the Publisher."); } if (id != currProviderId) { currProviderId = id; UpdateProviderId(id); } // Convert the data into a string for distribution Integer length; if (count) length = count + 1; else length = strlen(data) + 1; char *stream = new char[length]; if (count) { for (i = 0; i < count; ++i) stream[i] = data[i]; stream[i] = '\0'; } else { strcpy(stream, data); } strcat(stream, "\n"); std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { if (!(*current)->ReceiveData(stream)) return false; current++; } delete [] stream; return true; } //------------------------------------------------------------------------------ // bool Publish(Integer id, Integer *data, Integer count = false) //------------------------------------------------------------------------------ bool Publisher::Publish(Integer id, Integer *data, Integer count) { // No subscribers if (subscriberList.empty()) return false; #if DBGLVL_PUBLISHER_PUBLISH > 1 MessageInterface::ShowMessage("Publisher::Publish(Integer) id = %d\n", id); #endif if ((id < 0) || (id > providerId)) throw PublisherException ("Integer data provider has not registered with the Publisher."); if (id != currProviderId) { currProviderId = id; UpdateProviderId(id); } // Convert the data into a string for distribution char *stream = new char[count*25 + 1]; stream[0] = '\0'; for(Integer i = 0; i < count; ++i) { sprintf(stream, "%s%d", stream, data[i]); if (i < count - 1) strcat(stream, ", "); else strcat(stream, "\n"); } std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { if (!(*current)->ReceiveData(stream)) return false; current++; } delete [] stream; return true; } //------------------------------------------------------------------------------ // bool FlushBuffers(bool endOfDataBlock = true) //------------------------------------------------------------------------------ /** * Indicates end of data stream. */ //------------------------------------------------------------------------------ bool Publisher::FlushBuffers(bool endOfDataBlock) { // No subscribers if (subscriberList.empty()) return false; std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { if (!(*current)->FlushData(endOfDataBlock)) return false; current++; } return true; } //------------------------------------------------------------------------------ // bool NotifyEndOfRun() //------------------------------------------------------------------------------ bool Publisher::NotifyEndOfRun() { // No subscribers if (subscriberList.empty()) return false; std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { if (!(*current)->SetEndOfRun()) return false; current++; } return true; } //------------------------------------------------------------------------------ // const std::list<Subscriber*> GetSubscriberList() //------------------------------------------------------------------------------ const std::list<Subscriber*> Publisher::GetSubscriberList() { return subscriberList; } //------------------------------------------------------------------------------ // void ClearPublishedData() //------------------------------------------------------------------------------ void Publisher::ClearPublishedData() { #if DBGLVL_PUBLISHER_CLEAR MessageInterface::ShowMessage ("Publisher::ClearPublishedData() entered, clearing %d element owner objects\n", objectArray.size()); MessageInterface::ShowMessage(" providerMap.size()=%u\n", providerMap.size()); MessageInterface::ShowMessage(" subscriberList.size()=%u\n", subscriberList.size()); #endif objectArray.clear(); elementArray.clear(); providerId = -1; currProviderId = -1; // Clear subscriber's data std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { (*current)->ClearDataLabels(); current++; } #if DBGLVL_PUBLISHER_CLEAR > 1 MessageInterface::ShowMessage ("Publisher::ClearPublishedData() Using new Publisher code\n"); #endif std::map<GmatBase*, std::vector<DataType>* >::iterator iter = providerMap.begin(); while (iter != providerMap.end()) { std::vector<DataType>* dataList = iter->second; if (dataList != NULL) { #ifdef DEBUG_MEMORY MemoryTracker::Instance()->Remove (dataList, "dataList", "Publisher::ClearPublishedData()", "deleting dataList"); #endif delete dataList; } iter++; } providerMap.clear(); subscriberList.clear(); #if DBGLVL_PUBLISHER_CLEAR MessageInterface::ShowMessage ("Publisher::ClearPublishedData() leaving, providerMap.size()=%u\n", providerMap.size()); #endif } //------------------------------------------------------------------------------ // Integer RegisterPublishedData(GmatBase *provider, Integer id, // const StringArray& owners, const StringArray& elements) //------------------------------------------------------------------------------ /* * Registers provider with data elements. This method passes elements as data * labels to subscribers by calling SetDataLabels(elements). * * @param provider Provider who calls publiser * @param id Provider id, if id is -1 it will assign new id * @param owners Object names, such as spacecraft name * @param elements Element names, such as Sat1.X, Sat1.Y * * @return new provider id or existing id * * @note Currently only Propagate command registers and publishes orbit * trajectory data. The owner is not currently used since elements has owner * name, such as Sat1.X which Sat1 is the owner name. */ //------------------------------------------------------------------------------ Integer Publisher::RegisterPublishedData(GmatBase *provider, Integer id, const StringArray& owners, const StringArray& elements) { #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage ("Publisher::RegisterPublishedData() entered, <%p><%s> passed id: %d, %d " "owners and %d elements\n", provider, provider->GetTypeName().c_str(), id, owners.size(), elements.size()); MessageInterface::ShowMessage(" providerMap.size()=%d\n", providerMap.size()); #endif #if DBGLVL_PUBLISHER_REGISTER > 1 for (unsigned int i=0; i<owners.size(); i++) MessageInterface::ShowMessage(" owner[%d]=%s\n", i, owners[i].c_str()); for (unsigned int i=0; i<elements.size(); i++) MessageInterface::ShowMessage(" elements[%d]=%s\n", i, elements[i].c_str()); MessageInterface::ShowMessage (" providerId=%d, subscriberList.size()=%d\n", providerId, subscriberList.size()); #endif if (subscriberList.empty()) { // Let's just show warning if debug is turned on //throw PublisherException("There are no registered subscribers."); #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage ("*** WARNING *** Publisher::RegisterPublishedData() There are no " "subscribers to register data\n"); MessageInterface::ShowMessage ("Publisher::RegisterPublishedData() returning %d\n", providerId); #endif return providerId; } Integer actualId = -1; #if DBGLVL_PUBLISHER_REGISTER > 1 MessageInterface::ShowMessage ("Publisher::RegisterPublishedData() Using new Publisher code\n"); #endif if (id != -1) { #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage ("Publisher::RegisterPublishedData() returning %d, provider already has " "registered with data\n", id); #endif // Just set current run state std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { #if DBGLVL_PUBLISHER_REGISTER > 1 MessageInterface::ShowMessage (" calling <%s>->SetRunState()\n", (*current)->GetName().c_str()); #endif (*current)->SetRunState(runState); current++; } return id; } // Add publishing data object names std::map<GmatBase*, std::vector<DataType>* >::iterator iter = providerMap.find(provider); if (!owners.empty()) { //@tbd Should it be cleared first? (LOJ: 2009.11.04) objectArray.clear(); objectArray.push_back(StringArray(owners)); } // @note // New Publisher code doesn't use global providerId anymore. It keeps // track of provider's data labels and ids and copies corresponding // labels to current data labels before distributing the data in Publish(). // There was an issue with provider id being kept incrementing if data is // registered and published inside a GmatFunction if (!elements.empty()) { if (iter == providerMap.end()) { #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage("==> provider not found\n"); #endif // create new dataList actualId = 0; DataType newData(elements, actualId); std::vector<DataType>* dataList = new std::vector<DataType>; #ifdef DEBUG_MEMORY MemoryTracker::Instance()->Add (dataList, "dataList", "Publisher::RegisterPublishedData()", "creating dataList"); #endif dataList->push_back(newData); providerMap.insert(std::make_pair(provider, dataList)); } else { #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage("==> provider found\n"); #endif std::vector<DataType>* oldList = iter->second; actualId = oldList->size(); DataType newData(elements, actualId); oldList->push_back(newData); } } #if DBGLVL_PUBLISHER_REGISTER > 1 std::map<GmatBase*, std::vector<DataType>* >::iterator iter2 = providerMap.find(provider); std::vector<DataType>* tempList = iter2->second; MessageInterface::ShowMessage (" actualId=%d, tempList->size() = %d\n", actualId, tempList->size()); #endif providerId = actualId; std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { #if DBGLVL_PUBLISHER_REGISTER > 1 MessageInterface::ShowMessage (" calling <%s>->SetDataLabels()\n", (*current)->GetName().c_str()); #endif (*current)->SetDataLabels(elements); (*current)->SetRunState(runState); current++; } #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage(" providerMap.size()=%d\n", providerMap.size()); MessageInterface::ShowMessage ("Publisher::RegisterPublishedData() provider=<%p> returning %d\n", provider, actualId); #endif return actualId; } //------------------------------------------------------------------------------ // UnregisterPublishedData(GmatBase *provider) //------------------------------------------------------------------------------ void Publisher::UnregisterPublishedData(GmatBase *provider) { #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage ("Publisher::UnregisterPublishedData() entered, <%p><%s>, providerMap.size() = %d\n", provider, provider->GetTypeName().c_str(), providerMap.size()); #endif std::map<GmatBase*, std::vector<DataType>* >::iterator iter = providerMap.find(provider); if (iter != providerMap.end()) { std::vector<DataType>* dataList = iter->second; if (dataList != NULL) { #ifdef DEBUG_MEMORY MemoryTracker::Instance()->Remove (dataList, "dataList", "Publisher::UnregisterPublishedData()", "deleting dataList"); #endif delete dataList; } providerMap.erase(iter); } else { #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage ("*** WARNING *** Publisher::UnregisterPublishedData() provider <%p> " "not registered\n"); #endif } #if DBGLVL_PUBLISHER_REGISTER MessageInterface::ShowMessage ("Publisher::UnregisterPublishedData() leaving, providerMap.size() = %d\n", providerMap.size()); #endif } //------------------------------------------------------------------------------ // const StringArray& GetStringArrayParameter(const std::string& type) //------------------------------------------------------------------------------ const StringArray& Publisher::GetStringArrayParameter(const std::string& type) { if ((currProviderId < 0) || (currProviderId > providerId)) throw PublisherException("Data provider id out of range."); if (type == "SpaceObjectMap") return objectArray[currProviderId]; if (type == "PublishedDataMap") return elementArray[currProviderId]; throw PublisherException("Unknown StringArray type requested."); } //------------------------------------------------------------------------------ // void SetInternalCoordSystem(CoordinateSystem *cs) //------------------------------------------------------------------------------ /* * Sets the internal coordinate system. * * @parameter cs Internal coordinate system (usally EarthMJ2000Eq) */ //------------------------------------------------------------------------------ void Publisher::SetInternalCoordSystem(CoordinateSystem *cs) { if (cs != NULL) internalCoordSystem = cs; } //------------------------------------------------------------------------------ // void SetDataCoordSystem(CoordinateSystem *cs) //------------------------------------------------------------------------------ /* * Sets the coordinate system of data to subscribers. It also adds the coordinate * system to the map, if it is not found. * * @parameter cs Coordinate system which data represents */ //------------------------------------------------------------------------------ void Publisher::SetDataCoordSystem(CoordinateSystem *cs) { if (cs == NULL) return; dataCoordSystem = cs; std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { (*current)->SetDataCoordSystem(cs); current++; } // if coordinate system not found in the map, add std::string csName = cs->GetName(); if (coordSysMap.find(csName) != coordSysMap.end()) coordSysMap[csName] = cs; } //------------------------------------------------------------------------------ // void SetDataMJ2000EqOrigin(CelestialBody *cb) //------------------------------------------------------------------------------ /* * Sets origin of MJ2000Eq coordinate system which data represents. If matching * coordinate system name found from the map, it sets to data coordinate system, * otherwise, it creates new coordinate system. * * @parameter cb Origin of MJ2000Eq coordinate system which data represents */ //------------------------------------------------------------------------------ void Publisher::SetDataMJ2000EqOrigin(CelestialBody *cb) { if (cb == NULL) return; #if DBGLVL_PUBLISHER_DATA_REP MessageInterface::ShowMessage ("Publisher::SetDataMJ2000EqOrigin() cb=%s<%p>\n", cb->GetName().c_str(), cb); #endif dataMJ2000EqOrigin = cb; std::string originName = cb->GetName(); std::string csName = originName + "MJ2000Eq"; std::map<std::string, CoordinateSystem*>::iterator csIter = coordSysMap.find(csName); if (coordSysMap.find(csName) != coordSysMap.end()) { // set coordinate system from the map dataCoordSystem = coordSysMap.find(csName)->second; } else { // check as local name csName = "Local-" + csName; if (coordSysMap.find(csName) != coordSysMap.end()) dataCoordSystem = coordSysMap.find(csName)->second; else { // Create coordinate system if not exist CoordinateSystem *newCs = (CoordinateSystem*)internalCoordSystem->Clone(); newCs->SetName(csName); newCs->SetStringParameter("Origin", originName); newCs->SetRefObject(cb, Gmat::CELESTIAL_BODY, originName); newCs->Initialize(); coordSysMap[csName] = newCs; dataCoordSystem = newCs; #if DBGLVL_PUBLISHER_DATA_REP MessageInterface::ShowMessage (" ===> %s not found in the map, so created <%p>\n", csName.c_str(), newCs); #endif } } // set to subscribers std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { (*current)->SetDataMJ2000EqOrigin(cb); (*current)->SetDataCoordSystem(dataCoordSystem); current++; } } //------------------------------------------------------------------------------ // void SetRunState(const Gmat::RunState state) //------------------------------------------------------------------------------ void Publisher::SetRunState(const Gmat::RunState state) { #ifdef DEBUG_PUBLISHER_RUN_STATE MessageInterface::ShowMessage ("Publisher::SetRunState() entered, setting run state %d to " "%d subscribers\n", state, subscriberList.size()); #endif runState = state; std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { #ifdef DEBUG_PUBLISHER_RUN_STATE MessageInterface::ShowMessage(" current=<%p>\n", *current); #endif (*current)->SetRunState(runState); current++; } #ifdef DEBUG_PUBLISHER_RUN_STATE MessageInterface::ShowMessage("Publisher::SetRunState() exiting\n"); #endif } //------------------------------------------------------------------------------ // void SetManeuvering(GmatBase *originator, bool flag, Real epoch, // const std::string &satName, const std::string &desc) //------------------------------------------------------------------------------ /** * Sets single spacecraft maneuvering flag. * * @param originator The maneuver command pointer who is maneuvering * @param flag Set to true if maneuvering * @param epoch Epoch of maneuver * @param satName Name of the maneuvering spacecraft * @param desc Description of maneuver (e.g. impulsive or finite) */ //------------------------------------------------------------------------------ void Publisher::SetManeuvering(GmatBase *originator, bool flag, Real epoch, const std::string &satName, const std::string &desc) { maneuvering = flag; std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { (*current)->SetManeuvering(originator, flag, epoch, satName, desc); current++; } } //------------------------------------------------------------------------------ // void SetManeuvering(GmatBase *originator, bool flag, Real epoch, // const StringArray &satNames, const std::string &desc) //------------------------------------------------------------------------------ /** * Sets multiple spacecrafts maneuvering flag. * * @param originator The maneuver command pointer who is maneuvering * @param flag Set to true if maneuvering * @param epoch Epoch of maneuver * @param satNames Names of the maneuvering spacecraft * @param desc Description of maneuver (e.g. impulsive or finite) */ //------------------------------------------------------------------------------ void Publisher::SetManeuvering(GmatBase *originator, bool flag, Real epoch, const StringArray &satNames, const std::string &desc) { maneuvering = flag; std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { (*current)->SetManeuvering(originator, flag, epoch, satNames, desc); current++; } } //------------------------------------------------------------------------------ // bool GetManeuvering() //------------------------------------------------------------------------------ bool Publisher::GetManeuvering() { return maneuvering; } //------------------------------------------------------------------------------ // void SetScPropertyChanged(GmatBase *originator, Real epoch, // const std::string &satName, const std::string &desc) //------------------------------------------------------------------------------ /** * Sets spacecraft property change so that subscribers can handle appropriately. * * @param originator The assignment command pointer who is setting * @param epoch Epoch of spacecraft at property change * @param satName Name of the spacecraft * @param desc Description of property change */ //------------------------------------------------------------------------------ void Publisher::SetScPropertyChanged(GmatBase *originator, Real epoch, const std::string &satName, const std::string &desc) { std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { (*current)->SetScPropertyChanged(originator, epoch, satName, desc); current++; } } //------------------------------------------------------------------------------ // void UpdateProviderId(Integer newId) //------------------------------------------------------------------------------ void Publisher::UpdateProviderId(Integer newId) { std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { (*current)->SetProviderId(newId); current++; } } //------------------------------------------------------------------------------ // void ShowSubscribers() //------------------------------------------------------------------------------ void Publisher::ShowSubscribers() { if (subscriberList.empty()) { MessageInterface::ShowMessage(" ===== There are no subscribers\n"); return; } MessageInterface::ShowMessage (" ===== There are %d subscriber(s)\n", subscriberList.size()); std::list<Subscriber*>::iterator current = subscriberList.begin(); while (current != subscriberList.end()) { MessageInterface::ShowMessage (" <%p>'%s'\n", *current, (*current)->GetName().c_str()); current++; } }
/** * @file * @copyright defined in oac/LICENSE.txt */ #include <oac/chain/block.hpp> #include <oac/chain/merkle.hpp> #include <fc/io/raw.hpp> #include <fc/bitutil.hpp> #include <algorithm> namespace oac { namespace chain { digest_type block_header::digest()const { return digest_type::hash(*this); } uint32_t block_header::num_from_id(const block_id_type& id) { return fc::endian_reverse_u32(id._hash[0]); } block_id_type block_header::id()const { // Do not include signed_block_header attributes in id, specifically exclude producer_signature. block_id_type result = digest(); //fc::sha256::hash(*static_cast<const block_header*>(this)); result._hash[0] &= 0xffffffff00000000; result._hash[0] += fc::endian_reverse_u32(block_num()); // store the block num in the ID, 160 bits is plenty for the hash return result; } } }
/* ========================================================================= * * * * SMPL++ * * Copyright (c) 2018, Chongyi Zheng. * * All Rights reserved. * * * * ------------------------------------------------------------------------- * * * * This software implements a 3D human skinning model - SMPL: A Skinned * * Multi-Person Linear Model with C++. * * * * For more detail, see the paper published by Max Planck Institute for * * Intelligent Systems on SIGGRAPH ASIA 2015. * * * * We provide this software for research purposes only. * * The original SMPL model is available at http://smpl.is.tue.mpg. * * * * ========================================================================= */ //============================================================================= // // CLASS Tester IMPLEMENTATIONS // //============================================================================= //===== EXTERNAL MACROS ======================================================= //===== INCLUDES ============================================================== //---------- #include <fstream> //---------- #include <xtensor/xarray.hpp> #include <xtensor/xjson.hpp> //---------- #include "definition/def.h" #include "toolbox/Tester.h" #include "toolbox/TorchEx.hpp" #include "toolbox/Exception.h" #include "toolbox/Singleton.hpp" #include "smpl/BlendShape.h" #include "smpl/JointRegression.h" #include "smpl/WorldTransformation.h" #include "smpl/LinearBlendSkinning.h" //---------- //===== EXTERNAL FORWARD DECLARATIONS ========================================= //===== NAMESPACES ============================================================ namespace smpl { //===== INTERNAL MACROS ======================================================= //===== INTERNAL FORWARD DECLARATIONS ========================================= //===== CLASS IMPLEMENTATIONS ================================================= /**Tester * * Brief * ---------- * * Default constructor. * * Arguments * ---------- * * * Return * ---------- * * */ Tester::Tester() noexcept(true) : m__device(torch::kCPU) { } /**Tester (overload) * * Brief * ---------- * * Copy constructor. * * Arguments * ---------- * * @tester: - const Testet & - * The tester to copy with. * * Return * ---------- * * */ Tester::Tester(const Tester &tester) noexcept(true) : m__device(torch::kCPU) { *this = tester; } /**~Tester * * Brief * ---------- * * Destructor. * * Arguments * ---------- * * * Return * ---------- * * */ Tester::~Tester() noexcept(true) { } /**operator= * * Brief * ---------- * * Assignment operator is used to copy an tester. * * Arguments * ---------- * * @tester: - const Tester & - * The tester to copy with. * * Return * ---------- * * @*this: - Tester & - * Current instantiation. * */ Tester &Tester::operator=(const Tester &tester) noexcept(false) { if (tester.m__device.has_index()) { m__device = tester.m__device; } else { throw smpl_error("Tester", "Failed to fetch device index!"); } return *this; } /**setDevice * * Brief * ---------- * * Set the torch device. * * Arguments * ---------- * * * Return * ---------- * */ void Tester::setDevice(const torch::Device& device) noexcept(false) { if (device.has_index()) { m__device = device; } else { throw smpl_error("Tester", "Failed to fetch device index!"); } return; } /**singleton * * Brief * ---------- * * Test the <Singleton> module. * * Arguments * ---------- * * * Return * ---------- * * */ void Tester::singleton() noexcept(true) { std::cout << "---------- <Singleton> Test ----------" << std::endl; const int *intPtr1 = Singleton<int>::get(); const int *intPtr2 = Singleton<int>::get(); const float *floatPtr1 = Singleton<float>::get(); const float *floatPtr2 = Singleton<float>::get(); assert(intPtr1 == intPtr2); assert(floatPtr1 == floatPtr2); std::cout << "intPtr1: " << intPtr1 << std::endl; std::cout << "intPtr2: " << intPtr2 << std::endl; std::cout << std::endl; std::cout << "floatPtr1: " << floatPtr1 << std::endl; std::cout << "floatPtr2: " << floatPtr2 << std::endl; std::cout << std::endl; Singleton<int>::destroy(); Singleton<float>::destroy(); std::cout << "PASS!" << std::endl; std::cout << "--------------------------------------" << std::endl; return; } /**import * * Brief * ---------- * * Test file reading module. * * Arguments * ---------- * * * Return * ---------- * * */ void Tester::import() noexcept(true) { std::cout << "---------- Import Test ----------" << std::endl; std::ifstream file("../data/smpl_female.json"); nlohmann::json model; file >> model; xt::xarray<int64_t> kinematicTree_; xt::from_json(model["kinematic_tree"], kinematicTree_); /**correct result * * - kinematicTree: [2, 24] * [ * [4294967295, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, * 9, 9, 9, 12, 13, 14, 16, 17, 18, 19, 20, 21], * [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, * 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] * ] */ torch::Tensor kinematicTree = torch::from_blob( kinematicTree_.data(), {2, JOINT_NUM}, torch::kInt64 ).to(m__device); std::cout << "kinematic tree: " << kinematicTree.sizes() << std::endl; std::cout << kinematicTree << std::endl; std::cout << "PASS!" << std::endl; std::cout << "---------------------------------" << std::endl; return; } /**blendShape * * Brief * ---------- * * Test the <BlendShape> module. * * Arguments * ---------- * * * Return * ---------- * * * Notes * ---------- * * We need to set both BATCH_SIZE and VERTEX_NUM in "definition/def.h" to * 1 to make it compatible with this test. * This kind of random number is generated by numpy with random seed 0. * */ void Tester::blendShape() noexcept(true) { int batchSize = BATCH_SIZE; int vertexNum = VERTEX_NUM; BATCH_SIZE = 1; VERTEX_NUM = 1; std::cout << "---------- <BlendShape> Test ----------" << std::endl; xt::xarray<float> theta_ { { {0.79172504, 0.52889492, 0.56804456}, {0.92559664, 0.07103606, 0.0871293 }, {0.0202184 , 0.83261985, 0.77815675}, {0.87001215, 0.97861834, 0.79915856}, {0.46147936, 0.78052918, 0.11827443}, {0.63992102, 0.14335329, 0.94466892}, {0.52184832, 0.41466194, 0.26455561}, {0.77423369, 0.45615033, 0.56843395}, {0.0187898 , 0.6176355 , 0.61209572}, {0.616934 , 0.94374808, 0.6818203 }, {0.3595079 , 0.43703195, 0.6976312 }, {0.06022547, 0.66676672, 0.67063787}, {0.21038256, 0.1289263 , 0.31542835}, {0.36371077, 0.57019677, 0.43860151}, {0.98837384, 0.10204481, 0.20887676}, {0.16130952, 0.65310833, 0.2532916 }, {0.46631077, 0.24442559, 0.15896958}, {0.11037514, 0.65632959, 0.13818295}, {0.19658236, 0.36872517, 0.82099323}, {0.09710128, 0.83794491, 0.09609841}, {0.97645947, 0.4686512 , 0.97676109}, {0.60484552, 0.73926358, 0.03918779}, {0.28280696, 0.12019656, 0.2961402 }, {0.11872772, 0.31798318, 0.41426299} } };// (1, 24, 3) torch::Tensor theta = torch::from_blob(theta_.data(), {BATCH_SIZE, JOINT_NUM, 3}).to(m__device); xt::xarray<float> beta_ { { 0.5488135 , 0.71518937, 0.60276338, 0.54488318, 0.4236548 , 0.64589411 , 0.43758721, 0.891773 , 0.96366276, 0.38344152 } };// (1, 10) torch::Tensor beta = torch::from_blob(beta_.data(), {BATCH_SIZE, SHAPE_BASIS_DIM}).to(m__device); xt::xarray<float> poseBlendBasis_ { { {0.0641475 , 0.69247212, 0.56660145, 0.26538949, 0.52324805, 0.09394051, 0.5759465 , 0.9292962 , 0.31856895, 0.66741038, 0.13179786, 0.7163272 , 0.28940609, 0.18319136, 0.58651293, 0.02010755, 0.82894003, 0.00469548, 0.67781654, 0.27000797, 0.73519402, 0.96218855, 0.24875314, 0.57615733, 0.59204193, 0.57225191, 0.22308163, 0.95274901, 0.44712538, 0.84640867, 0.69947928, 0.29743695, 0.81379782, 0.39650574, 0.8811032 , 0.58127287, 0.88173536, 0.69253159, 0.72525428, 0.50132438, 0.95608363, 0.6439902 , 0.42385505, 0.60639321, 0.0191932 , 0.30157482, 0.66017354, 0.29007761, 0.61801543, 0.4287687 , 0.13547406, 0.29828233, 0.56996491, 0.59087276, 0.57432525, 0.65320082, 0.65210327, 0.43141844, 0.8965466 , 0.36756187, 0.43586493, 0.89192336, 0.80619399, 0.70388858, 0.10022689, 0.91948261, 0.7142413 , 0.99884701, 0.1494483 , 0.86812606, 0.16249293, 0.61555956, 0.12381998, 0.84800823, 0.80731896, 0.56910074, 0.4071833 , 0.069167 , 0.69742877, 0.45354268, 0.7220556 , 0.86638233, 0.97552151, 0.85580334, 0.01171408, 0.35997806, 0.72999056, 0.17162968, 0.52103661, 0.05433799, 0.19999652, 0.01852179, 0.7936977 , 0.22392469, 0.34535168, 0.92808129, 0.7044144 , 0.03183893, 0.16469416, 0.6214784 , 0.57722859, 0.23789282, 0.934214 , 0.61396596, 0.5356328 , 0.58990998, 0.73012203, 0.311945 , 0.39822106, 0.20984375, 0.18619301, 0.94437239, 0.7395508 , 0.49045881, 0.22741463, 0.25435648, 0.05802916, 0.43441663, 0.31179588, 0.69634349, 0.37775184, 0.17960368, 0.02467873, 0.06724963, 0.67939277, 0.45369684, 0.53657921, 0.89667129, 0.99033895, 0.21689698, 0.6630782 , 0.26332238, 0.020651 , 0.75837865, 0.32001715, 0.38346389, 0.58831711, 0.83104846, 0.62898184, 0.87265066, 0.27354203, 0.79804683, 0.18563594, 0.95279166, 0.68748828, 0.21550768, 0.94737059, 0.73085581, 0.25394164, 0.21331198, 0.51820071, 0.02566272, 0.20747008, 0.42468547, 0.37416998, 0.46357542, 0.27762871, 0.58678435, 0.86385561, 0.11753186, 0.51737911, 0.13206811, 0.71685968, 0.3960597 , 0.56542131, 0.18327984, 0.14484776, 0.48805628, 0.35561274, 0.94043195, 0.76532525, 0.74866362, 0.90371974, 0.08342244, 0.55219247, 0.58447607, 0.96193638, 0.29214753, 0.24082878, 0.10029394, 0.01642963, 0.92952932, 0.66991655, 0.78515291, 0.28173011, 0.58641017, 0.06395527, 0.4856276 , 0.97749514, 0.87650525, 0.33815895, 0.96157015, 0.23170163, 0.94931882, 0.9413777 , 0.79920259, 0.63044794, 0.87428797, 0.29302028, 0.84894356, 0.61787669, 0.01323686, 0.34723352, 0.14814086, 0.98182939, 0.47837031, 0.49739137}, {0.63947252, 0.36858461, 0.13690027, 0.82211773, 0.18984791, 0.51131898, 0.22431703, 0.09784448, 0.86219152, 0.97291949, 0.96083466, 0.9065555 , 0.77404733, 0.33314515, 0.08110139, 0.40724117, 0.23223414, 0.13248763, 0.05342718, 0.72559436, 0.01142746, 0.77058075, 0.14694665, 0.07952208, 0.08960303, 0.67204781, 0.24536721, 0.42053947, 0.55736879, 0.86055117, 0.72704426, 0.27032791, 0.1314828 , 0.05537432, 0.30159863, 0.26211815, 0.45614057, 0.68328134, 0.69562545, 0.28351885, 0.37992696, 0.18115096, 0.78854551, 0.05684808, 0.69699724, 0.7786954 , 0.77740756, 0.25942256, 0.37381314, 0.58759964, 0.2728219 , 0.3708528 , 0.19705428, 0.45985588, 0.0446123 , 0.79979588, 0.07695645, 0.51883515, 0.3068101 , 0.57754295, 0.95943334, 0.64557024, 0.03536244, 0.43040244, 0.51001685, 0.53617749, 0.68139251, 0.2775961 , 0.12886057, 0.39267568, 0.95640572, 0.18713089, 0.90398395, 0.54380595, 0.45691142, 0.88204141, 0.45860396, 0.72416764, 0.39902532, 0.90404439, 0.69002502, 0.69962205, 0.3277204 , 0.75677864, 0.63606106, 0.24002027, 0.16053882, 0.79639147, 0.9591666 , 0.45813883, 0.59098417, 0.85772264, 0.45722345, 0.95187448, 0.57575116, 0.82076712, 0.90884372, 0.81552382, 0.15941446, 0.62889844, 0.39843426, 0.06271295, 0.42403225, 0.25868407, 0.84903831, 0.03330463, 0.95898272, 0.35536885, 0.35670689, 0.0163285 , 0.18523233, 0.4012595 , 0.92929142, 0.09961493, 0.94530153, 0.86948853, 0.4541624 , 0.32670088, 0.23274413, 0.61446471, 0.03307459, 0.01560606, 0.42879572, 0.06807407, 0.25194099, 0.22116092, 0.25319119, 0.13105523, 0.01203622, 0.1154843 , 0.61848026, 0.97425621, 0.990345 , 0.4090541 , 0.16295443, 0.63876176, 0.49030535, 0.98940978, 0.06530421, 0.78323444, 0.2883985 , 0.24141862, 0.66250457, 0.24606318, 0.66585912, 0.51730852, 0.42408899, 0.55468781, 0.28705152, 0.70657471, 0.41485687, 0.36054556, 0.82865691, 0.92496691, 0.04600731, 0.23262699, 0.34851937, 0.81496648, 0.98549143, 0.9689717 , 0.90494835, 0.29655627, 0.99201124, 0.24942004, 0.10590615, 0.95095261, 0.23342026, 0.68976827, 0.05835636, 0.7307091 , 0.88172021, 0.2724369 , 0.3790569 , 0.37429618, 0.74878826, 0.23780724, 0.1718531 , 0.44929165, 0.30446841, 0.83918912, 0.23774183, 0.50238946, 0.9425836 , 0.6339977 , 0.86728941, 0.94020969, 0.75076486, 0.69957506, 0.96796557, 0.99440079, 0.45182168, 0.07086978, 0.29279403, 0.15235471, 0.41748637, 0.13128933, 0.6041178 , 0.38280806, 0.89538588, 0.96779467, 0.5468849 , 0.27482357, 0.59223042, 0.89676116, 0.40673335, 0.55207828, 0.27165277}, {0.45544415, 0.40171354, 0.24841347, 0.50586638, 0.31038083, 0.37303486, 0.52497044, 0.75059502, 0.33350747, 0.92415877, 0.86231855, 0.0486903 , 0.25364252, 0.44613551, 0.10462789, 0.34847599, 0.74009753, 0.68051448, 0.62238443, 0.7105284 , 0.20492369, 0.34169811, 0.67624248, 0.87923476, 0.54367805, 0.28269965, 0.03023526, 0.71033683, 0.0078841 , 0.37267907, 0.53053721, 0.92211146, 0.08949455, 0.40594232, 0.0243132 , 0.34261098, 0.62223106, 0.27906795, 0.20974995, 0.11570323, 0.57714024, 0.69527001, 0.67195714, 0.94886102, 0.00270321, 0.64719665, 0.60039224, 0.58873961, 0.96277032, 0.01687167, 0.69648243, 0.81367865, 0.5098072 , 0.33396487, 0.79084016, 0.09724293, 0.44203564, 0.51995237, 0.69395641, 0.09088573, 0.2277595 , 0.41030156, 0.62329467, 0.88696078, 0.61882617, 0.13346147, 0.98058013, 0.87178573, 0.50272076, 0.92234798, 0.54138079, 0.92330607, 0.82989737, 0.96828641, 0.91978281, 0.03603382, 0.174772 , 0.38913468, 0.9521427 , 0.30002892, 0.16046764, 0.88630467, 0.44639442, 0.90787559, 0.16023047, 0.66111751, 0.44026375, 0.07648677, 0.69646314, 0.24739876, 0.03961552, 0.0599443 , 0.06107854, 0.90773296, 0.73988392, 0.89806236, 0.67258231, 0.52893993, 0.30444636, 0.99796225, 0.36218906, 0.47064895, 0.37824517, 0.97952693, 0.17465839, 0.327988 , 0.68034867, 0.06320762, 0.60724937, 0.4776465 , 0.28399998, 0.23841328, 0.51451274, 0.36792758, 0.45651989, 0.33747738, 0.97049369, 0.13343943, 0.09680395, 0.34339173, 0.5910269 , 0.65917647, 0.39725675, 0.99927799, 0.351893 , 0.72140667, 0.63758269, 0.81305386, 0.97622566, 0.88979366, 0.76456197, 0.69824848, 0.33549817, 0.14768558, 0.062636 , 0.2419017 , 0.43228148, 0.52199627, 0.77308355, 0.95874092, 0.11732048, 0.10700414, 0.58969472, 0.74539807, 0.84815038, 0.93583208, 0.98342624, 0.39980169, 0.38033518, 0.14780868, 0.68493444, 0.65676196, 0.8620626 , 0.09725799, 0.49777691, 0.58108193, 0.24155704, 0.16902541, 0.85958084, 0.05853492, 0.4706209 , 0.115834 , 0.45705876, 0.97996233, 0.42370635, 0.85712492, 0.11731556, 0.27125208, 0.40379274, 0.39981214, 0.67138348, 0.34471813, 0.71376687, 0.6391869 , 0.39916115, 0.43176013, 0.6145277 , 0.07004219, 0.82240674, 0.65342116, 0.72634246, 0.536923 , 0.11047711, 0.40503561, 0.40537358, 0.32104299, 0.02995032, 0.73725424, 0.10978446, 0.60630813, 0.7032175 , 0.63478632, 0.95914225, 0.10329816, 0.86716716, 0.02919023, 0.53491685, 0.40424362, 0.52418386, 0.36509988, 0.19056691, 0.0191229 , 0.51814981, 0.84277686, 0.37321596, 0.22286382, 0.080532 } } };// (1, 3, 207) torch::Tensor poseBlendBasis = torch::from_blob(poseBlendBasis_.data(), {BATCH_SIZE, 3, POSE_BASIS_DIM}).to(m__device); xt::xarray<float> shapeBlendBasis_ { { {0.08531092, 0.22139645, 0.10001406, 0.2650397 , 0.06614946, 0.06560487, 0.85627618, 0.16212026, 0.55968241, 0.77345554}, {0.45640957, 0.15336888, 0.19959614, 0.43298421, 0.52823409, 0.34944029, 0.7814796 , 0.75102165, 0.92721181, 0.02895255}, {0.89569129, 0.39256879, 0.8783725 , 0.69078478, 0.98734876, 0.75928245, 0.36454463, 0.50106317, 0.37638916, 0.36491184} } };// (1, 3, 10) torch::Tensor shapeBlendBasis = torch::from_blob(shapeBlendBasis_.data(), {BATCH_SIZE, 3, SHAPE_BASIS_DIM}).to(m__device); /**correct result * * - shapeBlendShape: [1, 3] * [ * [1.835449, 3.082224, 3.695877] * ] * * - poseBlendShape: [1, 3] * [ * [ * [0.912995, -1.879041, -3.56463] * ] * ] * * - poseRotation: [5, 3, 3] * [ * [ * [ 0.728415, -0.269833, 0.629764], * [ 0.647397, 0.571931, -0.503758], * [-0.224251, 0.774652, 0.591292] * ], * [ * [ 0.994126, -0.044481, 0.098667], * [ 0.105604, 0.598255, -0.794316], * [-0.023696, 0.80007 , 0.599438], * ], * [ * [ 0.41794 , -0.612729, 0.670738], * [ 0.627818, 0.728445, 0.274249], * [-0.656636, 0.306481, 0.689129] * ], * [ * [ 0.346577, -0.172097, 0.922099], * [ 0.869102, 0.428758, -0.246636], * [-0.352912, 0.886876, 0.298167] * ], * [ * [ 0.70951 , 0.065427, 0.701652], * [ 0.270361, 0.894214, -0.356772], * [-0.650769, 0.442832, 0.616765] * ] * ] * * - restPoseRotation: [1, 3, 3] * [ * [1., 0., 0.], * [0., 1., 0.], * [0., 0., 1.] * ] */ torch::Tensor shapeBlendShape, poseBlendShape; torch::Tensor poseRotation, restPoseRotation; try { BlendShape blendShape; blendShape.setDevice(m__device); blendShape.setTheta(theta); blendShape.setBeta(beta); blendShape.setPoseBlendBasis(poseBlendBasis); blendShape.setShapeBlendBasis(shapeBlendBasis); blendShape.blend(); shapeBlendShape = blendShape.getShapeBlendShape();// (1, 1, 3) poseBlendShape = blendShape.getPoseBlendShape();// (1, 1, 3) poseRotation = blendShape.getPoseRotation();// (1, 24, 3, 3) restPoseRotation = blendShape.getRestPoseRotation();// (1, 24, 3, 3) } catch(Exception &e) { std::cerr << e.what() << std::endl; } std::cout << "shape blend shape: " << shapeBlendShape.sizes() << std::endl;// (1, 1, 3) std::cout << shapeBlendShape << std::endl; std::cout << std::endl; std::cout << "pose blend shape: " << poseBlendShape.sizes() << std::endl;// (1, 3, 3) std::cout << poseBlendShape << std::endl; std::cout << std::endl; torch::Tensor poseRotSlice = TorchEx::indexing(poseRotation, torch::IntList({0}), torch::IntList({0, 5}), torch::IntList(), torch::IntList() ); std::cout << "first five pose rotation: " << poseRotSlice.sizes() << std::endl;// (5, 3, 3) std::cout << poseRotSlice << std::endl;// the first five rotation std::cout << std::endl; torch::Tensor restRotSlice = TorchEx::indexing(restPoseRotation, torch::IntList(), torch::IntList({0}), torch::IntList(), torch::IntList() ); std::cout << "first rest pose rotation: " << restRotSlice.sizes() << std::endl;// (1, 3, 3) std::cout << restRotSlice << std::endl;// the first rotation std::cout << std::endl; std::cout << "PASS!" << std::endl; std::cout << "---------------------------------------" << std::endl; BATCH_SIZE = batchSize; VERTEX_NUM = vertexNum; return; } /**jointRegression * * Brief * ---------- * * Test the <JointRegression> module. * * Arguments * ---------- * * * Return * ---------- * * * Notes * ---------- * * We need to set BATCH_SIZE in "definition/def.h" to 1 and VERTEX_NUM to * 5 to make it compatible with this test. * This kind of random number is generated by numpy with random seed 0. * */ void Tester::jointRegression() noexcept(true) { int batchSize = BATCH_SIZE; int vertexNum = VERTEX_NUM; BATCH_SIZE = 1; VERTEX_NUM = 5; std::cout << "---------- <JointRegression> Test ----------" << std::endl; xt::xarray<float> templateShape_ { {0.5488135 , 0.71518937, 0.60276338}, {0.54488318, 0.4236548 , 0.64589411}, {0.43758721, 0.891773 , 0.96366276}, {0.38344152, 0.79172504, 0.52889492}, {0.56804456, 0.92559664, 0.07103606} };// (5, 3) torch::Tensor templateShape = torch::from_blob(templateShape_.data(), {VERTEX_NUM, 3}).to(m__device); xt::xarray<float> jointRegressor_ { {0.0871293 , 0.0202184 , 0.83261985, 0.77815675, 0.87001215}, {0.97861834, 0.79915856, 0.46147936, 0.78052918, 0.11827443}, {0.63992102, 0.14335329, 0.94466892, 0.52184832, 0.41466194}, {0.26455561, 0.77423369, 0.45615033, 0.56843395, 0.0187898 }, {0.6176355 , 0.61209572, 0.616934 , 0.94374808, 0.6818203 }, {0.3595079 , 0.43703195, 0.6976312 , 0.06022547, 0.66676672}, {0.67063787, 0.21038256, 0.1289263 , 0.31542835, 0.36371077}, {0.57019677, 0.43860151, 0.98837384, 0.10204481, 0.20887676}, {0.16130952, 0.65310833, 0.2532916 , 0.46631077, 0.24442559}, {0.15896958, 0.11037514, 0.65632959, 0.13818295, 0.19658236}, {0.36872517, 0.82099323, 0.09710128, 0.83794491, 0.09609841}, {0.97645947, 0.4686512 , 0.97676109, 0.60484552, 0.73926358}, {0.03918779, 0.28280696, 0.12019656, 0.2961402 , 0.11872772}, {0.31798318, 0.41426299, 0.0641475 , 0.69247212, 0.56660145}, {0.26538949, 0.52324805, 0.09394051, 0.5759465 , 0.9292962 }, {0.31856895, 0.66741038, 0.13179786, 0.7163272 , 0.28940609}, {0.18319136, 0.58651293, 0.02010755, 0.82894003, 0.00469548}, {0.67781654, 0.27000797, 0.73519402, 0.96218855, 0.24875314}, {0.57615733, 0.59204193, 0.57225191, 0.22308163, 0.95274901}, {0.44712538, 0.84640867, 0.69947928, 0.29743695, 0.81379782}, {0.39650574, 0.8811032 , 0.58127287, 0.88173536, 0.69253159}, {0.72525428, 0.50132438, 0.95608363, 0.6439902 , 0.42385505}, {0.60639321, 0.0191932 , 0.30157482, 0.66017354, 0.29007761}, {0.61801543, 0.4287687 , 0.13547406, 0.29828233, 0.56996491} };// (24, 5) torch::Tensor jointRegressor = torch::from_blob(jointRegressor_.data(), {JOINT_NUM, VERTEX_NUM}).to(m__device); xt::xarray<float> shapeBlendShape_ { { {0.1494483 , 0.86812606, 0.16249293}, {0.61555956, 0.12381998, 0.84800823}, {0.80731896, 0.56910074, 0.4071833 }, {0.069167 , 0.69742877, 0.45354268}, {0.7220556 , 0.86638233, 0.97552151} } };// (1, 5, 3) torch::Tensor shapeBlendShape = torch::from_blob(shapeBlendShape_.data(), {BATCH_SIZE, VERTEX_NUM, 3}).to(m__device); xt::xarray<float> poseBlendShape_ { { {0.59087276, 0.57432525, 0.65320082}, {0.65210327, 0.43141844, 0.8965466 }, {0.36756187, 0.43586493, 0.89192336}, {0.80619399, 0.70388858, 0.10022689}, {0.91948261, 0.7142413 , 0.99884701} } };// (1, 5, 3) torch::Tensor poseBlendShape = torch::from_blob(poseBlendShape_.data(), {BATCH_SIZE, VERTEX_NUM, 3}).to(m__device); /**correct results * * - restShape: (1, 5, 3) * [ * [ * [1.289135, 2.157641, 1.418457], * [1.812546, 0.978893, 2.390449], * [1.612468, 1.896739, 2.262769], * [1.258803, 2.193042, 1.082664], * [2.209583, 2.50622 , 2.045405] * ] * ] * * - joints: (1, 24, 3) * [ * [2.595438, 4.083213, 2.913282], * [2.691068, 4.035417, 3.465978], * [2.560358, 3.991899, 2.945506], * [1.932566, 2.389283, 2.56251 ], * [3.216363, 4.841475, 3.87352 ], * [2.514121, 3.112146, 2.641321], * [1.484908, 2.486839, 1.694772], * [2.45321 , 3.113077, 2.765337], * [1.712245, 2.115405, 2.160274], * [1.372309, 1.828988, 1.52776 ], * [1.834302, 2.595169, 2.565565], * [3.669125, 5.454995, 4.154255], * [0.792384, 1.046224, 1.03244 ], * [1.827013, 2.870513, 2.223435], * [2.369021, 3.366848, 2.651944], * [1.858591, 2.647657, 2.428134], * [1.214805, 1.883359, 1.863242], * [2.458281, 4.173653, 3.135531], * [3.13185 , 4.111864, 3.326101], * [3.349709, 4.094417, 3.709395], * [3.315481, 4.513383, 4.00757 ], * [3.116701, 4.538026, 3.690847], * [1.494156, 2.914095, 1.858294], * [1.968068, 2.876717, 2.188738] * ] * */ torch::Tensor restShape, joints; try { JointRegression jointRegression; jointRegression.setDevice(m__device); jointRegression.setShapeBlendShape(shapeBlendShape); jointRegression.setPoseBlendShape(poseBlendShape); jointRegression.setTemplateRestShape(templateShape); jointRegression.setJointRegressor(jointRegressor); jointRegression.regress(); restShape = jointRegression.getRestShape(); joints = jointRegression.getJoint(); } catch(std::exception &e) { std::cerr << e.what() << std::endl; } std::cout << "deformed shape in rest pose: "; std::cout << restShape.sizes() << std::endl;// (1, 5, 3) std::cout << restShape << std::endl; std::cout << std::endl; std::cout << "joints of deformed shape: "; std::cout << joints.sizes() << std::endl;// (1, 24, 3) std::cout << joints << std::endl; std::cout << std::endl; std::cout << "PASS!" << std::endl; std::cout << "--------------------------------------------" << std::endl; BATCH_SIZE = batchSize; VERTEX_NUM = vertexNum; return; } /**worldTransformation * * Brief * ---------- * * Test the <WorldTransformation> module. * * Arguments * ---------- * * * Return * ---------- * * * Notes * ---------- * * We need to set BATCH_SIZE in "definition/def.h" to 1 to make it * compatible with this test. * This kind of random number is generated by numpy with random seed 0. * */ void Tester::worldTransformation() noexcept(true) { int batchSize = BATCH_SIZE; BATCH_SIZE = 1; std::cout << "---------- <WorldTransformation> Test ----------" << std::endl; /** * * This array is exactly the kinematic tree of SMPL. * * first row - ancestor index * second row - joint indices * * Note: Joint with ancestor index as 4294967295 is indeed root at * the belly button. * */ xt::xarray<int64_t> kineTree_ { {4294967295, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19, 20, 21}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23} };// (2, 24) torch::Tensor kineTree = torch::from_blob(kineTree_.data(), {2, JOINT_NUM}, torch::kInt64).to(m__device); xt::xarray<float> joints_ { { {0.5488135 , 0.71518937, 0.60276338}, {0.54488318, 0.4236548 , 0.64589411}, {0.43758721, 0.891773 , 0.96366276}, {0.38344152, 0.79172504, 0.52889492}, {0.56804456, 0.92559664, 0.07103606}, {0.0871293 , 0.0202184 , 0.83261985}, {0.77815675, 0.87001215, 0.97861834}, {0.79915856, 0.46147936, 0.78052918}, {0.11827443, 0.63992102, 0.14335329}, {0.94466892, 0.52184832, 0.41466194}, {0.26455561, 0.77423369, 0.45615033}, {0.56843395, 0.0187898 , 0.6176355 }, {0.61209572, 0.616934 , 0.94374808}, {0.6818203 , 0.3595079 , 0.43703195}, {0.6976312 , 0.06022547, 0.66676672}, {0.67063787, 0.21038256, 0.1289263 }, {0.31542835, 0.36371077, 0.57019677}, {0.43860151, 0.98837384, 0.10204481}, {0.20887676, 0.16130952, 0.65310833}, {0.2532916 , 0.46631077, 0.24442559}, {0.15896958, 0.11037514, 0.65632959}, {0.13818295, 0.19658236, 0.36872517}, {0.82099323, 0.09710128, 0.83794491}, {0.09609841, 0.97645947, 0.4686512 } } };// (1, 24, 3) torch::Tensor joints = torch::from_blob(joints_.data(), {BATCH_SIZE, JOINT_NUM, 3}).to(m__device); xt::xarray<float> poseRotation_ { { { {0.95627849, 0.89187929, 0.90854612}, {0.03836603, 0.41701503, 0.14772014}, {0.28993016, 0.17507081, 0.39079753} }, { {0.58499362, 0.10064153, 0.54457918}, {0.80011548, 0.41637173, 0.41149671}, {0.13265631, 0.90360714, 0.73082417} }, { {0.32537401, 0.91710756, 0.15341195}, {0.73162891, 0.39768113, 0.21323369}, {0.59904164, 0.02763035, 0.96488143} }, { {0.00502689, 0.51447925, 0.39713296}, {0.78708538, 0.73032452, 0.36587094}, {0.61682359, 0.44937423, 0.84167919} }, { {0.18665207, 0.7642271 , 0.43332029}, {0.70818889, 0.56107224, 0.28825352}, {0.68090344, 0.31804854, 0.85389896} }, { {0.51405964, 0.80209599, 0.52180655}, {0.64139231, 0.45604417, 0.72038693}, {0.56952489, 0.38557196, 0.45690327} }, { {0.05984255, 0.4023277 , 0.67928159}, {0.90443419, 0.8244877 , 0.44117897}, {0.42239515, 0.39793523, 0.58646196} }, { {0.61958306, 0.68355122, 0.45891009}, {0.68378874, 0.51346619, 0.6298741 }, {0.38542157, 0.51875832, 0.62662601} }, { {0.65439811, 0.53069018, 0.09855839}, {0.74635595, 0.53849551, 0.98221896}, {0.12130913, 0.65451548, 0.15978788} }, { {0.60492718, 0.13627062, 0.81201472}, {0.79337436, 0.62632629, 0.3899005 }, {0.06797229, 0.76755827, 0.43429217} }, { {0.54019544, 0.98085134, 0.83875517}, {0.64025688, 0.01326178, 0.3095098 }, {0.54613187, 0.1943059 , 0.44798822} }, { {0.04445216, 0.26118456, 0.05332922}, {0.64929854, 0.29243343, 0.99436014}, {0.75923343, 0.9199268 , 0.09167282} }, { {0.27052909, 0.49025286, 0.51769376}, {0.39076631, 0.73695414, 0.55064207}, {0.87983846, 0.46535012, 0.65481791} }, { {0.51109183, 0.37932067, 0.25915189}, {0.30505931, 0.89955053, 0.9133271 }, {0.80356951, 0.21662106, 0.31412402} }, { {0.0829945 , 0.74951041, 0.40556339}, {0.99592475, 0.65174516, 0.23361654}, {0.03529602, 0.11602755, 0.88370903} }, { {0.40483631, 0.92653125, 0.66487067}, {0.88368515, 0.37452408, 0.49166429}, {0.23496407, 0.03565885, 0.56232839} }, { {0.34351363, 0.35307573, 0.5505034 }, {0.89206617, 0.57913725, 0.81656158}, {0.29362619, 0.73480444, 0.17370431} }, { {0.70035022, 0.60877291, 0.64513862}, {0.69636546, 0.64717498, 0.76019362}, {0.15679513, 0.45886827, 0.0768233 } }, { {0.20703653, 0.81542342, 0.4314793 }, {0.4626067 , 0.53306498, 0.67665851}, {0.86205042, 0.22566872, 0.59662289} }, { {0.17411446, 0.87321991, 0.3842784 }, {0.74543378, 0.22325653, 0.14053908}, {0.64343814, 0.43317839, 0.9124576 } }, { {0.6211688 , 0.76780402, 0.81942615}, {0.06770901, 0.56630987, 0.52995963}, {0.78074631, 0.2996166 , 0.21836571} }, { {0.11194162, 0.02085178, 0.85598015}, {0.74771759, 0.99648219, 0.25943816}, {0.65451316, 0.08116926, 0.44720223} }, { {0.58771193, 0.72523405, 0.28447649}, {0.57813715, 0.19171352, 0.79861522}, {0.56599658, 0.66127263, 0.53036483} }, { {0.80893773, 0.28595511, 0.82066083}, {0.57169238, 0.0129177 , 0.33566536}, {0.1370678 , 0.95815594, 0.46243331} } } };// (1, 24, 3, 3) torch::Tensor poseRotation = torch::from_blob(poseRotation_.data(), {BATCH_SIZE, JOINT_NUM, 3, 3}); /**correct results * * - transformations: (1, 5, 4, 4) * [ * [ * [ 0.956278, 0.891879, 0.908546, -1.161506], * [ 0.038366, 0.417015, 0.14772 , 0.306849], * [ 0.28993 , 0.175071, 0.390798, 0.082879], * [ 0. , 0. , 0. , 1. ] * ], * [ * [ 1.393548, 1.288563, 1.551762, -1.983273], * [ 0.3757 , 0.310975, 0.300451, 0.069317], * [ 0.361526, 0.455201, 0.515535, -0.155379], * [ 0. , 0. , 0. , 1. ] * ], * [ * [ 1.50793 , 1.256797, 1.213523, -2.02222 ], * [ 0.406074, 0.205106, 0.23734 , 0.248555], * [ 0.456527, 0.346317, 0.458883, -0.208346], * [ 0. , 0. , 0. , 1. ] * ], * [ * [ 1.267205, 1.551624, 1.470787, -2.100431], * [ 0.419537, 0.390676, 0.292143, 0.10516 ], * [ 0.380306, 0.452636, 0.50812 , -0.233582], * [ 0. , 0. , 0. , 1. ] * ], * [ * [ 2.229255, 2.2815 , 2.300334, -3.430226], * [ 0.494933, 0.557158, 0.508993, -0.241092], * [ 0.740878, 0.695654, 0.728085, -0.608528], * [ 0. , 0. , 0. , 1. ] * ] * ] * * */ torch::Tensor transformations; try { WorldTransformation worldTransformation; worldTransformation.setDevice(m__device); worldTransformation.setKinematicTree(kineTree); worldTransformation.setJoint(joints); worldTransformation.setPoseRotation(poseRotation); worldTransformation.transform(); transformations = worldTransformation.getTransformation(); } catch(std::exception &e) { std::cerr << e.what() << std::endl; } torch::Tensor slice = TorchEx::indexing(transformations, torch::IntList(), torch::IntList({0, 5}), torch::IntList()); std::cout << "first five pose rotation: " << slice.sizes() << std::endl;// (1, 5, 4, 4) std::cout << slice << std::endl; std::cout << "PASS!" << std::endl; std::cout << "------------------------------------------------" << std::endl; BATCH_SIZE = batchSize; return; } /**linearBlendSkinning * * Brief * ---------- * * Test the <LinearBlendSkinng> module. * * Arguments * ---------- * * * Return * ---------- * * * Notes * ---------- * * We need to set both BATCH_SIZE and VERTEX_NUM in "definition/def.h" to * 1 to make it compatible with this test. * This kind of random number is generated by numpy with random seed 0. * */ void Tester::linearBlendSkinning() noexcept(true) { int batchSize = BATCH_SIZE; int vertexNum = VERTEX_NUM; BATCH_SIZE = 1; VERTEX_NUM = 1; std::cout << "---------- <LinearBlendSkinning> Test ----------" << std::endl; xt::xarray<float> weights_ { { 0.5488135 , 0.71518937, 0.60276338, 0.54488318, 0.4236548 , 0.64589411, 0.43758721, 0.891773 , 0.96366276, 0.38344152, 0.79172504, 0.52889492, 0.56804456, 0.92559664, 0.07103606, 0.0871293 , 0.0202184 , 0.83261985, 0.77815675, 0.87001215, 0.97861834, 0.79915856, 0.46147936, 0.78052918 } };// (1, 24) torch::Tensor weights = torch::from_blob(weights_.data(), {BATCH_SIZE, JOINT_NUM}).to(m__device); xt::xarray<float> restShape_ { { {0.11827443, 0.63992102, 0.14335329} } };// (1, 1, 3) torch::Tensor restShape = torch::from_blob(restShape_.data(), {BATCH_SIZE, VERTEX_NUM, 3}).to(m__device); xt::xarray<float> transformations_ { { { {0.94466892, 0.52184832, 0.41466194, 0.26455561}, {0.77423369, 0.45615033, 0.56843395, 0.0187898 }, {0.6176355 , 0.61209572, 0.616934 , 0.94374808}, {0.6818203 , 0.3595079 , 0.43703195, 0.6976312 } }, { {0.06022547, 0.66676672, 0.67063787, 0.21038256}, {0.1289263 , 0.31542835, 0.36371077, 0.57019677}, {0.43860151, 0.98837384, 0.10204481, 0.20887676}, {0.16130952, 0.65310833, 0.2532916 , 0.46631077} }, { {0.24442559, 0.15896958, 0.11037514, 0.65632959}, {0.13818295, 0.19658236, 0.36872517, 0.82099323}, {0.09710128, 0.83794491, 0.09609841, 0.97645947}, {0.4686512 , 0.97676109, 0.60484552, 0.73926358} }, { {0.03918779, 0.28280696, 0.12019656, 0.2961402 }, {0.11872772, 0.31798318, 0.41426299, 0.0641475 }, {0.69247212, 0.56660145, 0.26538949, 0.52324805}, {0.09394051, 0.5759465 , 0.9292962 , 0.31856895} }, { {0.66741038, 0.13179786, 0.7163272 , 0.28940609}, {0.18319136, 0.58651293, 0.02010755, 0.82894003}, {0.00469548, 0.67781654, 0.27000797, 0.73519402}, {0.96218855, 0.24875314, 0.57615733, 0.59204193} }, { {0.57225191, 0.22308163, 0.95274901, 0.44712538}, {0.84640867, 0.69947928, 0.29743695, 0.81379782}, {0.39650574, 0.8811032 , 0.58127287, 0.88173536}, {0.69253159, 0.72525428, 0.50132438, 0.95608363} }, { {0.6439902 , 0.42385505, 0.60639321, 0.0191932 }, {0.30157482, 0.66017354, 0.29007761, 0.61801543}, {0.4287687 , 0.13547406, 0.29828233, 0.56996491}, {0.59087276, 0.57432525, 0.65320082, 0.65210327} }, { {0.43141844, 0.8965466 , 0.36756187, 0.43586493}, {0.89192336, 0.80619399, 0.70388858, 0.10022689}, {0.91948261, 0.7142413 , 0.99884701, 0.1494483 }, {0.86812606, 0.16249293, 0.61555956, 0.12381998} }, { {0.84800823, 0.80731896, 0.56910074, 0.4071833 }, {0.069167 , 0.69742877, 0.45354268, 0.7220556 }, {0.86638233, 0.97552151, 0.85580334, 0.01171408}, {0.35997806, 0.72999056, 0.17162968, 0.52103661} }, { {0.05433799, 0.19999652, 0.01852179, 0.7936977 }, {0.22392469, 0.34535168, 0.92808129, 0.7044144 }, {0.03183893, 0.16469416, 0.6214784 , 0.57722859}, {0.23789282, 0.934214 , 0.61396596, 0.5356328 } }, { {0.58990998, 0.73012203, 0.311945 , 0.39822106}, {0.20984375, 0.18619301, 0.94437239, 0.7395508 }, {0.49045881, 0.22741463, 0.25435648, 0.05802916}, {0.43441663, 0.31179588, 0.69634349, 0.37775184} }, { {0.17960368, 0.02467873, 0.06724963, 0.67939277}, {0.45369684, 0.53657921, 0.89667129, 0.99033895}, {0.21689698, 0.6630782 , 0.26332238, 0.020651 }, {0.75837865, 0.32001715, 0.38346389, 0.58831711} }, { {0.83104846, 0.62898184, 0.87265066, 0.27354203}, {0.79804683, 0.18563594, 0.95279166, 0.68748828}, {0.21550768, 0.94737059, 0.73085581, 0.25394164}, {0.21331198, 0.51820071, 0.02566272, 0.20747008} }, { {0.42468547, 0.37416998, 0.46357542, 0.27762871}, {0.58678435, 0.86385561, 0.11753186, 0.51737911}, {0.13206811, 0.71685968, 0.3960597 , 0.56542131}, {0.18327984, 0.14484776, 0.48805628, 0.35561274} }, { {0.94043195, 0.76532525, 0.74866362, 0.90371974}, {0.08342244, 0.55219247, 0.58447607, 0.96193638}, {0.29214753, 0.24082878, 0.10029394, 0.01642963}, {0.92952932, 0.66991655, 0.78515291, 0.28173011} }, { {0.58641017, 0.06395527, 0.4856276 , 0.97749514}, {0.87650525, 0.33815895, 0.96157015, 0.23170163}, {0.94931882, 0.9413777 , 0.79920259, 0.63044794}, {0.87428797, 0.29302028, 0.84894356, 0.61787669} }, { {0.01323686, 0.34723352, 0.14814086, 0.98182939}, {0.47837031, 0.49739137, 0.63947252, 0.36858461}, {0.13690027, 0.82211773, 0.18984791, 0.51131898}, {0.22431703, 0.09784448, 0.86219152, 0.97291949} }, { {0.96083466, 0.9065555 , 0.77404733, 0.33314515}, {0.08110139, 0.40724117, 0.23223414, 0.13248763}, {0.05342718, 0.72559436, 0.01142746, 0.77058075}, {0.14694665, 0.07952208, 0.08960303, 0.67204781} }, { {0.24536721, 0.42053947, 0.55736879, 0.86055117}, {0.72704426, 0.27032791, 0.1314828 , 0.05537432}, {0.30159863, 0.26211815, 0.45614057, 0.68328134}, {0.69562545, 0.28351885, 0.37992696, 0.18115096} }, { {0.78854551, 0.05684808, 0.69699724, 0.7786954 }, {0.77740756, 0.25942256, 0.37381314, 0.58759964}, {0.2728219 , 0.3708528 , 0.19705428, 0.45985588}, {0.0446123 , 0.79979588, 0.07695645, 0.51883515} }, { {0.3068101 , 0.57754295, 0.95943334, 0.64557024}, {0.03536244, 0.43040244, 0.51001685, 0.53617749}, {0.68139251, 0.2775961 , 0.12886057, 0.39267568}, {0.95640572, 0.18713089, 0.90398395, 0.54380595} }, { {0.45691142, 0.88204141, 0.45860396, 0.72416764}, {0.39902532, 0.90404439, 0.69002502, 0.69962205}, {0.3277204 , 0.75677864, 0.63606106, 0.24002027}, {0.16053882, 0.79639147, 0.9591666 , 0.45813883} }, { {0.59098417, 0.85772264, 0.45722345, 0.95187448}, {0.57575116, 0.82076712, 0.90884372, 0.81552382}, {0.15941446, 0.62889844, 0.39843426, 0.06271295}, {0.42403225, 0.25868407, 0.84903831, 0.03330463} }, { {0.95898272, 0.35536885, 0.35670689, 0.0163285 }, {0.18523233, 0.4012595 , 0.92929142, 0.09961493}, {0.94530153, 0.86948853, 0.4541624 , 0.32670088}, {0.23274413, 0.61446471, 0.03307459, 0.01560606} } } };// (1, 24, 4, 4) torch::Tensor transformations = torch::from_blob(transformations_.data(), {BATCH_SIZE, JOINT_NUM, 4, 4}).to(m__device); /**correct results * * - vertices: (1, 1, 1) * [ * [ * [1.077754, 1.091551, 1.083642] * ] * ] * */ torch::Tensor vertices; try { LinearBlendSkinning linearBlendSkinning; linearBlendSkinning.setDevice(m__device); linearBlendSkinning.setWeight(weights); linearBlendSkinning.setRestShape(restShape); linearBlendSkinning.setTransformation(transformations); linearBlendSkinning.skinning(); vertices = linearBlendSkinning.getVertex(); } catch(std::exception &e) { std::cerr << e.what() << std::endl; } std::cout << "posed vertices: " << vertices.sizes() << std::endl;// (N, 6890, 3) std::cout << vertices << std::endl; std::cout << "PASS!" << std::endl; std::cout << "------------------------------------------------" << std::endl; BATCH_SIZE = batchSize; VERTEX_NUM = vertexNum; return; } //============================================================================= } // namespace smpl //=============================================================================
/* =================================================== * This is the main function to act as the interface * to the roman numeral converter * * Created on: Nov 6, 2016 * Author: Aisha Steege *===================================================*/ #include <iostream> #include <sstream> #include <string> #include "NumeralConverter.h" using namespace std; main() { NumeralConverter converter; std::string input ("0"); cout << "\nWelcome to the Roman Numeral Converter\n\n"; cout << "Would you like to convert \n (1) roman to arabic\n (2) arabic to roman \n "; int selection = 0; std::getline ( std::cin, input ); std::stringstream( input ) >> selection; if ( selection == 1) { cout << "Please enter a number (I-MMMCMXCIX) to be converted\n"; cout << "Roman : "; std::string roman; std::getline ( std::cin, roman ); cout << "Arabic: " << converter.RomanToArabic( roman ) << endl; } else if ( selection == 2 ) { cout << "Please enter a number (1-3999) to be converted\n"; cout << "Arabic: "; int arabic = 0; std::getline ( std::cin, input ); std::stringstream( input ) >> arabic; cout << "Roman : " << converter.ArabicToRoman( arabic ) << endl; } else { cout << "Im sorry, that selection was invalid"; } return 0; }
#include "rutil/Subsystem.hxx" using namespace resip; Subsystem Subsystem::APP("RESIP:APP"); Subsystem Subsystem::CONTENTS("RESIP:CONTENTS"); Subsystem Subsystem::DNS("RESIP:DNS"); Subsystem Subsystem::DUM("RESIP:DUM"); Subsystem Subsystem::PRESENCE("RESIP:PRESENCE"); Subsystem Subsystem::SDP("RESIP:SDP"); Subsystem Subsystem::SIP("RESIP"); // SIP Stack / Parser Subsystem Subsystem::TEST("RESIP:TEST"); Subsystem Subsystem::TRANSACTION("RESIP:TRANSACTION"); Subsystem Subsystem::TRANSPORT("RESIP:TRANSPORT"); Subsystem Subsystem::STATS("RESIP:STATS"); Subsystem Subsystem::REPRO("REPRO:APP"); Subsystem Subsystem::NONE("UNDEFINED"); const Data& Subsystem::getSubsystem() const { return mSubsystem; } EncodeStream& resip::operator<<(EncodeStream& strm, const Subsystem& ss) { strm << ss.mSubsystem; return strm; } /* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY 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. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "stdafx.h" #include "QTreeViewStateSaver.hxx" #include <qtreeview.h> #include <qscrollbar.h> #include <AzCore/RTTI/RTTI.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/UserSettings/UserSettings.h> namespace AzToolsFramework { class QTreeViewStateSaverData : public AZ::UserSettings { public: AZ_RTTI(QTreeViewStateSaverData, "{CA0FBE7A-232C-4595-9824-F4B5C50FA7B4}", AZ::UserSettings); AZ_CLASS_ALLOCATOR(QTreeViewStateSaverData, AZ::SystemAllocator, 0); AZStd::vector<AZStd::string> m_expandedElements; AZStd::vector<AZStd::string> m_selectedElements; AZStd::string m_currentElement; int m_horizScrollLast; int m_vertScrollLast; bool m_bApplyingState; QTreeViewStateSaverData() : m_horizScrollLast(0) , m_vertScrollLast(0) , m_bApplyingState(false) { } virtual ~QTreeViewStateSaverData() { } static void Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context); if (serialize) { serialize->Class<QTreeViewStateSaverData, AZ::UserSettings>() ->Version(1) ->Field("m_expandedElements", &QTreeViewStateSaverData::m_expandedElements) ->Field("m_selectedElements", &QTreeViewStateSaverData::m_selectedElements) ->Field("m_currentElement", &QTreeViewStateSaverData::m_currentElement) ->Field("m_horizScrollLast", &QTreeViewStateSaverData::m_horizScrollLast) ->Field("m_vertScrollLast", &QTreeViewStateSaverData::m_vertScrollLast); } } void RecurseCaptureSnapshot(const QModelIndex& idxParent, AZStd::string pathSoFar, QTreeView* treeView) { int elements = treeView->model()->rowCount(idxParent); for (int idx = 0; idx < elements; ++idx) { QModelIndex rowIdx = treeView->model()->index(idx, 0, idxParent); AZStd::string displayString(treeView->model()->data(rowIdx, Qt::DisplayRole).toString().toUtf8().data()); if (!displayString.empty()) { AZStd::string actualPath = displayString; if (!pathSoFar.empty()) { actualPath = pathSoFar + "/" + displayString; } if (treeView->isExpanded(rowIdx)) { m_expandedElements.push_back(actualPath); } if (treeView->selectionModel() && treeView->selectionModel()->isSelected(rowIdx)) { m_selectedElements.push_back(actualPath); } RecurseCaptureSnapshot(rowIdx, actualPath, treeView); } } } void CaptureSnapshot(QTreeView* treeView) { Q_ASSERT(treeView && treeView->model()); m_selectedElements.clear(); m_expandedElements.clear(); RecurseCaptureSnapshot(QModelIndex(), AZStd::string(), treeView); _q_CurrentChanged(treeView->currentIndex(), QModelIndex()); QScrollBar* pScroll = treeView->verticalScrollBar(); if (pScroll) { m_vertScrollLast = pScroll->value(); } else { m_vertScrollLast = 0; } pScroll = treeView->horizontalScrollBar(); if (pScroll) { m_horizScrollLast = pScroll->value(); } else { m_horizScrollLast = 0; } } static void ExpandRow(QTreeView* treeView, const QModelIndex& rowIdx) { if (!treeView->isExpanded(rowIdx)) { treeView->expand(rowIdx); } } static void SelectRow(QTreeView* treeView, const QModelIndex& rowIdx) { if (treeView->selectionModel() && !treeView->isExpanded(rowIdx.parent())) { treeView->selectionModel()->select(rowIdx, QItemSelectionModel::Select); } } static void SetCurrentRow(QTreeView* treeView, const QModelIndex& rowIdx) { if (treeView->isExpanded(rowIdx.parent())) { treeView->setCurrentIndex(rowIdx); } } void ApplyRowOperation(QTreeView* treeView, const QModelIndex& idxParent, AZStd::string pathSoFar, const AZStd::function<void(QTreeView* treeView, const QModelIndex&)>& rowOperation) { AZStd::size_t pos = pathSoFar.find_first_of('/'); AZStd::string name = pathSoFar.substr(0, pos); int elements = treeView->model()->rowCount(idxParent); for (int idx = 0; idx < elements; ++idx) { QModelIndex rowIdx = treeView->model()->index(idx, 0, idxParent); AZStd::string displayString(treeView->model()->data(rowIdx, Qt::DisplayRole).toString().toUtf8().data()); if (name == displayString) { if (pos != AZStd::string::npos) { AZStd::string remaining = pathSoFar.substr(pos + 1); ApplyRowOperation(treeView, rowIdx, remaining, rowOperation); } else { rowOperation(treeView, rowIdx); } return; } } } void ApplySnapshot(QTreeView* treeView, const AZStd::function<bool(const QModelIndex&)>& /* expandedFunction */) { Q_ASSERT(treeView && treeView->model()); m_bApplyingState = true; // Reset the view to the 'default'/fully negative state then we can apply our positive transforms. treeView->collapseAll(); treeView->clearSelection(); //RecurseApplySnapshot(QModelIndex(), "", treeView, expandedFunction); for (auto& expanded : m_expandedElements) { ApplyRowOperation(treeView, QModelIndex(), expanded, &QTreeViewStateSaverData::ExpandRow); } for (auto& selected : m_selectedElements) { ApplyRowOperation(treeView, QModelIndex(), selected, &QTreeViewStateSaverData::SelectRow); } if (!m_currentElement.empty()) { ApplyRowOperation(treeView, QModelIndex(), m_currentElement, &QTreeViewStateSaverData::SetCurrentRow); } // force a refresh of the scroll bar: treeView->scrollToBottom(); treeView->scrollToTop(); QScrollBar* pScroll = treeView->verticalScrollBar(); if (pScroll) { pScroll->setValue(m_vertScrollLast); } pScroll = treeView->horizontalScrollBar(); if (pScroll) { pScroll->setValue(m_horizScrollLast); } m_bApplyingState = false; } QString GenerateIdentifier(const QModelIndex& modelIndex) { QString dataAtThatRow = modelIndex.data(Qt::DisplayRole).toString(); QModelIndex idx = modelIndex.parent(); while (idx.isValid()) { dataAtThatRow = idx.data(Qt::DisplayRole).toString() + "/" + dataAtThatRow; QModelIndex newIdx = idx.parent(); // its not safe to iterate on itself! idx = newIdx; } return dataAtThatRow; } void _q_VerticalScrollChanged(int newValue) { if (m_bApplyingState) { return; } m_vertScrollLast = newValue; } void _q_HorizontalScrollChanged(int newValue) { if (m_bApplyingState) { return; } m_horizScrollLast = newValue; } void _q_ModelReset() { if (m_bApplyingState) { return; } m_selectedElements.clear(); } void _q_CurrentChanged(const QModelIndex& current, const QModelIndex&) { if (m_bApplyingState) { return; } m_currentElement = ""; if (current != QModelIndex()) { QString id = GenerateIdentifier(current); if (!id.isEmpty()) { m_currentElement = id.toUtf8().data(); } } } void _q_selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { if (m_bApplyingState) { return; } QModelIndexList allsel = selected.indexes(); for (auto it = allsel.begin(); it != allsel.end(); ++it) { QModelIndex& targ = *it; QString id = GenerateIdentifier(targ); if (!id.isEmpty()) { m_selectedElements.push_back(id.toUtf8().data()); } } allsel = deselected.indexes(); for (auto it = allsel.begin(); it != allsel.end(); ++it) { QModelIndex& targ = *it; QString id = GenerateIdentifier(targ); auto itToDelete = AZStd::find(m_selectedElements.begin(), m_selectedElements.end(), id.toUtf8().data()); if (itToDelete != m_selectedElements.end()) { m_selectedElements.erase(itToDelete); } } } void _q_RowExpanded(const QModelIndex& modelIndex) { if (m_bApplyingState) { return; } QString id = GenerateIdentifier(modelIndex); m_expandedElements.push_back(id.toUtf8().data()); } void _q_RowCollapsed(const QModelIndex& modelIndex) { if (m_bApplyingState) { return; } QString id = GenerateIdentifier(modelIndex); auto itToDelete = AZStd::find(m_expandedElements.begin(), m_expandedElements.end(), id.toUtf8().data()); if (itToDelete != m_expandedElements.end()) { m_expandedElements.erase(itToDelete); } } }; QTreeViewStateSaver::QTreeViewStateSaver(AZ::u32 storageID, QObject* pParent) : QObject(pParent) , m_data(AZ::UserSettings::CreateFind<QTreeViewStateSaverData>(storageID, AZ::UserSettings::CT_LOCAL)) , m_expandedFunction(&QTreeViewStateSaver::DefaultExpandedFunction) { } void QTreeViewStateSaver::Attach(QTreeView* attach, QAbstractItemModel* dataModel, QItemSelectionModel* selectionModel) { // these all have to match by the time we attach Q_ASSERT(attach); Q_ASSERT(attach->model() == dataModel); Q_ASSERT(attach->selectionModel() == selectionModel); if (attach != m_attachedTree) { DetachTreeView(); AttachTreeView(attach); } if (selectionModel != m_selectionModel) { DetachSelectionModel(); AttachSelectionModel(selectionModel); } if (dataModel != m_dataModel) { DetachDataModel(); AttachDataModel(dataModel); } } void QTreeViewStateSaver::Detach() { CaptureSnapshot(); bool success = true; success = success && DetachTreeView(); success = success && DetachSelectionModel(); success = success && DetachDataModel(); Q_ASSERT(success); } bool QTreeViewStateSaver::AttachTreeView(QTreeView* attach) { m_attachedTree = attach; bool success = true; success = success && connect(m_attachedTree, &QTreeView::expanded, this, &QTreeViewStateSaver::RowExpanded); success = success && connect(m_attachedTree, &QTreeView::collapsed, this, &QTreeViewStateSaver::RowCollapsed); if (m_attachedTree->horizontalScrollBar()) { success = success && connect(m_attachedTree->horizontalScrollBar(), &QScrollBar::valueChanged, this, &QTreeViewStateSaver::HorizontalScrollChanged); } if (m_attachedTree->verticalScrollBar()) { success = success && connect(m_attachedTree->verticalScrollBar(), &QScrollBar::valueChanged, this, &QTreeViewStateSaver::VerticalScrollChanged); } return success; } bool QTreeViewStateSaver::DetachTreeView() { bool success = true; if (m_attachedTree) { success = success && disconnect(m_attachedTree, &QTreeView::expanded, this, &QTreeViewStateSaver::RowExpanded); success = success && disconnect(m_attachedTree, &QTreeView::collapsed, this, &QTreeViewStateSaver::RowCollapsed); if (m_attachedTree->horizontalScrollBar()) { success = success && disconnect(m_attachedTree->horizontalScrollBar(), &QScrollBar::valueChanged, this, &QTreeViewStateSaver::HorizontalScrollChanged); } if (m_attachedTree->verticalScrollBar()) { success = success && disconnect(m_attachedTree->verticalScrollBar(), &QScrollBar::valueChanged, this, &QTreeViewStateSaver::VerticalScrollChanged); } m_attachedTree = nullptr; } return success; } bool QTreeViewStateSaver::AttachDataModel(QAbstractItemModel* dataModel) { bool success = true; if (dataModel) { success = success && connect(dataModel, &QAbstractItemModel::modelReset, this, &QTreeViewStateSaver::ModelReset); } m_dataModel = dataModel; return success; } bool QTreeViewStateSaver::DetachDataModel() { bool success = true; if (m_dataModel) { success = success && disconnect(m_dataModel, &QAbstractItemModel::modelReset, this, &QTreeViewStateSaver::ModelReset); m_dataModel = nullptr; } return success; } bool QTreeViewStateSaver::AttachSelectionModel(QItemSelectionModel* selectionModel) { bool success = true; if (selectionModel) { success = success && connect(selectionModel, &QItemSelectionModel::selectionChanged, this, &QTreeViewStateSaver::SelectionChanged); success = success && connect(selectionModel, &QItemSelectionModel::currentChanged, this, &QTreeViewStateSaver::CurrentChanged); } m_selectionModel = selectionModel; return success; } bool QTreeViewStateSaver::DetachSelectionModel() { bool success = true; if (m_selectionModel) { success = success && disconnect(m_selectionModel, &QItemSelectionModel::selectionChanged, this, &QTreeViewStateSaver::SelectionChanged); success = success && disconnect(m_selectionModel, &QItemSelectionModel::currentChanged, this, &QTreeViewStateSaver::CurrentChanged); m_selectionModel = nullptr; } return true; } QTreeViewStateSaver::~QTreeViewStateSaver() { // We do this on close, if we can, to cover the case of the expandAll signal not getting emitted. // Has to be guarded, because the tree view's model is deleted but the pointer is not reset to nullptr CaptureSnapshot(); } void QTreeViewStateSaver::WriteStateTo(QSet<QString>& target) { target.clear(); for (auto& str : m_data->m_expandedElements) { target.insert(str.c_str()); } } void QTreeViewStateSaver::ReadStateFrom(QSet<QString>& source) { m_data->m_expandedElements.clear(); for (auto& qstr : source) { m_data->m_expandedElements.push_back(qstr.toUtf8().data()); } ApplySnapshot(); } void QTreeViewStateSaver::CaptureSnapshot() const { if (m_attachedTree && m_dataModel) { m_data->CaptureSnapshot(m_attachedTree); } } void QTreeViewStateSaver::ApplySnapshot() const { if (m_attachedTree) { m_data->ApplySnapshot(m_attachedTree, m_expandedFunction); } } void QTreeViewStateSaver::SetExpandedFunction(AZStd::function<bool(const QModelIndex&)> expandedFunction) { m_expandedFunction = expandedFunction; } void QTreeViewStateSaver::Reflect(AZ::ReflectContext* context) { QTreeViewStateSaverData::Reflect(context); } void QTreeViewStateSaver::VerticalScrollChanged(int newValue) { m_data->_q_VerticalScrollChanged(newValue); } void QTreeViewStateSaver::HorizontalScrollChanged(int newValue) { m_data->_q_HorizontalScrollChanged(newValue); } void QTreeViewStateSaver::ModelReset() { m_data->_q_ModelReset(); } void QTreeViewStateSaver::CurrentChanged(const QModelIndex& current, const QModelIndex& newCurrent) { m_data->_q_CurrentChanged(current, newCurrent); } void QTreeViewStateSaver::SelectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { m_data->_q_selectionChanged(selected, deselected); } void QTreeViewStateSaver::RowExpanded(const QModelIndex& modelIndex) { m_data->_q_RowExpanded(modelIndex); } void QTreeViewStateSaver::RowCollapsed(const QModelIndex& modelIndex) { m_data->_q_RowCollapsed(modelIndex); } QTreeViewWithStateSaving::QTreeViewWithStateSaving(QWidget* parent) : QTreeView(parent) { } QTreeViewWithStateSaving::~QTreeViewWithStateSaving() { if (m_treeStateSaver) { // called because Qt doesn't emit a signal on expandAll m_treeStateSaver->CaptureSnapshot(); } } void QTreeViewWithStateSaving::InitializeTreeViewSaving(AZ::u32 storageID) { SetupSaver(new QTreeViewStateSaver(storageID, this)); } void QTreeViewWithStateSaving::setModel(QAbstractItemModel* newModel) { QTreeView::setModel(newModel); if (m_treeStateSaver) { // reattach, so that the new model can be connected to by the state saver m_treeStateSaver->Attach(this, model(), selectionModel()); } } void QTreeViewWithStateSaving::setSelectionModel(QItemSelectionModel* newSelectionModel) { QTreeView::setSelectionModel(newSelectionModel); if (m_treeStateSaver) { // reattach, so that the new selection model can be connected to by the state saver m_treeStateSaver->Attach(this, model(), selectionModel()); } } void QTreeViewWithStateSaving::SetupSaver(QTreeViewStateSaver* stateSaver) { Q_ASSERT(!m_treeStateSaver); // can't call InitializeSaving twice! m_treeStateSaver = stateSaver; m_treeStateSaver->Attach(this, model(), selectionModel()); } void QTreeViewWithStateSaving::CaptureTreeViewSnapshot() const { Q_ASSERT(m_treeStateSaver); m_treeStateSaver->CaptureSnapshot(); } void QTreeViewWithStateSaving::ApplyTreeViewSnapshot() const { Q_ASSERT(m_treeStateSaver); m_treeStateSaver->ApplySnapshot(); } void QTreeViewWithStateSaving::WriteTreeViewStateTo(QSet<QString>& target) { Q_ASSERT(m_treeStateSaver); m_treeStateSaver->WriteStateTo(target); } void QTreeViewWithStateSaving::ReadTreeViewStateFrom(QSet<QString>& source) { Q_ASSERT(m_treeStateSaver); m_treeStateSaver->ReadStateFrom(source); } void QTreeViewWithStateSaving::SetTreeViewExpandedFunction(AZStd::function<bool(const QModelIndex&)> expandedFunction) { Q_ASSERT(m_treeStateSaver); m_treeStateSaver->SetExpandedFunction(expandedFunction); } void QTreeViewWithStateSaving::PauseTreeViewSaving() { Q_ASSERT(m_treeStateSaver); m_treeStateSaver->Detach(); } void QTreeViewWithStateSaving::UnpauseTreeViewSaving() { Q_ASSERT(m_treeStateSaver); m_treeStateSaver->Attach(this, model(), selectionModel()); } } #include <UI/UICore/QTreeViewStateSaver.moc>
#include <iostream> #include "../annoy/src/kissrandom.h" #include "../annoy/src/annoylib.h" #include <cstdio> #include <cstdlib> #include <cmath> #include <map> #define N 555555 using namespace std; std::vector<int> knn_id[N]; std::vector<double> knn_dis[N]; int n_pc, n_candidates; double average_nn_dis = 0; map<pair<int, int>, int> edge_cnt; int last_visit_idx[N * 10]; int visit_idx = 0; AnnoyIndex<int, double, Euclidean, Kiss32Random> pc_knn = AnnoyIndex<int, double, Euclidean, Kiss32Random>(3); struct Point { double x, y, z; Point() {}; Point (double _x, double _y, double _z) { x = _x; y = _y; z = _z; }; Point operator - (const Point& v) const { return Point(x - v.x, y - v.y, z - v.z);} Point operator + (const Point& v) const { return Point(x + v.x, y + v.y, z + v.z);} Point operator * (const double t) const { return Point(x * t, y * t, z * t);} double length() { return sqrt(x * x + y * y + z * z);} void normalize() { double l = length(); x /= l; y /= l; z /= l;} double dot(const Point& v) const { return x * v.x + y * v.y + z * v.z;} Point cross(const Point& v) const { return Point( y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x);} }pc[N]; struct Face { int a, b, c; int label, id; bool in_final_mesh; double l; Face() {}; Face (int _a, int _b, int _c) { a = _a; b = _b; c = _c; }; bool operator < (const Face& rhs) const { if (label == rhs.label) return l < rhs.l; return label < rhs.label; }; } candidates[N * 10]; vector<Face>vertex_faces[N]; bool check_inside(Point A, Point B, Point P, Point Q) { // check whether triangle ABQ contain triangle ABP Point normal = (Q - A).cross(B - A); normal.normalize(); double d = normal.dot(P - A); if (fabs(d) > average_nn_dis * 0.3) return false; P = P - (normal * d); double sABP = (P - A).cross(B - A).length(); double sAQP = (P - A).cross(Q - A).length(); double sBQP = (Q - B).cross(P - B).length(); double sABQ = (Q - A).cross(B - A).length(); if (fabs(sABP + sAQP + sBQP - sABQ) < 1e-5) return true; return false; } bool seg_seg_intersect(Point A, Point B, Point C, Point D, Point P, Point Q) { if (((A - C).length() < 1e-5 && (B - D).length() < 1e-5) || ((A - D).length() < 1e-5 && (B - C).length() < 1e-5)) { if (check_inside(A, B, P, Q)) return true; if (check_inside(A, B, Q, P)) return true; } // check whether segment AB and segment CD intersect Point norm = (B - A).cross(D - C); if (norm.length() < 1e-5) return false; norm.normalize(); double d = norm.dot(C - A); if (fabs(d) > average_nn_dis * 0.3) return false; if (fabs(d) > 1e-9) { A = A + norm * d; B = B + norm * d; } if ((A - C).length() < 1e-5 || (A - D).length() < 1e-5 || (B - C).length() < 1e-5 || (B - D).length() < 1e-5) return false; // area ratio Point V1 = (B - A); V1.normalize(); Point V2 = (D - C); V2.normalize(); Point V1V2 = V1.cross(V2); Point R1R2 = (C - A); double t1, t2; if (fabs(V1V2.x) > fabs(V1V2.y) && fabs(V1V2.x) > fabs(V1V2.z)) { t1 = (R1R2.cross(V2).x)/(V1V2.x); t2 = (R1R2.cross(V1).x)/(V1V2.x); } else if (fabs(V1V2.y) > fabs(V1V2.x) && fabs(V1V2.y) > fabs(V1V2.z)) { t1 = (R1R2.cross(V2).y)/(V1V2.y); t2 = (R1R2.cross(V1).y)/(V1V2.y); } else { t1 = (R1R2.cross(V2).z)/(V1V2.z); t2 = (R1R2.cross(V1).z)/(V1V2.z); } if (t1 < 1e-5 || t1 > (A - B).length() - 1e-5) return false; if (t2 < 1e-5 || t2 > (C - D).length() - 1e-5) return false; return true; } bool tri_tri_intersect(Point A, Point B, Point C, Point P, Point Q, Point R) { if (seg_seg_intersect(A, B, P, Q, C, R)) return true; if (seg_seg_intersect(A, B, Q, R, C, P)) return true; if (seg_seg_intersect(A, B, P, R, C, Q)) return true; if (seg_seg_intersect(B, C, P, Q, A, R)) return true; if (seg_seg_intersect(B, C, Q, R, A, P)) return true; if (seg_seg_intersect(B, C, P, R, A, Q)) return true; if (seg_seg_intersect(A, C, P, Q, B, R)) return true; if (seg_seg_intersect(A, C, Q, R, B, P)) return true; if (seg_seg_intersect(A, C, P, R, B, Q)) return true; return false; } bool tri_mesh_intersect(int a, int b, int c) { visit_idx++; int ver[3] = {a, b, c}; for (int i = 0; i < 3; i++) for (int j = 0; j < 5; j++) for (auto face : vertex_faces[knn_id[ver[i]][j]]) { if (last_visit_idx[face.id] == visit_idx) continue; last_visit_idx[face.id] = visit_idx; if (tri_tri_intersect(pc[a], pc[b], pc[c], pc[face.a], pc[face.b], pc[face.c])) return true; } return false; } void edge_add(int a, int b) { if (a > b) swap(a, b); edge_cnt[make_pair(a, b)] += 1; return ; } bool edge_check(int a, int b) { if (a > b) swap(a, b); return edge_cnt[make_pair(a, b)] < 2; } int main(int argc, char ** argv) { string input_file = argv[1]; string output_file = argv[2]; freopen(input_file.c_str(), "r", stdin); scanf("%d", &n_pc); for (int i = 0; i < n_pc; i++) { double vec[3]; scanf("%lf%lf%lf", &vec[0], &vec[1], &vec[2]); pc[i] = Point(vec[0], vec[1], vec[2]); pc_knn.add_item(i, vec); } pc_knn.build(10); int K = 80; for (int i = 0; i < n_pc; i++) { pc_knn.get_nns_by_item(i, K + 1, -1, &knn_id[i], &knn_dis[i]); average_nn_dis += knn_dis[i][1]; for (int j = 1; j < K; j++) for (int k = j + 1; k < K; k++) { Point A = pc[i]; Point B = pc[knn_id[i][j]]; Point C = pc[knn_id[i][k]]; if (fabs((B - C).length() - (A - B).length() - (A - C).length()) < 1e-3) { edge_cnt[make_pair(knn_id[i][j], knn_id[i][k])] = 100; edge_cnt[make_pair(knn_id[i][k], knn_id[i][j])] = 100; } } } average_nn_dis /= n_pc; scanf("%d", &n_candidates); for (int i = 0; i < n_candidates; i++) { int a, b, c, label; scanf("%d %d %d %d", &a, &b, &c, &label); int ver[3] = {a, b, c}; sort(&ver[0], &ver[3]); a = ver[0]; b = ver[1]; c = ver[2]; candidates[i] = Face(a, b, c); candidates[i].label = label; candidates[i].in_final_mesh = false; Point A = pc[a]; Point B = pc[b]; Point C = pc[c]; double l1 = (A - B).length(); double l2 = (A - C).length(); double l3 = (B - C).length(); candidates[i].l = max(max(l1, l2), l3); candidates[i].id = i; Point AC = C - A; AC.normalize(); Point AB = B - A; AB.normalize(); if (AC.cross(AB).length() < 1e-3) candidates[i].label = 0; } sort(&candidates[0], &candidates[n_candidates]); int n_faces = 0; for (int i = 0; i < n_candidates; i++) { Face face = candidates[i]; if (face.label == 0) continue; int a = face.a, b = face.b, c = face.c; if (!(edge_check(a, b) && edge_check(a, c) && edge_check(b, c))) continue; if (tri_mesh_intersect(a, b, c)) continue; candidates[i].in_final_mesh = true; n_faces++; vertex_faces[a].push_back(face); vertex_faces[b].push_back(face); vertex_faces[c].push_back(face); edge_add(a, b); edge_add(a, c); edge_add(b, c); } freopen(output_file.c_str(), "w", stdout); printf("ply\n"); printf("format ascii 1.0\n"); printf("element vertex %d\n", n_pc); printf("property float x\n"); printf("property float y\n"); printf("property float z\n"); printf("element face %d\n", n_faces); printf("property list uchar int vertex_indices\n"); printf("end_header\n"); for (int i = 0; i < n_pc; i++) printf("%lf %lf %lf\n", pc[i].x, pc[i].y, pc[i].z); for (int i = 0; i < n_candidates; i++) if (candidates[i].in_final_mesh) printf("3 %d %d %d\n", candidates[i].a, candidates[i].b, candidates[i].c); return 0; }
/* * Copyright (C) 2005, 2006, 2012 Apple Inc. All rights reserved. * Copyright (C) 2006 Alexey Proskuryakov * * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "Font.h" #include <CoreText/CoreText.h> #include <pal/spi/cocoa/CoreTextSPI.h> namespace WebCore { RetainPtr<CFDictionaryRef> Font::getCFStringAttributes(bool enableKerning, FontOrientation orientation, const AtomString& locale) const { CFTypeRef keys[5]; CFTypeRef values[5]; keys[0] = kCTFontAttributeName; values[0] = platformData().ctFont(); size_t count = 1; #if USE(CTFONTSHAPEGLYPHS) RetainPtr<CFStringRef> localeString; if (!locale.isEmpty()) { localeString = locale.string().createCFString(); keys[count] = kCTLanguageAttributeName; values[count] = localeString.get(); ++count; } #else UNUSED_PARAM(locale); #endif static CTParagraphStyleRef paragraphStyle = [] { auto paragraphStyle = CTParagraphStyleCreate(nullptr, 0); CTParagraphStyleSetCompositionLanguage(paragraphStyle, kCTCompositionLanguageNone); return paragraphStyle; }(); keys[count] = kCTParagraphStyleAttributeName; values[count] = paragraphStyle; ++count; if (!enableKerning) { const float zero = 0; static CFNumberRef zeroKerningValue = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &zero); keys[count] = kCTKernAttributeName; values[count] = zeroKerningValue; ++count; } if (orientation == FontOrientation::Vertical) { keys[count] = kCTVerticalFormsAttributeName; values[count] = kCFBooleanTrue; ++count; } ASSERT(count <= WTF_ARRAY_LENGTH(keys)); return adoptCF(CFDictionaryCreate(kCFAllocatorDefault, keys, values, count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); } } // namespace WebCore
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved. #include <algorithm> #include <cassert> #include <iostream> #include <limits> #include <random> #include <vector> using std::cout; using std::default_random_engine; using std::endl; using std::max; using std::min; using std::numeric_limits; using std::random_device; using std::uniform_int_distribution; using std::uniform_real_distribution; using std::vector; // @include double BuyAndSellStockTwice(const vector<double>& prices) { double max_total_profit = 0; vector<double> first_buy_sell_profits(prices.size(), 0); double min_price_so_far = numeric_limits<double>::max(); // Forward phase. For each day, we record maximum profit if we // sell on that day. for (int i = 0; i < prices.size(); ++i) { min_price_so_far = min(min_price_so_far, prices[i]); max_total_profit = max(max_total_profit, prices[i] - min_price_so_far); first_buy_sell_profits[i] = max_total_profit; } // Backward phase. For each day, find the maximum profit if we make // the second buy on that day. double max_price_so_far = numeric_limits<double>::min(); for (int i = prices.size() - 1; i > 0; --i) { max_price_so_far = max(max_price_so_far, prices[i]); max_total_profit = max(max_total_profit, max_price_so_far - prices[i] + first_buy_sell_profits[i - 1]); } return max_total_profit; } // @exclude // O(n^4) checking answer. double CheckAns(const vector<double>& A) { double cap = 0; for (int i = 1; i < A.size(); ++i) { for (int j = 0; j < i; ++j) { cap = max(cap, A[i] - A[j]); } } for (int a = 0; a < A.size(); ++a) { for (int b = a + 1; b < A.size(); ++b) { double temp = A[b] - A[a]; for (int c = b + 1; c < A.size(); ++c) { for (int d = c + 1; d < A.size(); ++d) { double profit = A[d] - A[c] + temp; cap = max(cap, profit); } } } } return cap; } int main(int argc, char* argv[]) { default_random_engine gen((random_device())()); for (int times = 0; times < 1000; ++times) { int n; if (argc == 2) { n = atoi(argv[1]); } else { uniform_int_distribution<int> dis(1, 100); n = dis(gen); } vector<double> A; uniform_real_distribution<double> dis(0.0, 10000.0); for (int i = 0; i < n; ++i) { A.emplace_back(dis(gen)); } cout << "n = " << n << endl; assert(CheckAns(A) == BuyAndSellStockTwice(A)); } return 0; }
//$Id: RunSimulator.hpp 1398 2011-04-21 20:39:37Z $ //------------------------------------------------------------------------------ // ClassName //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2020 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 NNG06CA54C // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2009/06/21 // /** * Mission Control Sequence Command that runs data simulation * * This command uses a simulator to generate simulated measurement data that can * be processed by GMAT's estimators. The Simulator class contains the elements * that actually manage the simulation process, including a finite state machine * that walks the system through the process of data simulation. * * Simulated data generated by this command is generated through propagation * using a pre-configured propagator. The ODEModel used in this process is set * prior to execution of the command. That means that the simulated data * generated in this process does not include any transient forces. */ //------------------------------------------------------------------------------ #ifndef RunSimulator_hpp #define RunSimulator_hpp #include "RunSolver.hpp" #include "PropSetup.hpp" #include "Simulator.hpp" #include "EventManager.hpp" class ESTIMATION_API RunSimulator : public RunSolver { public: RunSimulator(); virtual ~RunSimulator(); RunSimulator(const RunSimulator& rs); RunSimulator& operator=(const RunSimulator& rs); virtual GmatBase* Clone() const; virtual std::string GetRefObjectName(const UnsignedInt type) const; virtual bool SetRefObjectName(const UnsignedInt type, const std::string &name); virtual bool RenameRefObject(const UnsignedInt type, const std::string &oldName, const std::string &newName); virtual const std::string& GetGeneratingString(Gmat::WriteMode mode, const std::string &prefix, const std::string &useName); virtual bool Initialize(); virtual bool Execute(); virtual void RunComplete(); virtual bool TakeAction(const std::string &action, const std::string &actionData = ""); virtual GmatCommand* GetNext(); virtual bool HasLocalClones(); virtual void UpdateClonedObject(GmatBase *obj); protected: /// The simulator that drives this process Simulator *theSimulator; /// Flag indicating if command execution is started bool commandRunning; // /// Flag indicating if propagation is running an needs reentrance // bool commandPropagating; /// Flag indicating if command execution is done bool commandComplete; /// Flag indicating is the buffers have been filled bool bufferFilled; /// List of Event objects to process ObjectArray eventList; /// The current Event that is getting processed Event *currentEvent; /// Index of the current Event in the eventList UnsignedInt eventIndex; /// Flag indicating when all Events have been processed bool eventProcessComplete; /// The event manager EventManager *eventMan; /// Flag used to turn on STM propagation bool includeSTMPropagation; /// Time different used while running the event code Real dt; void PrepareToSimulate(); void Propagate(); void Calculate(); void LocateEvent(); void Simulate(); void Finalize(); void SetPropagationProperties(PropagationStateManager *psm); }; #endif /* RunSimulator_hpp */
#include <fstream> #include <streambuf> #include "Fireworks/Geometry/interface/FWRecoGeometryESProducer.h" #include "Fireworks/Geometry/interface/FWRecoGeometry.h" #include "Fireworks/Geometry/interface/FWTGeoRecoGeometry.h" #include "Fireworks/Geometry/interface/FWRecoGeometryRecord.h" #include "DataFormats/GeometrySurface/interface/RectangularPlaneBounds.h" #include "DataFormats/GeometrySurface/interface/TrapezoidalPlaneBounds.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "Geometry/CommonDetUnit/interface/GlobalTrackingGeometry.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/HGCalGeometry/interface/HGCalGeometry.h" #include "Geometry/HGCalGeometry/interface/FastTimeGeometry.h" #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h" #include "Geometry/CSCGeometry/interface/CSCGeometry.h" #include "Geometry/DTGeometry/interface/DTGeometry.h" #include "Geometry/CSCGeometry/interface/CSCChamber.h" #include "Geometry/CSCGeometry/interface/CSCLayer.h" #include "Geometry/DTGeometry/interface/DTChamber.h" #include "Geometry/DTGeometry/interface/DTLayer.h" #include "Geometry/RPCGeometry/interface/RPCGeometry.h" #include "Geometry/GEMGeometry/interface/GEMGeometry.h" #include "Geometry/GEMGeometry/interface/ME0Geometry.h" #include "Geometry/Records/interface/CaloGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/TrackerGeometryBuilder/interface/RectangularPixelTopology.h" #include "Geometry/CommonDetUnit/interface/PixelGeomDetUnit.h" #include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h" #include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetType.h" #include "Geometry/CommonTopologies/interface/PixelTopology.h" #include "Geometry/CommonTopologies/interface/StripTopology.h" #include "Geometry/CommonTopologies/interface/RectangularStripTopology.h" #include "Geometry/CommonTopologies/interface/TrapezoidalStripTopology.h" #include "Geometry/CommonTopologies/interface/GEMStripTopology.h" #include "TNamed.h" #include "FWCore/ParameterSet/interface/FileInPath.h" void FWRecoGeometryESProducer::ADD_PIXEL_TOPOLOGY(unsigned int rawid, const GeomDet* detUnit, FWRecoGeometry& fwRecoGeometry) { const PixelGeomDetUnit* det = dynamic_cast<const PixelGeomDetUnit*>(detUnit); if (det) { const PixelTopology* topo = &det->specificTopology(); std::pair<float, float> pitch = topo->pitch(); fwRecoGeometry.idToName[rawid].topology[0] = pitch.first; fwRecoGeometry.idToName[rawid].topology[1] = pitch.second; fwRecoGeometry.idToName[rawid].topology[2] = topo->localX(0.f); // offsetX fwRecoGeometry.idToName[rawid].topology[3] = topo->localY(0.f); // offsetY // big pixels layout fwRecoGeometry.idToName[rawid].topology[4] = topo->isItBigPixelInX(80) ? 0 : 1; } } using Phase2TrackerGeomDetUnit = PixelGeomDetUnit; using Phase2TrackerTopology = PixelTopology; #define ADD_SISTRIP_TOPOLOGY(rawid, detUnit) \ const StripGeomDetUnit* det = dynamic_cast<const StripGeomDetUnit*>(detUnit); \ if (det) { \ if (const StripTopology* topo = dynamic_cast<const StripTopology*>(&det->specificTopology())) { \ fwRecoGeometry.idToName[rawid].topology[0] = 0; \ fwRecoGeometry.idToName[rawid].topology[1] = topo->nstrips(); \ fwRecoGeometry.idToName[rawid].topology[2] = topo->stripLength(); \ } else if (const RadialStripTopology* rtop = \ dynamic_cast<const RadialStripTopology*>(&(det->specificType().specificTopology()))) { \ fwRecoGeometry.idToName[rawid].topology[0] = 1; \ fwRecoGeometry.idToName[rawid].topology[3] = rtop->yAxisOrientation(); \ fwRecoGeometry.idToName[rawid].topology[4] = rtop->originToIntersection(); \ fwRecoGeometry.idToName[rawid].topology[5] = rtop->phiOfOneEdge(); \ fwRecoGeometry.idToName[rawid].topology[6] = rtop->angularWidth(); \ } else if (dynamic_cast<const RectangularStripTopology*>(&(det->specificType().specificTopology()))) { \ fwRecoGeometry.idToName[rawid].topology[0] = 2; \ fwRecoGeometry.idToName[rawid].topology[3] = topo->pitch(); \ } else if (dynamic_cast<const TrapezoidalStripTopology*>(&(det->specificType().specificTopology()))) { \ fwRecoGeometry.idToName[rawid].topology[0] = 3; \ fwRecoGeometry.idToName[rawid].topology[3] = topo->pitch(); \ } \ } else { \ const Phase2TrackerGeomDetUnit* det = dynamic_cast<const Phase2TrackerGeomDetUnit*>(detUnit); \ if (det) { \ if (const Phase2TrackerTopology* topo = \ dynamic_cast<const Phase2TrackerTopology*>(&(det->specificTopology()))) { \ fwRecoGeometry.idToName[rawid].topology[0] = topo->pitch().first; \ fwRecoGeometry.idToName[rawid].topology[1] = topo->pitch().second; \ } \ } \ } namespace { const std::array<std::string, 3> hgcal_geom_names = { {"HGCalEESensitive", "HGCalHESiliconSensitive", "HGCalHEScintillatorSensitive"}}; } FWRecoGeometryESProducer::FWRecoGeometryESProducer(const edm::ParameterSet& pset) : m_current(-1) { m_tracker = pset.getUntrackedParameter<bool>("Tracker", true); m_muon = pset.getUntrackedParameter<bool>("Muon", true); m_calo = pset.getUntrackedParameter<bool>("Calo", true); m_timing = pset.getUntrackedParameter<bool>("Timing", false); auto cc = setWhatProduced(this); if (m_tracker or m_muon) { m_trackingGeomToken = cc.consumes(); } if (m_timing) { m_ftlBarrelGeomToken = cc.consumes(edm::ESInputTag{"", "FastTimeBarrel"}); m_ftlEndcapGeomToken = cc.consumes(edm::ESInputTag{"", "SFBX"}); } if (m_calo) { m_caloGeomToken = cc.consumes(); } } FWRecoGeometryESProducer::~FWRecoGeometryESProducer(void) {} std::unique_ptr<FWRecoGeometry> FWRecoGeometryESProducer::produce(const FWRecoGeometryRecord& record) { using namespace edm; auto fwRecoGeometry = std::make_unique<FWRecoGeometry>(); if (m_tracker || m_muon) { m_trackingGeom = &record.get(m_trackingGeomToken); DetId detId(DetId::Tracker, 0); m_trackerGeom = static_cast<const TrackerGeometry*>(m_trackingGeom->slaveGeometry(detId)); } if (m_tracker) { addPixelBarrelGeometry(*fwRecoGeometry); addPixelForwardGeometry(*fwRecoGeometry); addTIBGeometry(*fwRecoGeometry); addTIDGeometry(*fwRecoGeometry); addTOBGeometry(*fwRecoGeometry); addTECGeometry(*fwRecoGeometry); writeTrackerParametersXML(*fwRecoGeometry); } if (m_muon) { addDTGeometry(*fwRecoGeometry); addCSCGeometry(*fwRecoGeometry); addRPCGeometry(*fwRecoGeometry); addGEMGeometry(*fwRecoGeometry); addME0Geometry(*fwRecoGeometry); } if (m_calo) { m_caloGeom = &record.get(m_caloGeomToken); addCaloGeometry(*fwRecoGeometry); } if (m_timing) { m_ftlBarrelGeom = &record.getRecord<CaloGeometryRecord>().get(m_ftlBarrelGeomToken); m_ftlEndcapGeom = &record.getRecord<CaloGeometryRecord>().get(m_ftlEndcapGeomToken); addFTLGeometry(*fwRecoGeometry); } fwRecoGeometry->idToName.resize(m_current + 1); std::vector<FWRecoGeom::Info>(fwRecoGeometry->idToName).swap(fwRecoGeometry->idToName); std::sort(fwRecoGeometry->idToName.begin(), fwRecoGeometry->idToName.end()); return fwRecoGeometry; } void FWRecoGeometryESProducer::addCSCGeometry(FWRecoGeometry& fwRecoGeometry) { DetId detId(DetId::Muon, 2); const CSCGeometry* cscGeometry = static_cast<const CSCGeometry*>(m_trackingGeom->slaveGeometry(detId)); for (auto it = cscGeometry->chambers().begin(), end = cscGeometry->chambers().end(); it != end; ++it) { const CSCChamber* chamber = *it; if (chamber) { unsigned int rawid = chamber->geographicalId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, chamber, fwRecoGeometry); // // CSC layers geometry // for (std::vector<const CSCLayer*>::const_iterator lit = chamber->layers().begin(), lend = chamber->layers().end(); lit != lend; ++lit) { const CSCLayer* layer = *lit; if (layer) { unsigned int rawid = layer->geographicalId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, layer, fwRecoGeometry); const CSCStripTopology* stripTopology = layer->geometry()->topology(); fwRecoGeometry.idToName[current].topology[0] = stripTopology->yAxisOrientation(); fwRecoGeometry.idToName[current].topology[1] = stripTopology->centreToIntersection(); fwRecoGeometry.idToName[current].topology[2] = stripTopology->yCentreOfStripPlane(); fwRecoGeometry.idToName[current].topology[3] = stripTopology->phiOfOneEdge(); fwRecoGeometry.idToName[current].topology[4] = stripTopology->stripOffset(); fwRecoGeometry.idToName[current].topology[5] = stripTopology->angularWidth(); const CSCWireTopology* wireTopology = layer->geometry()->wireTopology(); fwRecoGeometry.idToName[current].topology[6] = wireTopology->wireSpacing(); fwRecoGeometry.idToName[current].topology[7] = wireTopology->wireAngle(); } } } } } void FWRecoGeometryESProducer::addDTGeometry(FWRecoGeometry& fwRecoGeometry) { DetId detId(DetId::Muon, 1); const DTGeometry* dtGeometry = static_cast<const DTGeometry*>(m_trackingGeom->slaveGeometry(detId)); // // DT chambers geometry // for (auto it = dtGeometry->chambers().begin(), end = dtGeometry->chambers().end(); it != end; ++it) { const DTChamber* chamber = *it; if (chamber) { unsigned int rawid = chamber->geographicalId().rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, chamber, fwRecoGeometry); } } // Fill in DT layer parameters for (auto it = dtGeometry->layers().begin(), end = dtGeometry->layers().end(); it != end; ++it) { const DTLayer* layer = *it; if (layer) { unsigned int rawid = layer->id().rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, layer, fwRecoGeometry); const DTTopology& topo = layer->specificTopology(); const BoundPlane& surf = layer->surface(); // Topology W/H/L: fwRecoGeometry.idToName[current].topology[0] = topo.cellWidth(); fwRecoGeometry.idToName[current].topology[1] = topo.cellHeight(); fwRecoGeometry.idToName[current].topology[2] = topo.cellLenght(); fwRecoGeometry.idToName[current].topology[3] = topo.firstChannel(); fwRecoGeometry.idToName[current].topology[4] = topo.lastChannel(); fwRecoGeometry.idToName[current].topology[5] = topo.channels(); // Bounds W/H/L: fwRecoGeometry.idToName[current].topology[6] = surf.bounds().width(); fwRecoGeometry.idToName[current].topology[7] = surf.bounds().thickness(); fwRecoGeometry.idToName[current].topology[8] = surf.bounds().length(); } } } void FWRecoGeometryESProducer::addRPCGeometry(FWRecoGeometry& fwRecoGeometry) { // // RPC rolls geometry // DetId detId(DetId::Muon, 3); const RPCGeometry* rpcGeom = static_cast<const RPCGeometry*>(m_trackingGeom->slaveGeometry(detId)); for (auto it = rpcGeom->rolls().begin(), end = rpcGeom->rolls().end(); it != end; ++it) { const RPCRoll* roll = (*it); if (roll) { unsigned int rawid = roll->geographicalId().rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, roll, fwRecoGeometry); const StripTopology& topo = roll->specificTopology(); fwRecoGeometry.idToName[current].topology[0] = topo.nstrips(); fwRecoGeometry.idToName[current].topology[1] = topo.stripLength(); fwRecoGeometry.idToName[current].topology[2] = topo.pitch(); } } try { RPCDetId id(1, 1, 4, 1, 1, 1, 1); m_trackingGeom->slaveGeometry(detId); fwRecoGeometry.extraDet.Add(new TNamed("RE4", "RPC endcap station 4")); } catch (std::runtime_error& e) { std::cerr << e.what() << std::endl; } } void FWRecoGeometryESProducer::addGEMGeometry(FWRecoGeometry& fwRecoGeometry) { // // GEM geometry // try { DetId detId(DetId::Muon, 4); const GEMGeometry* gemGeom = static_cast<const GEMGeometry*>(m_trackingGeom->slaveGeometry(detId)); // add in superChambers - gem Segments are based on superChambers for (auto sc : gemGeom->superChambers()) { if (sc) { unsigned int rawid = sc->geographicalId().rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, sc, fwRecoGeometry); } } // add in chambers for (auto ch : gemGeom->chambers()) { if (ch) { unsigned int rawid = ch->geographicalId().rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, ch, fwRecoGeometry); } } // add in etaPartitions - gem rechits are based on etaPartitions for (auto roll : gemGeom->etaPartitions()) { if (roll) { unsigned int rawid = roll->geographicalId().rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, roll, fwRecoGeometry); const StripTopology& topo = roll->specificTopology(); fwRecoGeometry.idToName[current].topology[0] = topo.nstrips(); fwRecoGeometry.idToName[current].topology[1] = topo.stripLength(); fwRecoGeometry.idToName[current].topology[2] = topo.pitch(); float height = topo.stripLength() / 2; LocalPoint lTop(0., height, 0.); LocalPoint lBottom(0., -height, 0.); fwRecoGeometry.idToName[current].topology[3] = roll->localPitch(lTop); fwRecoGeometry.idToName[current].topology[4] = roll->localPitch(lBottom); fwRecoGeometry.idToName[current].topology[5] = roll->npads(); } } fwRecoGeometry.extraDet.Add(new TNamed("GEM", "GEM muon detector")); try { GEMDetId id(1, 1, 2, 1, 1, 1); m_trackingGeom->slaveGeometry(id); fwRecoGeometry.extraDet.Add(new TNamed("GE2", "GEM endcap station 2")); } catch (std::runtime_error& e) { std::cerr << e.what() << std::endl; } } catch (cms::Exception& exception) { edm::LogError("FWRecoGeometry") << " GEM geometry not found " << exception.what() << std::endl; } } void FWRecoGeometryESProducer::addME0Geometry(FWRecoGeometry& fwRecoGeometry) { // // ME0 geometry // DetId detId(DetId::Muon, 5); try { const ME0Geometry* me0Geom = static_cast<const ME0Geometry*>(m_trackingGeom->slaveGeometry(detId)); for (auto roll : me0Geom->etaPartitions()) { if (roll) { unsigned int rawid = roll->geographicalId().rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, roll, fwRecoGeometry); const StripTopology& topo = roll->specificTopology(); fwRecoGeometry.idToName[current].topology[0] = topo.nstrips(); fwRecoGeometry.idToName[current].topology[1] = topo.stripLength(); fwRecoGeometry.idToName[current].topology[2] = topo.pitch(); float height = topo.stripLength() / 2; LocalPoint lTop(0., height, 0.); LocalPoint lBottom(0., -height, 0.); fwRecoGeometry.idToName[current].topology[3] = roll->localPitch(lTop); fwRecoGeometry.idToName[current].topology[4] = roll->localPitch(lBottom); fwRecoGeometry.idToName[current].topology[5] = roll->npads(); } } fwRecoGeometry.extraDet.Add(new TNamed("ME0", "ME0 muon detector")); } catch (cms::Exception& exception) { edm::LogError("FWRecoGeometry") << " ME0 geometry not found " << exception.what() << std::endl; } } void FWRecoGeometryESProducer::addPixelBarrelGeometry(FWRecoGeometry& fwRecoGeometry) { for (TrackerGeometry::DetContainer::const_iterator it = m_trackerGeom->detsPXB().begin(), end = m_trackerGeom->detsPXB().end(); it != end; ++it) { const GeomDet* det = *it; if (det) { DetId detid = det->geographicalId(); unsigned int rawid = detid.rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, det, fwRecoGeometry); ADD_PIXEL_TOPOLOGY(current, m_trackerGeom->idToDetUnit(detid), fwRecoGeometry); } } } void FWRecoGeometryESProducer::addPixelForwardGeometry(FWRecoGeometry& fwRecoGeometry) { for (TrackerGeometry::DetContainer::const_iterator it = m_trackerGeom->detsPXF().begin(), end = m_trackerGeom->detsPXF().end(); it != end; ++it) { const GeomDet* det = *it; if (det) { DetId detid = det->geographicalId(); unsigned int rawid = detid.rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, det, fwRecoGeometry); ADD_PIXEL_TOPOLOGY(current, m_trackerGeom->idToDetUnit(detid), fwRecoGeometry); } } } void FWRecoGeometryESProducer::addTIBGeometry(FWRecoGeometry& fwRecoGeometry) { for (TrackerGeometry::DetContainer::const_iterator it = m_trackerGeom->detsTIB().begin(), end = m_trackerGeom->detsTIB().end(); it != end; ++it) { const GeomDet* det = *it; if (det) { DetId detid = det->geographicalId(); unsigned int rawid = detid.rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, det, fwRecoGeometry); ADD_SISTRIP_TOPOLOGY(current, m_trackerGeom->idToDet(detid)); } } } void FWRecoGeometryESProducer::addTOBGeometry(FWRecoGeometry& fwRecoGeometry) { for (TrackerGeometry::DetContainer::const_iterator it = m_trackerGeom->detsTOB().begin(), end = m_trackerGeom->detsTOB().end(); it != end; ++it) { const GeomDet* det = *it; if (det) { DetId detid = det->geographicalId(); unsigned int rawid = detid.rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, det, fwRecoGeometry); ADD_SISTRIP_TOPOLOGY(current, m_trackerGeom->idToDet(detid)); } } } void FWRecoGeometryESProducer::addTIDGeometry(FWRecoGeometry& fwRecoGeometry) { for (TrackerGeometry::DetContainer::const_iterator it = m_trackerGeom->detsTID().begin(), end = m_trackerGeom->detsTID().end(); it != end; ++it) { const GeomDet* det = *it; if (det) { DetId detid = det->geographicalId(); unsigned int rawid = detid.rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, det, fwRecoGeometry); ADD_SISTRIP_TOPOLOGY(current, m_trackerGeom->idToDet(detid)); } } } void FWRecoGeometryESProducer::addTECGeometry(FWRecoGeometry& fwRecoGeometry) { for (TrackerGeometry::DetContainer::const_iterator it = m_trackerGeom->detsTEC().begin(), end = m_trackerGeom->detsTEC().end(); it != end; ++it) { const GeomDet* det = *it; if (det) { DetId detid = det->geographicalId(); unsigned int rawid = detid.rawId(); unsigned int current = insert_id(rawid, fwRecoGeometry); fillShapeAndPlacement(current, det, fwRecoGeometry); ADD_SISTRIP_TOPOLOGY(current, m_trackerGeom->idToDet(detid)); } } } void FWRecoGeometryESProducer::addCaloGeometry(FWRecoGeometry& fwRecoGeometry) { std::vector<DetId> vid = m_caloGeom->getValidDetIds(); // Calo for (std::vector<DetId>::const_iterator it = vid.begin(), end = vid.end(); it != end; ++it) { unsigned int id = insert_id(it->rawId(), fwRecoGeometry); if (!((DetId::Forward == it->det()) || (DetId::HGCalEE == it->det()) || (DetId::HGCalHSi == it->det()) || (DetId::HGCalHSc == it->det()))) { const CaloCellGeometry::CornersVec& cor = m_caloGeom->getGeometry(*it)->getCorners(); fillPoints(id, cor.begin(), cor.end(), fwRecoGeometry); } else { DetId::Detector det = it->det(); int subdet = (((DetId::HGCalEE == det) || (DetId::HGCalHSi == det) || (DetId::HGCalHSc == det)) ? ForwardEmpty : it->subdetId()); const HGCalGeometry* geom = dynamic_cast<const HGCalGeometry*>(m_caloGeom->getSubdetectorGeometry(det, subdet)); const auto cor = geom->getNewCorners(*it); // roll = yaw = pitch = 0 fwRecoGeometry.idToName[id].matrix[0] = 1.0; fwRecoGeometry.idToName[id].matrix[4] = 1.0; fwRecoGeometry.idToName[id].matrix[8] = 1.0; // corners of the front face for (uint i = 0; i < (cor.size() - 1); ++i) { fwRecoGeometry.idToName[id].points[i * 3 + 0] = cor[i].x(); fwRecoGeometry.idToName[id].points[i * 3 + 1] = cor[i].y(); fwRecoGeometry.idToName[id].points[i * 3 + 2] = cor[i].z(); } // center auto center = geom->getPosition(*it); fwRecoGeometry.idToName[id].points[(cor.size() - 1) * 3 + 0] = center.x(); fwRecoGeometry.idToName[id].points[(cor.size() - 1) * 3 + 1] = center.y(); fwRecoGeometry.idToName[id].points[(cor.size() - 1) * 3 + 2] = center.z(); // thickness fwRecoGeometry.idToName[id].shape[3] = cor[cor.size() - 1].z(); // total points fwRecoGeometry.idToName[id].topology[0] = cor.size() - 1; } } } void FWRecoGeometryESProducer::addFTLGeometry(FWRecoGeometry& fwRecoGeometry) { // do the barrel for (const auto& detid : m_ftlBarrelGeom->getValidDetIds()) { unsigned int id = insert_id(detid.rawId(), fwRecoGeometry); const auto& cor = m_ftlBarrelGeom->getCorners(detid); fillPoints(id, cor.begin(), cor.end(), fwRecoGeometry); } // do the endcap for (const auto& detid : m_ftlEndcapGeom->getValidDetIds()) { unsigned int id = insert_id(detid.rawId(), fwRecoGeometry); const auto& cor = m_ftlEndcapGeom->getCorners(detid); fillPoints(id, cor.begin(), cor.end(), fwRecoGeometry); } } unsigned int FWRecoGeometryESProducer::insert_id(unsigned int rawid, FWRecoGeometry& fwRecoGeometry) { ++m_current; fwRecoGeometry.idToName.push_back(FWRecoGeom::Info()); fwRecoGeometry.idToName.back().id = rawid; return m_current; } void FWRecoGeometryESProducer::fillPoints(unsigned int id, std::vector<GlobalPoint>::const_iterator begin, std::vector<GlobalPoint>::const_iterator end, FWRecoGeometry& fwRecoGeometry) { unsigned int index(0); for (std::vector<GlobalPoint>::const_iterator i = begin; i != end; ++i) { assert(index < FWTGeoRecoGeometry::maxPoints_ - 1); fwRecoGeometry.idToName[id].points[index] = i->x(); fwRecoGeometry.idToName[id].points[++index] = i->y(); fwRecoGeometry.idToName[id].points[++index] = i->z(); ++index; } } /** Shape of GeomDet */ void FWRecoGeometryESProducer::fillShapeAndPlacement(unsigned int id, const GeomDet* det, FWRecoGeometry& fwRecoGeometry) { // Trapezoidal const Bounds* b = &((det->surface()).bounds()); if (const TrapezoidalPlaneBounds* b2 = dynamic_cast<const TrapezoidalPlaneBounds*>(b)) { std::array<const float, 4> const& par = b2->parameters(); // These parameters are half-lengths, as in CMSIM/GEANT3 fwRecoGeometry.idToName[id].shape[0] = 1; fwRecoGeometry.idToName[id].shape[1] = par[0]; // hBottomEdge fwRecoGeometry.idToName[id].shape[2] = par[1]; // hTopEdge fwRecoGeometry.idToName[id].shape[3] = par[2]; // thickness fwRecoGeometry.idToName[id].shape[4] = par[3]; // apothem } if (const RectangularPlaneBounds* b2 = dynamic_cast<const RectangularPlaneBounds*>(b)) { // Rectangular fwRecoGeometry.idToName[id].shape[0] = 2; fwRecoGeometry.idToName[id].shape[1] = b2->width() * 0.5; // half width fwRecoGeometry.idToName[id].shape[2] = b2->length() * 0.5; // half length fwRecoGeometry.idToName[id].shape[3] = b2->thickness() * 0.5; // half thickness } // Position of the DetUnit's center GlobalPoint pos = det->surface().position(); fwRecoGeometry.idToName[id].translation[0] = pos.x(); fwRecoGeometry.idToName[id].translation[1] = pos.y(); fwRecoGeometry.idToName[id].translation[2] = pos.z(); // Add the coeff of the rotation matrix // with a projection on the basis vectors TkRotation<float> detRot = det->surface().rotation(); fwRecoGeometry.idToName[id].matrix[0] = detRot.xx(); fwRecoGeometry.idToName[id].matrix[1] = detRot.yx(); fwRecoGeometry.idToName[id].matrix[2] = detRot.zx(); fwRecoGeometry.idToName[id].matrix[3] = detRot.xy(); fwRecoGeometry.idToName[id].matrix[4] = detRot.yy(); fwRecoGeometry.idToName[id].matrix[5] = detRot.zy(); fwRecoGeometry.idToName[id].matrix[6] = detRot.xz(); fwRecoGeometry.idToName[id].matrix[7] = detRot.yz(); fwRecoGeometry.idToName[id].matrix[8] = detRot.zz(); } void FWRecoGeometryESProducer::writeTrackerParametersXML(FWRecoGeometry& fwRecoGeometry) { std::string path = "Geometry/TrackerCommonData/data/"; if (m_trackerGeom->isThere(GeomDetEnumerators::P1PXB) || m_trackerGeom->isThere(GeomDetEnumerators::P1PXEC)) { path += "PhaseI/"; } else if (m_trackerGeom->isThere(GeomDetEnumerators::P2PXB) || m_trackerGeom->isThere(GeomDetEnumerators::P2PXEC) || m_trackerGeom->isThere(GeomDetEnumerators::P2OTB) || m_trackerGeom->isThere(GeomDetEnumerators::P2OTEC)) { path += "PhaseII/"; } path += "trackerParameters.xml"; std::string fullPath = edm::FileInPath(path).fullPath(); std::ifstream t(fullPath); std::stringstream buffer; buffer << t.rdbuf(); fwRecoGeometry.trackerTopologyXML = buffer.str(); }
/* * sys_beos.cpp - System dependent routines, BeOS implementation * * Basilisk II (C) 1997-2008 Christian Bauer * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <StorageKit.h> #include <InterfaceKit.h> #include <kernel/fs_info.h> #include <drivers/Drivers.h> #include <device/scsi.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include "sysdeps.h" #include "main.h" #include "macos_util.h" #include "prefs.h" #include "user_strings.h" #include "sys.h" #define DEBUG 0 #include "debug.h" #ifdef __HAIKU__ #include <fs_volume.h> #define unmount(x) fs_unmount_volume(x, 0) #endif // File handles are pointers to these structures struct file_handle { file_handle *next; // Pointer to next file handle (must be first in struct!) const char *name; // File/device name (copied, for mount menu) int fd; // fd of file/device bool is_file; // Flag: plain file or /dev/something? bool read_only; // Copy of Sys_open() flag loff_t start_byte; // Size of file header (if any) loff_t file_size; // Size of file data (only valid if is_file is true) }; // Linked list of file handles static file_handle *first_file_handle; // Temporary buffer for transfers from/to kernel space const int TMP_BUF_SIZE = 0x10000; static uint8 *tmp_buf; // For B_SCSI_PREVENT_ALLOW static const int32 PREVENT = 1; static const int32 ALLOW = 0; /* * Check if device is a mounted HFS volume, get mount name */ static bool is_drive_mounted(const char *dev_name, char *mount_name) { int32 i = 0; dev_t d; fs_info info; while ((d = next_dev(&i)) >= 0) { fs_stat_dev(d, &info); if (strcmp(dev_name, info.device_name) == 0) { status_t err = -1; BPath mount; BDirectory dir; BEntry entry; node_ref node; node.device = info.dev; node.node = info.root; err = dir.SetTo(&node); if (!err) err = dir.GetEntry(&entry); if (!err) err = entry.GetPath(&mount); if (!err) { strcpy(mount_name, mount.Path()); return true; } } } return false; } /* * Initialization */ void SysInit(void) { first_file_handle = NULL; // Allocate temporary buffer tmp_buf = new uint8[TMP_BUF_SIZE]; } /* * Deinitialization */ void SysExit(void) { delete[] tmp_buf; } /* * Create menu of used volumes (for "mount" menu) */ void SysCreateVolumeMenu(BMenu *menu, uint32 msg) { for (file_handle *fh=first_file_handle; fh; fh=fh->next) if (!SysIsFixedDisk(fh)) menu->AddItem(new BMenuItem(fh->name, new BMessage(msg))); } /* * Mount volume given name from mount menu */ void SysMountVolume(const char *name) { file_handle *fh; for (fh=first_file_handle; fh && strcmp(fh->name, name); fh=fh->next) ; if (fh) MountVolume(fh); } /* * This gets called when no "floppy" prefs items are found * It scans for available floppy drives and adds appropriate prefs items */ void SysAddFloppyPrefs(void) { // Only one floppy drive under BeOS PrefsAddString("floppy", "/dev/disk/floppy/raw"); } /* * This gets called when no "disk" prefs items are found * It scans for available HFS volumes and adds appropriate prefs items */ void SysAddDiskPrefs(void) { // Let BeOS scan for HFS drives D(bug("Looking for Mac volumes...\n")); system("mountvolume -allhfs"); // Add all HFS volumes int32 i = 0; dev_t d; fs_info info; while ((d = next_dev(&i)) >= 0) { fs_stat_dev(d, &info); status_t err = -1; BPath mount; if (!strcmp(info.fsh_name, "hfs")) { BDirectory dir; BEntry entry; node_ref node; node.device = info.dev; node.node = info.root; err = dir.SetTo(&node); if (!err) err = dir.GetEntry(&entry); if (!err) err = entry.GetPath(&mount); } if (!err) err = unmount(mount.Path()); if (!err) { char dev_name[B_FILE_NAME_LENGTH]; if (info.flags & B_FS_IS_READONLY) { dev_name[0] = '*'; dev_name[1] = 0; } else dev_name[0] = 0; strcat(dev_name, info.device_name); PrefsAddString("disk", dev_name); } } } /* * This gets called when no "cdrom" prefs items are found * It scans for available CD-ROM drives and adds appropriate prefs items */ // Scan directory for CD-ROM drives, add them to prefs static void scan_for_cdrom_drives(const char *directory) { // Set directory BDirectory dir; dir.SetTo(directory); if (dir.InitCheck() != B_NO_ERROR) return; dir.Rewind(); // Scan each entry BEntry entry; while (dir.GetNextEntry(&entry) >= 0) { // Get path and ref for entry BPath path; if (entry.GetPath(&path) != B_NO_ERROR) continue; const char *name = path.Path(); entry_ref e; if (entry.GetRef(&e) != B_NO_ERROR) continue; // Recursively enter subdirectories (except for floppy) if (entry.IsDirectory()) { if (!strcmp(e.name, "floppy")) continue; scan_for_cdrom_drives(name); } else { D(bug(" checking '%s'\n", name)); // Ignore partitions if (strcmp(e.name, "raw")) continue; // Open device int fd = open(name, O_RDONLY); if (fd < 0) continue; // Get geometry and device type device_geometry g; if (ioctl(fd, B_GET_GEOMETRY, &g, sizeof(g)) < 0) { close(fd); continue; } // Insert to list if it is a CD drive if (g.device_type == B_CD) PrefsAddString("cdrom", name); close(fd); } } } void SysAddCDROMPrefs(void) { // Don't scan for drives if nocdrom option given if (PrefsFindBool("nocdrom")) return; // Look for CD-ROM drives and add prefs items D(bug("Looking for CD-ROM drives...\n")); scan_for_cdrom_drives("/dev/disk"); } /* * Add default serial prefs (must be added, even if no ports present) */ void SysAddSerialPrefs(void) { #ifdef __HAIKU__ PrefsAddString("seriala", "serial1"); PrefsAddString("serialb", "serial2"); #else system_info info; get_system_info(&info); switch (info.platform_type) { case B_BEBOX_PLATFORM: case B_AT_CLONE_PLATFORM: PrefsAddString("seriala", "serial1"); PrefsAddString("serialb", "serial2"); break; case B_MAC_PLATFORM: PrefsAddString("seriala", "modem"); PrefsAddString("serialb", "printer"); break; default: PrefsAddString("seriala", "none"); PrefsAddString("serialb", "none"); break; } #endif } /* * Open file/device, create new file handle (returns NULL on error) */ void *Sys_open(const char *name, bool read_only) { static bool published_all = false; bool is_file = (strstr(name, "/dev/") != name); D(bug("Sys_open(%s, %s)\n", name, read_only ? "read-only" : "read/write")); // Print warning message and eventually unmount drive when this is an HFS volume mounted under BeOS (double mounting will corrupt the volume) char mount_name[B_FILE_NAME_LENGTH]; if (!is_file && !read_only && is_drive_mounted(name, mount_name)) { char str[256 + B_FILE_NAME_LENGTH]; sprintf(str, GetString(STR_VOLUME_IS_MOUNTED_WARN), mount_name); WarningAlert(str); if (unmount(mount_name) != 0) { sprintf(str, GetString(STR_CANNOT_UNMOUNT_WARN), mount_name); WarningAlert(str); return NULL; } } int fd = open(name, read_only ? O_RDONLY : O_RDWR); if (fd < 0 && !published_all) { // Open failed, create all device nodes and try again, but only the first time system("mountvolume -publishall"); published_all = true; fd = open(name, read_only ? O_RDONLY : O_RDWR); } if (fd >= 0) { file_handle *fh = new file_handle; fh->name = strdup(name); fh->fd = fd; fh->is_file = is_file; fh->read_only = read_only; fh->start_byte = 0; if (fh->is_file) { // Detect disk image file layout loff_t size = lseek(fd, 0, SEEK_END); uint8 data[256]; lseek(fd, 0, SEEK_SET); read(fd, data, 256); FileDiskLayout(size, data, fh->start_byte, fh->file_size); } // Enqueue file handle fh->next = NULL; file_handle *q = first_file_handle; if (q) { while (q->next) q = q->next; q->next = fh; } else first_file_handle = fh; return fh; } else return NULL; } /* * Close file/device, delete file handle */ void Sys_close(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return; // Free device name and close file/device free((void *)fh->name); close(fh->fd); // Dequeue file handle file_handle *q = first_file_handle; if (q == fh) { first_file_handle = NULL; delete fh; return; } while (q) { if (q->next == fh) { q->next = fh->next; delete fh; return; } q = q->next; } } /* * Read "length" bytes from file/device, starting at "offset", to "buffer", * returns number of bytes read (or 0) */ static inline ssize_t sread(int fd, void *buf, size_t count) { ssize_t res; while ((res = read(fd, buf, count)) == B_INTERRUPTED) ; return res; } size_t Sys_read(void *arg, void *buffer, loff_t offset, size_t length) { file_handle *fh = (file_handle *)arg; if (!fh) return 0; // D(bug("Sys_read(%08lx, %08lx, %Ld, %d)\n", fh, buffer, offset, length)); // Seek to position if (lseek(fh->fd, offset + fh->start_byte, SEEK_SET) < 0) return 0; // Buffer in kernel space? size_t actual = 0; if ((uint32)buffer < 0x80000000) { // Yes, transfer via buffer while (length) { size_t transfer_size = (length > TMP_BUF_SIZE) ? TMP_BUF_SIZE : length; if (sread(fh->fd, tmp_buf, transfer_size) != transfer_size) return actual; memcpy(buffer, tmp_buf, transfer_size); buffer = (void *)((uint8 *)buffer + transfer_size); length -= transfer_size; actual += transfer_size; } } else { // No, transfer directly actual = sread(fh->fd, buffer, length); if (actual < 0) actual = 0; } return actual; } /* * Write "length" bytes from "buffer" to file/device, starting at "offset", * returns number of bytes written (or 0) */ static inline ssize_t swrite(int fd, void *buf, size_t count) { ssize_t res; while ((res = write(fd, buf, count)) == B_INTERRUPTED) ; return res; } size_t Sys_write(void *arg, void *buffer, loff_t offset, size_t length) { file_handle *fh = (file_handle *)arg; if (!fh) return 0; // D(bug("Sys_write(%08lx, %08lx, %Ld, %d)\n", fh, buffer, offset, length)); // Seek to position if (lseek(fh->fd, offset + fh->start_byte, SEEK_SET) < 0) return 0; // Buffer in kernel space? size_t actual = 0; if ((uint32)buffer < 0x80000000) { // Yes, transfer via buffer while (length) { size_t transfer_size = (length > TMP_BUF_SIZE) ? TMP_BUF_SIZE : length; memcpy(tmp_buf, buffer, transfer_size); if (swrite(fh->fd, tmp_buf, transfer_size) != transfer_size) return actual; buffer = (void *)((uint8 *)buffer + transfer_size); length -= transfer_size; actual += transfer_size; } } else { // No, transfer directly actual = swrite(fh->fd, buffer, length); if (actual < 0) actual = 0; } return actual; } /* * Return size of file/device (minus header) */ loff_t SysGetFileSize(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return true; if (fh->is_file) return fh->file_size; else { device_geometry g; if (ioctl(fh->fd, B_GET_GEOMETRY, &g, sizeof(g)) >= 0) return (loff_t)g.bytes_per_sector * g.sectors_per_track * g.cylinder_count * g.head_count; else return 0; } } /* * Eject volume (if applicable) */ void SysEject(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return; if (!fh->is_file) ioctl(fh->fd, B_EJECT_DEVICE); } /* * Format volume (if applicable) */ bool SysFormat(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return false; if (!fh->is_file) return ioctl(fh->fd, B_FORMAT_DEVICE) >= 0; else return false; } /* * Check if file/device is read-only (this includes the read-only flag on Sys_open()) */ bool SysIsReadOnly(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return true; if (fh->is_file) { // File, return flag given to Sys_open return fh->read_only; } else { // Device, check write protection device_geometry g; if (ioctl(fh->fd, B_GET_GEOMETRY, &g, sizeof(g)) >= 0) return g.read_only | fh->read_only; else return fh->read_only; // Removable but not inserted } } /* * Check if the given file handle refers to a fixed or a removable disk */ bool SysIsFixedDisk(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return true; if (fh->is_file) return true; else { device_geometry g; if (ioctl(fh->fd, B_GET_GEOMETRY, &g, sizeof(g)) >= 0) return !g.removable; else return false; // Removable but not inserted } } /* * Check if a disk is inserted in the drive (always true for files) */ bool SysIsDiskInserted(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return false; if (fh->is_file) return true; else { status_t l; if (ioctl(fh->fd, B_GET_MEDIA_STATUS, &l, sizeof(l)) >= 0 && l == B_NO_ERROR) return true; else return false; } } /* * Prevent medium removal (if applicable) */ void SysPreventRemoval(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return; if (!fh->is_file) ioctl(fh->fd, B_SCSI_PREVENT_ALLOW, &PREVENT, sizeof(PREVENT)); } /* * Allow medium removal (if applicable) */ void SysAllowRemoval(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return; if (!fh->is_file) ioctl(fh->fd, B_SCSI_PREVENT_ALLOW, &ALLOW, sizeof(ALLOW)); } /* * Read CD-ROM TOC (binary MSF format, 804 bytes max.) */ bool SysCDReadTOC(void *arg, uint8 *toc) { file_handle *fh = (file_handle *)arg; if (!fh) return false; if (!fh->is_file) { memset(tmp_buf, 0, 804); if (ioctl(fh->fd, B_SCSI_GET_TOC, tmp_buf, 804) < 0) return false; memcpy(toc, tmp_buf, 804); return true; } else return false; } /* * Read CD-ROM position data (Sub-Q Channel, 16 bytes, see SCSI standard) */ bool SysCDGetPosition(void *arg, uint8 *pos) { file_handle *fh = (file_handle *)arg; if (!fh) return false; if (!fh->is_file) { if (ioctl(fh->fd, B_SCSI_GET_POSITION, tmp_buf, 16) < 0) return false; memcpy(pos, tmp_buf, 16); return true; } else return false; } /* * Play CD audio */ bool SysCDPlay(void *arg, uint8 start_m, uint8 start_s, uint8 start_f, uint8 end_m, uint8 end_s, uint8 end_f) { file_handle *fh = (file_handle *)arg; if (!fh) return false; if (!fh->is_file) { scsi_play_position *p = (scsi_play_position *)tmp_buf; p->start_m = start_m; p->start_s = start_s; p->start_f = start_f; p->end_m = end_m; p->end_s = end_s; p->end_f = end_f; return ioctl(fh->fd, B_SCSI_PLAY_POSITION, p, sizeof(scsi_play_position)) == 0; } else return false; } /* * Pause CD audio */ bool SysCDPause(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return true; if (!fh->is_file) return ioctl(fh->fd, B_SCSI_PAUSE_AUDIO) == 0; else return false; } /* * Resume paused CD audio */ bool SysCDResume(void *arg) { file_handle *fh = (file_handle *)arg; if (!fh) return false; if (!fh->is_file) return ioctl(fh->fd, B_SCSI_RESUME_AUDIO) == 0; else return false; } /* * Stop CD audio */ bool SysCDStop(void *arg, uint8 lead_out_m, uint8 lead_out_s, uint8 lead_out_f) { file_handle *fh = (file_handle *)arg; if (!fh) return false; if (!fh->is_file) return ioctl(fh->fd, B_SCSI_STOP_AUDIO) == 0; else return false; } /* * Perform CD audio fast-forward/fast-reverse operation starting from specified address */ bool SysCDScan(void *arg, uint8 start_m, uint8 start_s, uint8 start_f, bool reverse) { file_handle *fh = (file_handle *)arg; if (!fh) return false; if (!fh->is_file) { scsi_scan *p = (scsi_scan *)tmp_buf; p->speed = 0; p->direction = reverse ? -1 : 1; return ioctl(fh->fd, B_SCSI_SCAN, p, sizeof(scsi_scan)) == 0; } else return false; } /* * Set CD audio volume (0..255 each channel) */ void SysCDSetVolume(void *arg, uint8 left, uint8 right) { file_handle *fh = (file_handle *)arg; if (!fh) return; if (!fh->is_file) { scsi_volume *p = (scsi_volume *)tmp_buf; p->flags = B_SCSI_PORT0_VOLUME | B_SCSI_PORT1_VOLUME; p->port0_volume = left; p->port1_volume = right; ioctl(fh->fd, B_SCSI_SET_VOLUME, p, sizeof(scsi_volume)); } } /* * Get CD audio volume (0..255 each channel) */ void SysCDGetVolume(void *arg, uint8 &left, uint8 &right) { file_handle *fh = (file_handle *)arg; if (!fh) return; left = right = 0; if (!fh->is_file) { scsi_volume *p = (scsi_volume *)tmp_buf; p->flags = B_SCSI_PORT0_VOLUME | B_SCSI_PORT1_VOLUME; if (ioctl(fh->fd, B_SCSI_GET_VOLUME, p, sizeof(scsi_volume)) == 0) { left = p->port0_volume; right = p->port1_volume; } } }
// Tenchi wo Kurau #include "cps.h" static struct BurnInputInfo DrvInputList[] = { {"P1 Coin" , BIT_DIGITAL, CpsInp018+0, "p1 coin"}, {"P1 Start" , BIT_DIGITAL, CpsInp018+4, "p1 start"}, {"P1 Up" , BIT_DIGITAL, CpsInp001+3, "p1 up"}, {"P1 Down" , BIT_DIGITAL, CpsInp001+2, "p1 down"}, {"P1 Left" , BIT_DIGITAL, CpsInp001+1, "p1 left"}, {"P1 Right" , BIT_DIGITAL, CpsInp001+0, "p1 right"}, {"P1 Attack Left" , BIT_DIGITAL, CpsInp001+4, "p1 fire 1"}, {"P1 Attack Right" , BIT_DIGITAL, CpsInp001+5, "p1 fire 2"}, {"P1 Special" , BIT_DIGITAL, CpsInp001+6, "p1 fire 3"}, {"P2 Coin" , BIT_DIGITAL, CpsInp018+1, "p2 coin"}, {"P2 Start" , BIT_DIGITAL, CpsInp018+5, "p2 start"}, {"P2 Up" , BIT_DIGITAL, CpsInp000+3, "p2 up"}, {"P2 Down" , BIT_DIGITAL, CpsInp000+2, "p2 down"}, {"P2 Left" , BIT_DIGITAL, CpsInp000+1, "p2 left"}, {"P2 Right" , BIT_DIGITAL, CpsInp000+0, "p2 right"}, {"P2 Attack Left" , BIT_DIGITAL, CpsInp000+4, "p2 fire 1"}, {"P2 Attack Right" , BIT_DIGITAL, CpsInp000+5, "p2 fire 2"}, {"P2 Special" , BIT_DIGITAL, CpsInp000+6, "p2 fire 3"}, {"Reset" , BIT_DIGITAL, &CpsReset, "reset"}, {"Diagnostic" , BIT_DIGITAL, CpsInp018+6, "diag"}, {"Service" , BIT_DIGITAL, CpsInp018+2, "service"}, {"Dip A" , BIT_DIPSWITCH, &Cpi01A , "dip"}, {"Dip B" , BIT_DIPSWITCH, &Cpi01C , "dip"}, {"Dip C" , BIT_DIPSWITCH, &Cpi01E , "dip"}, }; STDINPUTINFO(Drv); static struct BurnDIPInfo dwDIPList[]= { // Defaults {0x15, 0xff, 0xff, 0x00, NULL }, {0x16, 0xff, 0xff, 0x00, NULL }, {0x17, 0xff, 0xff, 0x40, NULL }, // Dip A {0 , 0xfe, 0 , 7 , "Coin 1" }, {0x15, 0x01, 0x07, 0x06, "4 Coins 1 Credit" }, {0x15, 0x01, 0x07, 0x05, "3 Coins 1 Credit" }, {0x15, 0x01, 0x07, 0x04, "2 Coins 1 Credit" }, {0x15, 0x01, 0x07, 0x00, "1 Coin 1 Credit" }, {0x15, 0x01, 0x07, 0x01, "1 Coin 2 Credits" }, {0x15, 0x01, 0x07, 0x02, "1 Coin 3 Credits" }, {0x15, 0x01, 0x07, 0x03, "1 Coin 4 Credits" }, {0 , 0xfe, 0 , 7 , "Coin 2" }, {0x15, 0x01, 0x38, 0x30, "4 Coins 1 Credit" }, {0x15, 0x01, 0x38, 0x28, "3 Coins 1 Credit" }, {0x15, 0x01, 0x38, 0x20, "2 Coins 1 Credit" }, {0x15, 0x01, 0x38, 0x00, "1 Coin 1 Credit" }, {0x15, 0x01, 0x38, 0x08, "1 Coin 2 Credits" }, {0x15, 0x01, 0x38, 0x10, "1 Coin 3 Credits" }, {0x15, 0x01, 0x38, 0x18, "1 Coin 4 Credits" }, // {0 , 0xfe, 0 , 2 , "Unknown" }, // {0x15, 0x01, 0x40, 0x00, "Off" }, // {0x15, 0x01, 0x40, 0x40, "On" }, {0 , 0xfe, 0 , 2 , "Free Play" }, {0x15, 0x01, 0x80, 0x00, "Off" }, {0x15, 0x01, 0x80, 0x80, "On" }, // Dip B {0 , 0xfe, 0 , 8 , "Difficulty" }, {0x16, 0x01, 0x07, 0x03, "Very Easy" }, {0x16, 0x01, 0x07, 0x02, "Easy 2" }, {0x16, 0x01, 0x07, 0x01, "Easy 1" }, {0x16, 0x01, 0x07, 0x00, "Normal" }, {0x16, 0x01, 0x07, 0x04, "Difficult 1" }, {0x16, 0x01, 0x07, 0x05, "Difficult 2" }, {0x16, 0x01, 0x07, 0x06, "Difficult 3" }, {0x16, 0x01, 0x07, 0x07, "Very Difficult" }, // {0 , 0xfe, 0 , 2 , "Unknown" }, // {0x16, 0x01, 0x08, 0x00, "Off" }, // {0x16, 0x01, 0x08, 0x08, "On" }, // {0 , 0xfe, 0 , 2 , "Unknown" }, // {0x16, 0x01, 0x10, 0x00, "Off" }, // {0x16, 0x01, 0x10, 0x10, "On" }, // {0 , 0xfe, 0 , 2 , "Unknown" }, // {0x16, 0x01, 0x20, 0x00, "Off" }, // {0x16, 0x01, 0x20, 0x20, "On" }, // {0 , 0xfe, 0 , 2 , "Unknown" }, // {0x16, 0x01, 0x40, 0x00, "Off" }, // {0x16, 0x01, 0x40, 0x40, "On" }, // {0 , 0xfe, 0 , 2 , "Unknown" }, // {0x16, 0x01, 0x80, 0x00, "Off" }, // {0x16, 0x01, 0x80, 0x80, "On" }, // Dip C {0 , 0xfe, 0 , 2 , "Freeze" }, {0x17, 0x01, 0x01, 0x00, "Off" }, {0x17, 0x01, 0x01, 0x01, "On" }, {0 , 0xfe, 0 , 2 , "Turbo Mode" }, {0x17, 0x01, 0x02, 0x00, "Off" }, {0x17, 0x01, 0x02, 0x02, "On" }, // {0 , 0xfe, 0 , 2 , "Unknown" }, // {0x17, 0x01, 0x04, 0x00, "Off" }, // {0x17, 0x01, 0x04, 0x04, "On" }, // {0 , 0xfe, 0 , 2 , "Unknown" }, // {0x17, 0x01, 0x08, 0x00, "Off" }, // {0x17, 0x01, 0x08, 0x08, "On" }, {0 , 0xfe, 0 , 2 , "Flip" }, {0x17, 0x01, 0x10, 0x00, "Off" }, {0x17, 0x01, 0x10, 0x10, "On" }, {0 , 0xfe, 0 , 2 , "Demo Sound" }, {0x17, 0x01, 0x20, 0x00, "Off" }, {0x17, 0x01, 0x20, 0x20, "On" }, {0 , 0xfe, 0 , 2 , "Continue" }, {0x17, 0x01, 0x40, 0x00, "Off" }, {0x17, 0x01, 0x40, 0x40, "On" }, }; STDDIPINFO(dw); static int dwjInit() { int nRet=0; Cps=1; nCpsRomLen= 0x100000; nCpsCodeLen= 0; // not encrypted nCpsGfxLen= 8*0x080000; nCpsZRomLen= 0x010000; nCpsAdLen= 2*0x020000; nRet=CpsInit(); if (nRet!=0) return 1; // Load program roms nRet=BurnLoadRom(CpsRom+0x000001,0,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x000000,1,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x040001,2,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x040000,3,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x080001,4,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x080000,5,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x0c0001,6,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x0c0000,7,2); if (nRet!=0) return 1; // Load graphics roms CpsLoadTilesByte(CpsGfx, 8); CpsLoadTilesByte(CpsGfx+(0x100000), 16); CpsLoadTilesByte(CpsGfx+(0x200000), 24); CpsLoadTilesByte(CpsGfx+(0x300000), 32); nCpsGfxScroll[2]=0x200000; nCpsGfxScroll[3]=0x200000; nCpsLcReg=0x6c; // Layer control register is at 0x6c CpsLayEn[1]=0x02; CpsLayEn[2]=0x04; CpsLayEn[3]=0x08; MaskAddr[0]=0x6a; MaskAddr[1]=0x68; MaskAddr[2]=0x66; MaskAddr[3]=0x64; // Load Z80 Rom nRet=BurnLoadRom(CpsZRom,40,1); // Load ADPCM data nRet=BurnLoadRom(CpsAd ,41,1); nRet=BurnLoadRom(CpsAd+0x20000,42,1); nRet=CpsRunInit(); if (nRet!=0) return 1; // Ready to go return 0; } static int DrvExit() { CpsRunExit(); CpsExit(); nCpsAdLen=0; nCpsZRomLen=0; nCpsGfxLen=0; nCpsRomLen=0; Cps=0; return 0; } //======================= //Tenchi wo Kurau (Japan) //======================= // Rom information static struct BurnRomInfo DwjRomDesc[] = { { "36.bin", 0x20000, 0x1a516657, BRF_ESS | BRF_PRG }, // 0 even 68000 code { "42.bin", 0x20000, 0x12a290a0, BRF_ESS | BRF_PRG }, // 1 odd { "37.bin", 0x20000, 0x932fc943, BRF_ESS | BRF_PRG }, // 2 even { "43.bin", 0x20000, 0x872ad76d, BRF_ESS | BRF_PRG }, // 3 odd { "34.bin", 0x20000, 0x8f663d00, BRF_ESS | BRF_PRG }, // 4 even 68000 code { "40.bin", 0x20000, 0x1586dbf3, BRF_ESS | BRF_PRG }, // 5 odd { "35.bin", 0x20000, 0x9db93d7a, BRF_ESS | BRF_PRG }, // 6 even { "41.bin", 0x20000, 0x1aae69a4, BRF_ESS | BRF_PRG }, // 7 odd // graphics: { "09.bin", 0x20000, 0xc3e83c69, BRF_GRA }, // 8 { "01.bin", 0x20000, 0x187b2886, BRF_GRA }, { "13.bin", 0x20000, 0x0273d87d, BRF_GRA }, { "05.bin", 0x20000, 0x339378b8, BRF_GRA }, { "24.bin", 0x20000, 0xc6909b6f, BRF_GRA }, // 12 { "17.bin", 0x20000, 0x2e2f8320, BRF_GRA }, { "38.bin", 0x20000, 0xcd7923ed, BRF_GRA }, { "32.bin", 0x20000, 0x21a0a453, BRF_GRA }, { "10.bin", 0x20000, 0xff28f8d0, BRF_GRA }, // 16 { "02.bin", 0x20000, 0xcc83c02f, BRF_GRA }, { "14.bin", 0x20000, 0x18fb232c, BRF_GRA }, { "06.bin", 0x20000, 0x6f9edd75, BRF_GRA }, { "25.bin", 0x20000, 0x152ea74a, BRF_GRA }, // 20 { "18.bin", 0x20000, 0x1833f932, BRF_GRA }, { "39.bin", 0x20000, 0xbc09b360, BRF_GRA }, { "33.bin", 0x20000, 0x89de1533, BRF_GRA }, { "11.bin", 0x20000, 0x29eaf490, BRF_GRA }, // 24 { "03.bin", 0x20000, 0x7bf51337, BRF_GRA }, { "15.bin", 0x20000, 0xd36cdb91, BRF_GRA }, { "07.bin", 0x20000, 0xe04af054, BRF_GRA }, { "26.bin", 0x20000, 0x07fc714b, BRF_GRA }, // 28 { "19.bin", 0x20000, 0x7114e5c6, BRF_GRA }, { "28.bin", 0x20000, 0xaf62bf07, BRF_GRA }, { "21.bin", 0x20000, 0x523f462a, BRF_GRA }, { "12.bin", 0x20000, 0x38652339, BRF_GRA }, // 32 { "04.bin", 0x20000, 0x4951bc0f, BRF_GRA }, { "16.bin", 0x20000, 0x381608ae, BRF_GRA }, { "08.bin", 0x20000, 0xb475d4e9, BRF_GRA }, { "27.bin", 0x20000, 0xa27e81fa, BRF_GRA }, // 36 { "20.bin", 0x20000, 0x002796dc, BRF_GRA }, { "29.bin", 0x20000, 0x6b41f82d, BRF_GRA }, { "22.bin", 0x20000, 0x52145369, BRF_GRA }, // z80 rom { "23.bin", 0x10000, 0xb3b79d4f, BRF_GRA }, // 40 // samples { "30.bin", 0x20000, 0x7e5f6cb4, BRF_GRA }, { "31.bin", 0x20000, 0x4a30c737, BRF_GRA }, }; // Make The RomInfo/Name functions for the game STD_ROM_PICK(Dwj) STD_ROM_FN(Dwj) struct BurnDriver BurnDrvCpsDwj = { "dynwarj", "dynwar", NULL, "1989", "Tenchi wo Kurau (Japan)\0", NULL, "Capcom", "CPS1", L"\u8EE2\u5730\u3092\u55B0\u3089\u3046 (Japan)\0Tenchi wo Kurau (Japan)\0", NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE,2,HARDWARE_CAPCOM_CPS1, NULL,DwjRomInfo,DwjRomName,DrvInputInfo, dwDIPInfo, dwjInit,DrvExit,Cps1Frame,CpsRedraw,CpsAreaScan, &CpsRecalcPal,384,224,4,3 }; static int dwInit() { int nRet=0; Cps=1; nCpsRomLen= 0x100000; nCpsCodeLen= 0; // not encrypted nCpsGfxLen= 8*0x080000; nCpsZRomLen= 0x010000; nCpsAdLen= 2*0x020000; nRet=CpsInit(); if (nRet!=0) return 1; // Load program roms nRet=BurnLoadRom(CpsRom+0x000001,0,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x000000,1,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x040001,2,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x040000,3,2); if (nRet!=0) return 1; nRet=BurnLoadRom(CpsRom+0x080000,4,1); if (nRet!=0) return 1; // Load graphics roms CpsLoadTiles(CpsGfx ,5); CpsLoadTiles(CpsGfx+(0x200000),9); nCpsGfxScroll[2]=0x200000; nCpsGfxScroll[3]=0x200000; nCpsLcReg=0x6c; // Layer control register is at 0x6c CpsLayEn[1]=0x02; CpsLayEn[2]=0x04; CpsLayEn[3]=0x08; MaskAddr[0]=0x6a; MaskAddr[1]=0x68; MaskAddr[2]=0x66; MaskAddr[3]=0x64; // Load Z80 Rom nRet=BurnLoadRom(CpsZRom,13,1); // Load ADPCM data nRet=BurnLoadRom(CpsAd ,14,1); nRet=BurnLoadRom(CpsAd+0x20000,15,1); nRet=CpsRunInit(); if (nRet!=0) return 1; // Ready to go return 0; } //==================== //Dynasty Wars (World) //==================== // Rom information static struct BurnRomInfo DwRomDesc[] = { { "30.11f", 0x20000, 0xf9ec6d68, BRF_ESS | BRF_PRG }, // 0 even 68000 code { "35.11h", 0x20000, 0xe41fff2f, BRF_ESS | BRF_PRG }, // 1 odd { "31.12f", 0x20000, 0xe3de76ff, BRF_ESS | BRF_PRG }, // 2 even { "36.12h", 0x20000, 0x7a13cfbf, BRF_ESS | BRF_PRG }, // 3 odd { "tkm-9.8h", 0x80000, 0x93654bcf, BRF_ESS | BRF_PRG }, // 4 // graphics: { "tkm-5.7a", 0x80000, 0xf64bb6a0, BRF_GRA }, { "tkm-8.9a", 0x80000, 0x21fe6274, BRF_GRA }, { "tkm-6.3a", 0x80000, 0x0bf228cb, BRF_GRA }, // 5 { "tkm-7.5a", 0x80000, 0x1255dfb1, BRF_GRA }, { "tkm-1.8a", 0x80000, 0x44f7661e, BRF_GRA }, { "tkm-4.10a", 0x80000, 0xa54c515d, BRF_GRA }, { "tkm-2.4a", 0x80000, 0xca5c687c, BRF_GRA }, // 9 { "tkm-3.6a", 0x80000, 0xf9fe6591, BRF_GRA }, // z80 rom { "tke17.12b", 0x10000, 0xb3b79d4f, BRF_GRA }, // 13 // samples { "tke18.11c", 0x20000, 0xac6e307d, BRF_GRA }, { "tke19.12c", 0x20000, 0x068741db, BRF_GRA }, }; // Make The RomInfo/Name functions for the game STD_ROM_PICK(Dw) STD_ROM_FN(Dw) struct BurnDriver BurnDrvCpsDw = { "dynwar", NULL, NULL, "1989", "Dynasty Wars (World)\0", NULL, "Capcom", "CPS1", NULL, NULL, NULL, NULL, BDF_GAME_WORKING,2,HARDWARE_CAPCOM_CPS1, NULL,DwRomInfo,DwRomName,DrvInputInfo, dwDIPInfo, dwInit,DrvExit,Cps1Frame,CpsRedraw,CpsAreaScan, &CpsRecalcPal,384,224,4,3 };
// Copyright (c) 2013-2014 The Bitcoin developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2018 The nint developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "hash.h" #include "crypto/hmac_sha512.h" inline uint32_t ROTL32(uint32_t x, int8_t r) { return (x << r) | (x >> (32 - r)); } unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector<unsigned char>& vDataToHash) { // The following is MurmurHash3 (x86_32), see http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp uint32_t h1 = nHashSeed; if (vDataToHash.size() > 0) { const uint32_t c1 = 0xcc9e2d51; const uint32_t c2 = 0x1b873593; const int nblocks = vDataToHash.size() / 4; //---------- // body const uint32_t* blocks = (const uint32_t*)(&vDataToHash[0] + nblocks * 4); for (int i = -nblocks; i; i++) { uint32_t k1 = blocks[i]; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1, 13); h1 = h1 * 5 + 0xe6546b64; } //---------- // tail const uint8_t* tail = (const uint8_t*)(&vDataToHash[0] + nblocks * 4); uint32_t k1 = 0; switch (vDataToHash.size() & 3) { case 3: k1 ^= tail[2] << 16; case 2: k1 ^= tail[1] << 8; case 1: k1 ^= tail[0]; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; }; } //---------- // finalization h1 ^= vDataToHash.size(); h1 ^= h1 >> 16; h1 *= 0x85ebca6b; h1 ^= h1 >> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >> 16; return h1; } void BIP32Hash(const ChainCode chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]) { unsigned char num[4]; num[0] = (nChild >> 24) & 0xFF; num[1] = (nChild >> 16) & 0xFF; num[2] = (nChild >> 8) & 0xFF; num[3] = (nChild >> 0) & 0xFF; CHMAC_SHA512(chainCode.begin(), chainCode.size()).Write(&header, 1).Write(data, 32).Write(num, 4).Finalize(output); }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::Analytics namespace UnityEngine::Analytics { // Forward declaring type: AnalyticsResult struct AnalyticsResult; // Forward declaring type: CustomEventData class CustomEventData; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IDictionary`2<TKey, TValue> template<typename TKey, typename TValue> class IDictionary_2; } // Completed forward declares // Type namespace: UnityEngine.Analytics namespace UnityEngine::Analytics { // Forward declaring type: Analytics class Analytics; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::Analytics::Analytics); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::Analytics::Analytics*, "UnityEngine.Analytics", "Analytics"); // Type namespace: UnityEngine.Analytics namespace UnityEngine::Analytics { // Size: 0x10 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.Analytics.Analytics // [TokenAttribute] Offset: FFFFFFFF // [NativeHeaderAttribute] Offset: 6DE048 // [NativeHeaderAttribute] Offset: 6DE048 // [NativeHeaderAttribute] Offset: 6DE048 class Analytics : public ::Il2CppObject { public: // static System.Boolean IsInitialized() // Offset: 0x1900FFC static bool IsInitialized(); // static private UnityEngine.Analytics.AnalyticsResult SendCustomEventName(System.String customEventName) // Offset: 0x1901030 static ::UnityEngine::Analytics::AnalyticsResult SendCustomEventName(::StringW customEventName); // static private UnityEngine.Analytics.AnalyticsResult SendCustomEvent(UnityEngine.Analytics.CustomEventData eventData) // Offset: 0x1901070 static ::UnityEngine::Analytics::AnalyticsResult SendCustomEvent(::UnityEngine::Analytics::CustomEventData* eventData); // static public UnityEngine.Analytics.AnalyticsResult CustomEvent(System.String customEventName) // Offset: 0x19010B0 static ::UnityEngine::Analytics::AnalyticsResult CustomEvent(::StringW customEventName); // static public UnityEngine.Analytics.AnalyticsResult CustomEvent(System.String customEventName, System.Collections.Generic.IDictionary`2<System.String,System.Object> eventData) // Offset: 0x190117C static ::UnityEngine::Analytics::AnalyticsResult CustomEvent(::StringW customEventName, ::System::Collections::Generic::IDictionary_2<::StringW, ::Il2CppObject*>* eventData); }; // UnityEngine.Analytics.Analytics #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::Analytics::Analytics::IsInitialized // Il2CppName: IsInitialized template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&UnityEngine::Analytics::Analytics::IsInitialized)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::Analytics::Analytics*), "IsInitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::Analytics::Analytics::SendCustomEventName // Il2CppName: SendCustomEventName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Analytics::AnalyticsResult (*)(::StringW)>(&UnityEngine::Analytics::Analytics::SendCustomEventName)> { static const MethodInfo* get() { static auto* customEventName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Analytics::Analytics*), "SendCustomEventName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{customEventName}); } }; // Writing MetadataGetter for method: UnityEngine::Analytics::Analytics::SendCustomEvent // Il2CppName: SendCustomEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Analytics::AnalyticsResult (*)(::UnityEngine::Analytics::CustomEventData*)>(&UnityEngine::Analytics::Analytics::SendCustomEvent)> { static const MethodInfo* get() { static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.Analytics", "CustomEventData")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Analytics::Analytics*), "SendCustomEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData}); } }; // Writing MetadataGetter for method: UnityEngine::Analytics::Analytics::CustomEvent // Il2CppName: CustomEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Analytics::AnalyticsResult (*)(::StringW)>(&UnityEngine::Analytics::Analytics::CustomEvent)> { static const MethodInfo* get() { static auto* customEventName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Analytics::Analytics*), "CustomEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{customEventName}); } }; // Writing MetadataGetter for method: UnityEngine::Analytics::Analytics::CustomEvent // Il2CppName: CustomEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Analytics::AnalyticsResult (*)(::StringW, ::System::Collections::Generic::IDictionary_2<::StringW, ::Il2CppObject*>*)>(&UnityEngine::Analytics::Analytics::CustomEvent)> { static const MethodInfo* get() { static auto* customEventName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* eventData = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "IDictionary`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Object")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Analytics::Analytics*), "CustomEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{customEventName, eventData}); } };
#include "./include/AFSArchive.h" void AFSArchive::readHeader() { std::streampos back = r->tell(); r->seek(5); header = new awbHeader; header->offsetSize = r->readUInt8(); r->seek(8); header->fileCount = r->readUInt32LE(); header->alignment = r->readUInt32LE(); header->ids = new unsigned short[header->fileCount]; header->fileEndPoints = new unsigned int[header->fileCount + 1]; for (unsigned int i = 0; i < header->fileCount; i++) { header->ids[i] = r->readUInt16LE(); } for (unsigned int i = 0; i < header->fileCount + 1; i++) { header->fileEndPoints[i] = r->readUIntLE(header->offsetSize); } r->seek(back); } AFSArchive::AFSArchive(unsigned char * awb, unsigned int l) { r = new Reader(awb, l); r->seek(0); unsigned int t = r->readUInt32BE(); if (t != 0x41465332) { r->close(); delete r; throw "Not AWB file."; } length = l; readHeader(); files = new entryFile[header->fileCount]; for (unsigned int i = 0; i < header->fileCount; i++) { unsigned int tmp = header->fileEndPoints[i] % header->alignment; unsigned int start = (tmp == 0 ? header->fileEndPoints[i] / header->alignment : header->fileEndPoints[i] / header->alignment + 1) * header->alignment; unsigned int length = header->fileEndPoints[i + 1] - start; files[header->ids[i]].buf = new unsigned char[length]; files[header->ids[i]].length = length; files[header->ids[i]].id = header->ids[i]; std::streampos back = r->tell(); r->seek(start); r->read((char*)files[header->ids[i]].buf, length); r->seek(back); } r->close(); } AFSArchive::~AFSArchive() { delete r; for (unsigned int i = 0; i < header->fileCount; i++) { delete[] files[i].buf; } delete[] files; delete[] header->fileEndPoints; delete[] header->ids; delete header; }
#include <bits/stdc++.h> #define ll long long #define pb push_back #define pii pair<int,int> #define vi vector<int> #define vii vector<pii> #define mi map<int,int> #define mii map<pii,int> #define all(a) (a).begin(),(a).end() #define ff first #define ss second #define sz(x) (int)x.size() #define endl '\n' #define hell 1000000007 #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; int main(){ cin.tie(NULL); ios::sync_with_stdio(false); //insert code int n,target; cin>>n>>target; vi arr(n); rep(i,0,n)cin>>arr[i]; vector<ll>dp(target+1,INT_MAX); dp[0] = 0; rep(i,0,target+1){ rep(j,0,n){ if (i>=arr[j] && dp[i-arr[j]]!=INT_MAX)dp[i] = min(dp[i],1+dp[i-arr[j]]); } } cout<<(dp[target]==INT_MAX?-1:dp[target])<<endl; return 0; }
#include "neuron_utils.h" #include "bp_neuron_net.h" /************************************************************************ * bp neuron net ************************************************************************/ bpNeuronNet::bpNeuronNet(int numInputs, double learningRate) :mNumInputs(numInputs), mNumOutputs(0), mNumHiddenLayers(0), mLearningRate(learningRate), mErrorSum(9999) { } bpNeuronNet::~bpNeuronNet() { for (size_t i = 0; i < mNeuronLayers.size(); i++) { if (mNeuronLayers[i]) { delete mNeuronLayers[i]; } } //todo something } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// void bpNeuronNet::reset() { //for each layer for (int i = 0; i < mNumHiddenLayers + 1; ++i) { mNeuronLayers[i]->reset(); } mErrorSum = 9999; } void bpNeuronNet::addNeuronLayer(int numNeurons) { int numInputsPerNeuron = (mNeuronLayers.size() > 0) ? mNeuronLayers[mNumHiddenLayers]->mNumNeurons : mNumInputs; /** create a neuron layer */ mNeuronLayers.push_back(new neuronLayer(numNeurons, numInputsPerNeuron)); /** calculate the count of hidden layers */ mNumHiddenLayers = (mNeuronLayers.size() > 0) ? (mNeuronLayers.size() - 1) : 0; } /************************************************************************ * bp neuron net forward propagation ************************************************************************/ double bpNeuronNet::sigmoidActive(double activation, double response) { /** sigmoid function: f(x) = 1 /(1 + exp(-x)) */ return (1.0 / (1.0 + exp(-activation * response))); } void bpNeuronNet::updateNeuronLayer(neuronLayer& nl, const double inputs[]) { int numNeurons = nl.mNumNeurons; int numInputsPerNeuron = nl.mNumInputsPerNeuron; double* curOutActivations = nl.mOutActivations; //for each neuron for (int n = 0; n < numNeurons; ++n) { double* curWeights = nl.mWeights[n]; double netinput = 0; int k; //for each weight for (k = 0; k < numInputsPerNeuron; ++k) { //sum the weights x inputs netinput += curWeights[k] * inputs[k]; } //add in the bias netinput += curWeights[k] * BIAS; //The combined activation is first filtered through the sigmoid //function and a record is kept for each neuron curOutActivations[n] = sigmoidActive(netinput, ACTIVATION_RESPONSE); } } void bpNeuronNet::updateNeuronLayer(neuronLayer& nl, const int indexArray[], const size_t arraySize) { int numNeurons = nl.mNumNeurons; int numInputsPerNeuron = nl.mNumInputsPerNeuron; double* curOutActivations = nl.mOutActivations; //for each neuron for (int n = 0; n < numNeurons; ++n) { double* curWeights = nl.mWeights[n]; double netinput = 0; //for each weight for (size_t k = 0; k < arraySize; k++) { netinput += curWeights[indexArray[k]]; } //add in the bias netinput += curWeights[numInputsPerNeuron] * BIAS; //The combined activation is first filtered through the sigmoid //function and a record is kept for each neuron curOutActivations[n] = sigmoidActive(netinput, ACTIVATION_RESPONSE); } } void bpNeuronNet::process(const double inputs[], double* outputs[]) { for (int i = 0; i < mNumHiddenLayers + 1; i++) { updateNeuronLayer(*mNeuronLayers[i], inputs); inputs = mNeuronLayers[i]->mOutActivations; } *outputs = mNeuronLayers[mNumHiddenLayers]->mOutActivations; } void bpNeuronNet::process(const int indexArray[], const size_t arraySize, double* outputs[]) { updateNeuronLayer(*mNeuronLayers[0], indexArray, arraySize); double* inputs = mNeuronLayers[0]->mOutActivations; for (int i = 1; i < mNumHiddenLayers + 1; i++) { updateNeuronLayer(*mNeuronLayers[i], inputs); inputs = mNeuronLayers[i]->mOutActivations; } *outputs = mNeuronLayers[mNumHiddenLayers]->mOutActivations; } /************************************************************************ * bp neuron net back propagation ************************************************************************/ double bpNeuronNet::backActive(double x) { /** calculate the error value with * f(x) = x * (1 - x) is the derivatives of sigmoid active function */ return x * (1 - x); } void bpNeuronNet::trainUpdate(const double inputs[], const double targets[]) { for (int i = 0; i < mNumHiddenLayers + 1; i++) { updateNeuronLayer(*mNeuronLayers[i], inputs); inputs = mNeuronLayers[i]->mOutActivations; } /** get the activations of output layer */ neuronLayer& outLayer = *mNeuronLayers[mNumHiddenLayers]; double* outActivations = outLayer.mOutActivations; double* outErrors = outLayer.mOutErrors; int numNeurons = outLayer.mNumNeurons; mErrorSum = 0; /** update the out error of output neuron layer */ for (int i = 0; i < numNeurons; i++) { //double err = outActivations[i] - targets[i]; double err = targets[i] - outActivations[i]; outErrors[i] = err; /** update the SSE(Sum Squared Error). (when this value becomes lower than a * preset threshold we know the training is successful) */ mErrorSum += err * err; } } void bpNeuronNet::trainUpdate(const int indexArray[], const size_t arraySize, const double targets[]) { double* inputs; updateNeuronLayer(*mNeuronLayers[0], indexArray, arraySize); inputs = mNeuronLayers[0]->mOutActivations; for (int i = 1; i < mNumHiddenLayers + 1; i++) { updateNeuronLayer(*mNeuronLayers[i], inputs); inputs = mNeuronLayers[i]->mOutActivations; } /** get the activations of output layer */ neuronLayer& outLayer = *mNeuronLayers[mNumHiddenLayers]; double* outActivations = outLayer.mOutActivations; double* outErrors = outLayer.mOutErrors; int numNeurons = outLayer.mNumNeurons; mErrorSum = 0; /** update the out error of output neuron layer */ for (int i = 0; i < numNeurons; i++) { //double err = outActivations[i] - targets[i]; double err = targets[i] - outActivations[i]; outErrors[i] = err; /** update the SSE(Sum Squared Error). (when this value becomes lower than a * preset threshold we know the training is successful) */ mErrorSum += err * err; } } void bpNeuronNet::trainNeuronLayer(neuronLayer& nl, const double prevOutActivations[], double prevOutErrors[]) { int numNeurons = nl.mNumNeurons; int numInputsPerNeuron = nl.mNumInputsPerNeuron; double* curOutErrors = nl.mOutErrors; double* curOutActivations = nl.mOutActivations; /** for each neuron of current layer calculate the error and adjust weights accordingly */ for (int i = 0; i < numNeurons; i++) { double* curWeights = nl.mWeights[i]; double coi = curOutActivations[i]; /** calculate the error value with * f(x) = x * (1 - x) is the derivatives of sigmoid active function */ double err = curOutErrors[i] * backActive(coi); /** for each weight in this neuron calculate the new weight based * on the error signal and the learning rate */ int w; //for each weight up to but not including the bias for (w = 0; w < numInputsPerNeuron; w++) { /** update the output error of prev neuron layer */ if (prevOutErrors) /** because the input layer only have data, haven't other member */ { prevOutErrors[w] += curWeights[w] * err; } /** calculate the new weight based on the back propagation rules */ curWeights[w] += err * mLearningRate * prevOutActivations[w]; } /** and the bias for this neuron */ curWeights[w] += err * mLearningRate * BIAS; } } void bpNeuronNet::trainNeuronLayer(neuronLayer& nl, const int indexArray[], const size_t arraySize) { int numNeurons = nl.mNumNeurons; int numInputsPerNeuron = nl.mNumInputsPerNeuron; double* curOutErrors = nl.mOutErrors; double* curOutActivations = nl.mOutActivations; /** for each neuron of current layer calculate the error and adjust weights accordingly */ for (int i = 0; i < numNeurons; i++) { double* curWeights = nl.mWeights[i]; double coi = curOutActivations[i]; /** calculate the error value with * f(x) = x * (1 - x) is the derivatives of sigmoid active function */ double err = curOutErrors[i] * backActive(coi); /** for each weight in this neuron calculate the new weight based * on the error signal and the learning rate */ double deltaW = err * mLearningRate; //for each weight up to but not including the bias for (int w = 0; w < arraySize; w++) { /** calculate the new weight based on the back propagation rules */ curWeights[indexArray[w]] += deltaW; } /** and the bias for this neuron */ curWeights[numInputsPerNeuron] += err * mLearningRate * BIAS; } } bool bpNeuronNet::training(const double inputs[], const double targets[]) { const double* prevOutActivations = NULL; double* prevOutErrors = NULL; trainUpdate(inputs, targets); for (int i = mNumHiddenLayers; i >= 0; i--) { neuronLayer& curLayer = *mNeuronLayers[i]; /** get the out activation of prev layer or use inputs data */ if (i > 0) { neuronLayer& prev = *mNeuronLayers[(i - 1)]; prevOutActivations = prev.mOutActivations; prevOutErrors = prev.mOutErrors; memset(prevOutErrors, 0, prev.mNumNeurons * sizeof(double)); } else { prevOutActivations = inputs; prevOutErrors = NULL; } trainNeuronLayer(curLayer, prevOutActivations, prevOutErrors); } return true; } bool bpNeuronNet::training(const int indexArray[], const size_t arraySize, const double targets[]) { const double* prevOutActivations = NULL; double* prevOutErrors = NULL; trainUpdate(indexArray, arraySize, targets); for (int i = mNumHiddenLayers; i >= 0; i--) { neuronLayer& curLayer = *mNeuronLayers[i]; /** get the out activation of prev layer or use inputs data */ if (i > 0) { neuronLayer& prev = *mNeuronLayers[(i - 1)]; prevOutActivations = prev.mOutActivations; prevOutErrors = prev.mOutErrors; memset(prevOutErrors, 0, prev.mNumNeurons * sizeof(double)); trainNeuronLayer(curLayer, prevOutActivations, prevOutErrors); } else { trainNeuronLayer(curLayer, indexArray, arraySize); } } return true; }
/** * @file * @brief Potion and potion-like effects. **/ #include "AppHdr.h" #include "potion.h" #include <cstdio> #include <cstring> #include "cloud.h" #include "food.h" #include "godconduct.h" #include "hints.h" #include "itemname.h" #include "itemprop.h" #include "item_use.h" #include "message.h" #include "misc.h" #include "mutation.h" #include "player-stats.h" #include "prompt.h" #include "religion.h" #include "skill_menu.h" #include "spl-goditem.h" #include "stringutil.h" #include "transform.h" #include "xom.h" int _xom_factor(bool was_known); PotionEffect::PotionEffect(const potion_type pot) : potion_name(potion_type_name(pot)), kind(pot) { } bool PotionEffect::can_quaff(string *reason) const { return true; } bool PotionEffect::quaff(bool was_known) const { if (was_known && !check_known_quaff()) return false; effect(); return true; } bool PotionEffect::check_known_quaff() const { string reason; if (!can_quaff(&reason)) { mpr(reason); return false; } return true; } class PotionCuring : public PotionEffect { private: PotionCuring() : PotionEffect(POT_CURING) { } DISALLOW_COPY_AND_ASSIGN(PotionCuring); public: static const PotionCuring &instance() { static PotionCuring inst; return inst; } bool can_quaff(string *reason = nullptr) const override { // cure status effects if (you.duration[DUR_CONF] || you.duration[DUR_POISONING] || you.disease || player_rotted()) { return true; } // heal if (you.duration[DUR_DEATHS_DOOR]) { if (reason) *reason = "You can't heal while in Death's door."; return false; } if (!you.can_device_heal() || you.hp == you.hp_max && player_rotted() == 0) { if (reason) *reason = "You have no ailments to cure."; return false; } return true; } bool effect(bool=true, int=40, bool is_device = true) const override { const bool ddoor = you.duration[DUR_DEATHS_DOOR]; bool unrotted = false; if ((you.can_device_heal() || !is_device) && !ddoor || player_rotted()) { int amount = 5 + random2(7); if (is_device && !you.can_device_heal() && player_rotted()) { // Treat the effectiveness of rot removal as if the player // had two levels of MUT_NO_DEVICE_HEAL unrot_hp(div_rand_round(amount,3)); unrotted = true; } else { if (is_device) amount = you.scale_device_healing(amount); if (player_rotted()) unrotted = true; // Pay for rot right off the top. amount = unrot_hp(amount); inc_hp(amount); } } if (ddoor) mpr("You feel queasy."); else if (you.can_device_heal() || you.duration[DUR_POISONING] || you.duration[DUR_CONF] || unrotted) canned_msg(MSG_GAIN_HEALTH); else mpr("That felt strangely inert."); // need to redraw from yellow to green even if no hp was gained if (you.duration[DUR_POISONING]) you.redraw_hit_points = true; you.duration[DUR_POISONING] = 0; you.disease = 0; you.duration[DUR_CONF] = 0; return true; } }; class PotionHealWounds : public PotionEffect { private: PotionHealWounds() : PotionEffect(POT_HEAL_WOUNDS) { } DISALLOW_COPY_AND_ASSIGN(PotionHealWounds); public: static const PotionHealWounds &instance() { static PotionHealWounds inst; return inst; } bool can_quaff(string *reason = nullptr) const override { if (!you.can_device_heal()) { if (reason) *reason = "That would not heal you."; return false; } if (you.duration[DUR_DEATHS_DOOR]) { if (reason) *reason = "You cannot heal while in Death's door!"; return false; } if (you.hp == you.hp_max && player_rotted() == 0) { if (reason) *reason = "Your health is already full!"; return false; } return true; } bool effect(bool=true, int=40, bool is_device = true) const override { if (you.duration[DUR_DEATHS_DOOR]) { mpr("You feel queasy."); return false; } if (!you.can_device_heal() && is_device) { mpr("That seemed strangely inert."); return false; } int amount = 10 + random2avg(28, 3); if (is_device) amount = you.scale_device_healing(amount); // Pay for rot right off the top. amount = unrot_hp(amount); inc_hp(amount); mpr("You feel much better."); return true; } }; /** * Return a message for the player drinking blood when a non-vampire. */ static string _blood_flavour_message() { if (player_mutation_level(MUT_HERBIVOROUS) < 3 && player_likes_chunks()) return "This tastes like blood."; return "Yuck - this tastes like blood."; } static bool _prompt_quaff_blood() { if (is_good_god(you.religion) && !yesno("Really drink that potion of blood?", false, 'n')) { canned_msg(MSG_OK); return false; } return true; } class PotionBlood : public PotionEffect { private: PotionBlood() : PotionEffect(POT_BLOOD) { } DISALLOW_COPY_AND_ASSIGN(PotionBlood); public: static const PotionBlood &instance() { static PotionBlood inst; return inst; } bool effect(bool=true, int pow = 40, bool=true) const override { if (you.species == SP_VAMPIRE) { mpr("Yummy - fresh blood!"); lessen_hunger(pow, true); } else mpr(_blood_flavour_message()); // no actual effect, just 'flavour' ha ha ha return true; } bool can_quaff(string *reason = nullptr) const override { if (you.hunger_state == HS_ENGORGED) { if (reason) *reason = "You are much too full right now."; return false; } return true; } bool quaff(bool was_known) const override { if (was_known && (!check_known_quaff() || !_prompt_quaff_blood())) return false; effect(was_known, 1040); did_god_conduct(DID_DRINK_BLOOD, 1 + random2(3), was_known); return true; } }; class PotionHaste : public PotionEffect { private: PotionHaste() : PotionEffect(POT_HASTE) { } DISALLOW_COPY_AND_ASSIGN(PotionHaste); public: static const PotionHaste &instance() { static PotionHaste inst; return inst; } bool can_quaff(string *reason = nullptr) const override { if (you.stasis(false)) { if (reason) *reason = NO_HASTE_MSG; return false; } return true; } bool effect(bool=true, int pow = 40, bool=true) const override { return haste_player(40 + random2(pow)); } bool quaff(bool was_known) const override { if (was_known && !check_known_quaff()) return false; if (effect()) did_god_conduct(DID_HASTY, 10, was_known); return true; } }; class PotionMight : public PotionEffect { private: PotionMight() : PotionEffect(POT_MIGHT) { } DISALLOW_COPY_AND_ASSIGN(PotionMight); public: static const PotionMight &instance() { static PotionMight inst; return inst; } bool effect(bool=true, int pow = 40, bool=true) const override { const bool were_mighty = you.duration[DUR_MIGHT] > 0; mprf(MSGCH_DURATION, "You feel %s all of a sudden.", were_mighty ? "mightier" : "very mighty"); you.increase_duration(DUR_MIGHT, 35 + random2(pow), 80); if (!were_mighty) notify_stat_change(STAT_STR, 5, true); return true; } }; class PotionBrilliance : public PotionEffect { private: PotionBrilliance() : PotionEffect(POT_BRILLIANCE) { } DISALLOW_COPY_AND_ASSIGN(PotionBrilliance); public: static const PotionBrilliance &instance() { static PotionBrilliance inst; return inst; } bool effect(bool=true, int pow = 40, bool=true) const override { const bool were_brilliant = you.duration[DUR_BRILLIANCE] > 0; mprf(MSGCH_DURATION, "You feel %s all of a sudden.", were_brilliant ? "more clever" : "clever"); you.increase_duration(DUR_BRILLIANCE, 35 + random2(pow), 80); if (!were_brilliant) notify_stat_change(STAT_INT, 5, true); return true; } }; class PotionAgility : public PotionEffect { private: PotionAgility() : PotionEffect(POT_AGILITY) { } DISALLOW_COPY_AND_ASSIGN(PotionAgility); public: static const PotionAgility &instance() { static PotionAgility inst; return inst; } bool effect(bool=true, int pow = 40, bool=true) const override { const bool were_agile = you.duration[DUR_AGILITY] > 0; mprf(MSGCH_DURATION, "You feel %s all of a sudden.", were_agile ? "more agile" : "agile"); you.increase_duration(DUR_AGILITY, 35 + random2(pow), 80); if (!were_agile) notify_stat_change(STAT_DEX, 5, true); return true; } }; class PotionFlight : public PotionEffect { private: PotionFlight() : PotionEffect(POT_FLIGHT) { } DISALLOW_COPY_AND_ASSIGN(PotionFlight); public: static const PotionFlight &instance() { static PotionFlight inst; return inst; } bool can_quaff(string *reason = nullptr) const override { if (!flight_allowed(true, reason)) { if (reason) *reason = "You cannot fly right now."; return false; } return true; } bool effect(bool=true, int pow = 40, bool=true) const override { you.attribute[ATTR_FLIGHT_UNCANCELLABLE] = 1; fly_player(pow); return you.airborne(); } }; #if TAG_MAJOR_VERSION == 34 class PotionPoison : public PotionEffect { private: PotionPoison() : PotionEffect(POT_POISON) { } DISALLOW_COPY_AND_ASSIGN(PotionPoison); public: static const PotionPoison &instance() { static PotionPoison inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { mprf(MSGCH_WARN, "That liquid tasted very nasty..."); return poison_player(10 + random2avg(15, 2), "", "a potion of poison"); } bool quaff(bool was_known) const override { if (player_res_poison() >= 1) mpr("You feel slightly nauseous."); else if (effect(was_known)) xom_is_stimulated(100 / _xom_factor(was_known)); return true; } }; #endif class PotionCancellation : public PotionEffect { private: PotionCancellation() : PotionEffect(POT_CANCELLATION) { } DISALLOW_COPY_AND_ASSIGN(PotionCancellation); public: static const PotionCancellation &instance() { static PotionCancellation inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { debuff_player(); mpr("You feel magically purged."); return true; } }; class PotionAmbrosia : public PotionEffect { private: PotionAmbrosia() : PotionEffect(POT_AMBROSIA) { } DISALLOW_COPY_AND_ASSIGN(PotionAmbrosia); public: static const PotionAmbrosia &instance() { static PotionAmbrosia inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { const int ambrosia_turns = 3 + random2(8); if (confuse_player(ambrosia_turns, false, true)) { mprf("You feel%s invigorated.", you.duration[DUR_AMBROSIA] ? " more" : ""); you.increase_duration(DUR_AMBROSIA, ambrosia_turns); return true; } mpr("You feel briefly invigorated."); return false; } }; class PotionInvisibility : public PotionEffect { private: PotionInvisibility() : PotionEffect(POT_INVISIBILITY) { } DISALLOW_COPY_AND_ASSIGN(PotionInvisibility); public: static const PotionInvisibility &instance() { static PotionInvisibility inst; return inst; } bool effect(bool=true, int pow = 40, bool=true) const override { if (you.backlit()) { vector<const char *> afflictions; if (you.haloed() && !you.umbraed()) afflictions.push_back("halo"); if (get_contamination_level() > 1) afflictions.push_back("magical contamination"); if (you.duration[DUR_CORONA]) afflictions.push_back("corona"); if (you.duration[DUR_LIQUID_FLAMES]) afflictions.push_back("liquid flames"); if (you.duration[DUR_QUAD_DAMAGE]) afflictions.push_back("!!!QUAD DAMAGE!!!"); mprf(MSGCH_DURATION, "You become %stransparent, but the glow from %s " "%s prevents you from becoming completely invisible.", you.duration[DUR_INVIS] ? "more " : "", you.haloed() && you.halo_radius() == -1 ? "the" : "your", comma_separated_line(afflictions.begin(), afflictions.end()).c_str()); } else { mprf(MSGCH_DURATION, !you.duration[DUR_INVIS] ? "You fade into invisibility!" : "You fade further into invisibility."); } // Now multiple invisiblity casts aren't as good. -- bwr if (!you.duration[DUR_INVIS]) you.set_duration(DUR_INVIS, 15 + random2(pow), 100); else you.increase_duration(DUR_INVIS, random2(pow), 100); return true; } bool can_quaff(string *reason = nullptr) const override { return invis_allowed(true, reason); } bool quaff(bool was_known) const override { // Let invis_allowed print the messages and possibly do a prompt. if (was_known && !invis_allowed()) return false; effect(); you.attribute[ATTR_INVIS_UNCANCELLABLE] = 1; return true; } }; class PotionExperience : public PotionEffect { private: PotionExperience() : PotionEffect(POT_EXPERIENCE) { } DISALLOW_COPY_AND_ASSIGN(PotionExperience); public: static const PotionExperience &instance() { static PotionExperience inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { if (you.experience_level < you.get_max_xl()) { mpr("You feel more experienced!"); // Defer calling level_change() until later in drink() to prevent // SIGHUP abuse. adjust_level(1, true); } else mpr("A flood of memories washes over you."); // these are included in default force_more_message skill_menu(SKMF_EXPERIENCE, 750 * you.experience_level); return true; } }; class PotionMagic : public PotionEffect { private: PotionMagic() : PotionEffect(POT_MAGIC) { } DISALLOW_COPY_AND_ASSIGN(PotionMagic); public: static const PotionMagic &instance() { static PotionMagic inst; return inst; } bool can_quaff(string *reason = nullptr) const override { #if TAG_MAJOR_VERSION == 34 if (you.species == SP_DJINNI) return PotionHealWounds::instance().can_quaff(reason); #endif if (you.magic_points == you.max_magic_points) { if (reason) *reason = "Your magic is already full."; return false; } return true; } bool effect(bool=true, int pow = 40, bool=true) const override { #if TAG_MAJOR_VERSION == 34 // Allow repairing rot, disallow going through Death's Door. if (you.species == SP_DJINNI && PotionHealWounds::instance().can_quaff()) { return PotionHealWounds::instance().effect(pow); } #endif inc_mp(POT_MAGIC_MP); mpr("Magic courses through your body."); return true; } }; class PotionBerserk : public PotionEffect { private: PotionBerserk() : PotionEffect(POT_BERSERK_RAGE) { } DISALLOW_COPY_AND_ASSIGN(PotionBerserk); public: static const PotionBerserk &instance() { static PotionBerserk inst; return inst; } bool can_quaff(string *reason = nullptr) const override { return you.can_go_berserk(true, true, true, reason); } bool effect(bool was_known = true, int pow = 40, bool=true) const override { if (you.species == SP_VAMPIRE && you.hunger_state <= HS_SATIATED) { mpr("You feel slightly irritated."); return false; } you.go_berserk(was_known, true); return true; } bool quaff(bool was_known) const override { if (was_known && (!check_known_quaff() || !berserk_check_wielded_weapon())) { return false; } if (effect(was_known)) xom_is_stimulated(50); return true; } }; /** * Is the player unable to mutate (temporarily or permanently) & thus unable * to drink a mutation-causing potion? * @param reason Pointer to a string where the reason will be stored if unable * to mutate * @returns True if the player is able to mutate now. */ static bool _disallow_mutate(string *reason) { if (!undead_mutation_rot()) return false; if (reason) { *reason = make_stringf("You cannot mutate%s.", !you.undead_state(false) ? " at present" : ""); } return true; } class PotionCureMutation : public PotionEffect { private: PotionCureMutation() : PotionEffect(POT_CURE_MUTATION) { } DISALLOW_COPY_AND_ASSIGN(PotionCureMutation); public: static const PotionCureMutation &instance() { static PotionCureMutation inst; return inst; } bool can_quaff(string *reason = nullptr) const override { if (_disallow_mutate(reason)) return false; if (!how_mutated(false, false, false)) { if (reason) { *reason = make_stringf("You have no %smutations to cure!", how_mutated(false, false, true) ? "permanent " : ""); } return false; } return true; } bool quaff(bool was_known) const override { if (was_known && !check_known_quaff()) return false; if (was_known && how_mutated(false, true) > how_mutated(false, true, false) && !yesno("Your transient mutations will not be cured; Quaff anyway?", false, 'n')) { canned_msg(MSG_OK); return false; } effect(); return true; } bool effect(bool=true, int=40, bool=true) const override { mpr("It has a very clean taste."); bool mutated = false; for (int i = 0; i < 7; i++) { if (random2(9) >= i) { mutated |= delete_mutation(RANDOM_MUTATION, "potion of cure mutation", false); } } return mutated; } }; class PotionMutation : public PotionEffect { private: PotionMutation() : PotionEffect(POT_MUTATION) { } DISALLOW_COPY_AND_ASSIGN(PotionMutation); public: static const PotionMutation &instance() { static PotionMutation inst; return inst; } bool can_quaff(string *reason = nullptr) const override { if (_disallow_mutate(reason)) return false; return true; } bool effect(bool=true, int=40, bool=true) const override { mpr("You feel extremely strange."); bool mutated = false; for (int i = 0; i < 3; i++) mutated |= mutate(RANDOM_MUTATION, "potion of mutation", false); learned_something_new(HINT_YOU_MUTATED); return mutated; } bool quaff(bool was_known) const override { if (was_known && !check_known_quaff()) return false; string msg = "Really drink that potion of mutation"; msg += you.rmut_from_item() ? " while resistant to mutation?" : "?"; if (was_known && (you_worship(GOD_ZIN) || you.rmut_from_item()) && !yesno(msg.c_str(), false, 'n')) { canned_msg(MSG_OK); return false; } effect(); // Zin conduct is violated even if you get lucky and don't mutate did_god_conduct(DID_DELIBERATE_MUTATING, 10, was_known); return true; } }; class PotionBeneficialMutation : public PotionEffect { private: PotionBeneficialMutation() : PotionEffect(POT_BENEFICIAL_MUTATION) { } DISALLOW_COPY_AND_ASSIGN(PotionBeneficialMutation); public: static const PotionBeneficialMutation &instance() { static PotionBeneficialMutation inst; return inst; } bool can_quaff(string *reason = nullptr) const override { if (_disallow_mutate(reason)) return false; return true; } bool effect(bool = true, int = 40, bool=true) const override { const bool mutated = mutate(RANDOM_GOOD_MUTATION, "potion of beneficial mutation", true, false, false, true); if (undead_mutation_rot()) { mpr("You feel dead inside."); return mutated; } if (mutated) mpr("You feel fantastic!"); else mpr("You feel fantastic for a moment."); learned_something_new(HINT_YOU_MUTATED); return mutated; } bool quaff(bool was_known) const override { if (was_known && !check_known_quaff()) return false; // Beneficial mutations go rMut, so don't prompt in this case. if (was_known && you_worship(GOD_ZIN) && !yesno("Really drink that potion of beneficial mutation?", false, 'n')) { canned_msg(MSG_OK); return false; } effect(was_known); // Zin conduct is violated even if you get lucky and don't mutate did_god_conduct(DID_DELIBERATE_MUTATING, 10, was_known); return true; } }; class PotionResistance : public PotionEffect { private: PotionResistance() : PotionEffect(POT_RESISTANCE) { } DISALLOW_COPY_AND_ASSIGN(PotionResistance); public: static const PotionResistance &instance() { static PotionResistance inst; return inst; } bool effect(bool=true, int pow = 40, bool=true) const override { mprf(MSGCH_DURATION, "You feel protected."); you.increase_duration(DUR_RESISTANCE, random2(pow) + 35); return true; } }; class PotionLignify : public PotionEffect { private: PotionLignify() : PotionEffect(POT_LIGNIFY) { } DISALLOW_COPY_AND_ASSIGN(PotionLignify); public: static const PotionLignify &instance() { static PotionLignify inst; return inst; } bool can_quaff(string *reason = nullptr) const override { return transform(0, TRAN_TREE, false, true, reason); } bool effect(bool was_known = true, int=40, bool=true) const override { return transform(30, TRAN_TREE, !was_known); } bool quaff(bool was_known) const override { if (was_known) { if (!check_known_quaff() || !check_form_stat_safety(TRAN_TREE)) return false; const cloud_type cloud = cloud_type_at(you.pos()); if (is_damaging_cloud(cloud, false) // Tree form is immune to these two. && cloud != CLOUD_MEPHITIC && cloud != CLOUD_POISON && !yesno(make_stringf("Really become a tree while standing in " "a cloud of %s?", cloud_type_name(cloud).c_str()).c_str(), false, 'n')) { canned_msg(MSG_OK); return false; } } if (effect(was_known)) { you.transform_uncancellable = true; did_god_conduct(DID_CHAOS, 10, was_known); } else mpr("You feel woody for a moment."); return true; } }; // Removed potions #if TAG_MAJOR_VERSION == 34 class PotionDecay : public PotionEffect { private: PotionDecay() : PotionEffect(POT_DECAY) { } DISALLOW_COPY_AND_ASSIGN(PotionDecay); public: static const PotionDecay &instance() { static PotionDecay inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { return you.rot(&you, 3 + random2(3));; } bool quaff(bool was_known) const override { if (effect()) xom_is_stimulated( 50 / _xom_factor(was_known)); return true; } }; class PotionBloodCoagulated : public PotionEffect { private: PotionBloodCoagulated() : PotionEffect(POT_BLOOD_COAGULATED) { } DISALLOW_COPY_AND_ASSIGN(PotionBloodCoagulated); public: static const PotionBloodCoagulated &instance() { static PotionBloodCoagulated inst; return inst; } bool effect(bool=true, int pow = 40, bool=true) const override { if (you.species == SP_VAMPIRE) { mpr("This tastes delicious."); lessen_hunger(pow, true); } else mpr(_blood_flavour_message()); // no actual effect, just 'flavour' ha ha ha return true; } bool can_quaff(string *reason = nullptr) const override { if (you.hunger_state == HS_ENGORGED) { *reason = "You are much too full right now."; return false; } return true; } bool quaff(bool was_known) const override { if (was_known && (!check_known_quaff() || !_prompt_quaff_blood())) return false; effect(was_known, 840); did_god_conduct(DID_DRINK_BLOOD, 1 + random2(3), was_known); return true; } }; class PotionGainStrength : public PotionEffect { private: PotionGainStrength() : PotionEffect(POT_GAIN_STRENGTH) { } DISALLOW_COPY_AND_ASSIGN(PotionGainStrength); public: static const PotionGainStrength &instance() { static PotionGainStrength inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { return mutate(MUT_STRONG, "potion of gain strength", true, false, false, true); } bool quaff(bool was_known) const override { if (was_known && !check_known_quaff()) return false; if (effect()) learned_something_new(HINT_YOU_MUTATED); return true; } }; class PotionGainDexterity : public PotionEffect { private: PotionGainDexterity() : PotionEffect(POT_GAIN_DEXTERITY) { } DISALLOW_COPY_AND_ASSIGN(PotionGainDexterity); public: static const PotionGainDexterity &instance() { static PotionGainDexterity inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { return mutate(MUT_AGILE, "potion of gain dexterity", true, false, false, true); } bool quaff(bool was_known) const override { if (was_known && !check_known_quaff()) return false; if (effect()) learned_something_new(HINT_YOU_MUTATED); return true; } }; class PotionGainIntelligence : public PotionEffect { private: PotionGainIntelligence() : PotionEffect(POT_GAIN_INTELLIGENCE) { } DISALLOW_COPY_AND_ASSIGN(PotionGainIntelligence); public: static const PotionGainIntelligence &instance() { static PotionGainIntelligence inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { return mutate(MUT_STRONG, "potion of gain intelligence", true, false, false, true); } bool quaff(bool was_known) const override { if (was_known && !check_known_quaff()) return false; if (effect()) learned_something_new(HINT_YOU_MUTATED); return true; } }; class PotionPorridge : public PotionEffect { private: PotionPorridge() : PotionEffect(POT_PORRIDGE) { } DISALLOW_COPY_AND_ASSIGN(PotionPorridge); public: static const PotionPorridge &instance() { static PotionPorridge inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { if (you.species == SP_VAMPIRE || player_mutation_level(MUT_CARNIVOROUS) == 3) { mpr("Blech - that potion was really gluggy!"); } else { mpr("That potion was really gluggy!"); lessen_hunger(6000, true); } return true; } bool can_quaff(string *reason) const override { if (you.hunger_state == HS_ENGORGED) { if (reason) *reason = "You are much too full right now."; return false; } return true; } }; class PotionWater : public PotionEffect { private: PotionWater() : PotionEffect(POT_WATER) { } DISALLOW_COPY_AND_ASSIGN(PotionWater); public: static const PotionWater &instance() { static PotionWater inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { mpr("This tastes like water."); return true; } }; class PotionSlowing : public PotionEffect { private: PotionSlowing() : PotionEffect(POT_SLOWING) { } DISALLOW_COPY_AND_ASSIGN(PotionSlowing); public: static const PotionSlowing &instance() { static PotionSlowing inst; return inst; } bool can_quaff(string *reason = nullptr) const override { if (you.stasis(false)) { if (reason) *reason = "This potion cannot work under stasis."; return false; } return true; } bool effect(bool=true, int pow = 40, bool=true) const override { return slow_player(10 + random2(pow)); } }; class PotionRestoreAbilities : public PotionEffect { private: PotionRestoreAbilities() : PotionEffect(POT_RESTORE_ABILITIES) { } DISALLOW_COPY_AND_ASSIGN(PotionRestoreAbilities); public: static const PotionRestoreAbilities &instance() { static PotionRestoreAbilities inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { bool nothing_happens = true; if (you.duration[DUR_BREATH_WEAPON]) { mprf(MSGCH_RECOVERY, "You have got your breath back."); you.duration[DUR_BREATH_WEAPON] = 0; nothing_happens = false; } // Give a message if no message otherwise. if (!restore_stat(STAT_ALL, 0, false) && nothing_happens) mpr("You feel refreshed."); return nothing_happens; } }; #endif class PotionDegeneration : public PotionEffect { private: PotionDegeneration() : PotionEffect(POT_DEGENERATION) { } DISALLOW_COPY_AND_ASSIGN(PotionDegeneration); public: static const PotionDegeneration &instance() { static PotionDegeneration inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { mpr("There was something very wrong with that liquid."); bool success = false; for (int i = 0; i < NUM_STATS; ++i) if (lose_stat(static_cast<stat_type>(i), 1 + random2(3))) success = true; return success; } bool quaff(bool was_known) const override { if (effect()) xom_is_stimulated( 50 / _xom_factor(was_known)); return true; } }; // placeholder 'buggy' potion class PotionStale : public PotionEffect { private: PotionStale() : PotionEffect(NUM_POTIONS) { } DISALLOW_COPY_AND_ASSIGN(PotionStale); public: static const PotionStale &instance() { static PotionStale inst; return inst; } bool effect(bool=true, int=40, bool=true) const override { mpr("That potion was far past its expiry date."); return true; } }; static const PotionEffect* potion_effects[] = { &PotionCuring::instance(), &PotionHealWounds::instance(), &PotionHaste::instance(), &PotionMight::instance(), &PotionBrilliance::instance(), &PotionAgility::instance(), #if TAG_MAJOR_VERSION == 34 &PotionGainStrength::instance(), &PotionGainDexterity::instance(), &PotionGainIntelligence::instance(), #endif &PotionFlight::instance(), #if TAG_MAJOR_VERSION == 34 &PotionPoison::instance(), &PotionSlowing::instance(), #endif &PotionCancellation::instance(), &PotionAmbrosia::instance(), &PotionInvisibility::instance(), #if TAG_MAJOR_VERSION == 34 &PotionPorridge::instance(), #endif &PotionDegeneration::instance(), #if TAG_MAJOR_VERSION == 34 &PotionDecay::instance(), &PotionWater::instance(), #endif &PotionExperience::instance(), &PotionMagic::instance(), #if TAG_MAJOR_VERSION == 34 &PotionRestoreAbilities::instance(), &PotionPoison::instance(), #endif &PotionBerserk::instance(), &PotionCureMutation::instance(), &PotionMutation::instance(), &PotionResistance::instance(), &PotionBlood::instance(), #if TAG_MAJOR_VERSION == 34 &PotionBloodCoagulated::instance(), #endif &PotionLignify::instance(), &PotionBeneficialMutation::instance(), &PotionStale::instance() }; const PotionEffect* get_potion_effect(potion_type pot) { COMPILE_CHECK(ARRAYSZ(potion_effects) == NUM_POTIONS+1); ASSERT_RANGE(pot, 0, NUM_POTIONS+1); return potion_effects[pot]; } /** * Quaff a potion, identifying it if appropriate & triggering its effects on * the player. Does not handle decrementing item quantities. * * @param potion The potion (stack) being quaffed. * @return true if the potion was used; false if the player aborted. */ bool quaff_potion(item_def &potion) { const bool was_known = item_type_known(potion); if (!was_known) { set_ident_flags(potion, ISFLAG_IDENT_MASK); set_ident_type(potion, true); mprf("It was a %s.", potion.name(DESC_QUALNAME).c_str()); } const potion_type ptyp = static_cast<potion_type>(potion.sub_type); return get_potion_effect(ptyp)->quaff(was_known); } /** * Trigger an effect on the player corresponding to the given potion type. * * @param effect The type of potion in question. * @param pow The power of the effect. (Only relevant for some pots.) * @param was_known Whether the player should be held responsible. * @param is_device Whether to apply the effects of MUT_NO_DEVICE_HEAL. */ void potionlike_effect(potion_type effect, int pow, bool was_known, bool is_device) { get_potion_effect(effect)->effect(was_known, pow, is_device); } int _xom_factor(bool was_known) { // Knowingly drinking bad potions is much less amusing. int xom_factor = 1; if (was_known) { xom_factor *= 2; if (!player_in_a_dangerous_place()) xom_factor *= 3; } return xom_factor; }
// -*- C++ -*- // // $Id$ // **** Code generated by the The ACE ORB (TAO) IDL Compiler **** // TAO and the TAO IDL Compiler have been developed by: // Center for Distributed Object Computing // Washington University // St. Louis, MO // USA // http://www.cs.wustl.edu/~schmidt/doc-center.html // and // Distributed Object Computing Laboratory // University of California at Irvine // Irvine, CA // USA // http://doc.ece.uci.edu/ // and // Institute for Software Integrated Systems // Vanderbilt University // Nashville, TN // USA // http://www.isis.vanderbilt.edu/ // // Information about TAO is available at: // http://www.cs.wustl.edu/~schmidt/TAO.html // TAO_IDL - Generated from // ../../../TAO/TAO_IDL/be/be_visitor_interface/interface_ci.cpp:70 #if !defined (_SESSION_SESSION_I___CI_) #define _SESSION_SESSION_I___CI_ ACE_INLINE session::Session_I::Session_I ( TAO_Stub *objref, ::CORBA::Boolean _tao_collocated, TAO_Abstract_ServantBase *servant, TAO_ORB_Core *oc ) : ::CORBA::Object (objref, _tao_collocated, servant, oc), the_TAO_Session_I_Proxy_Broker_ (0) { this->session_Session_I_setup_collocation (); } ACE_INLINE session::Session_I::Session_I ( IOP::IOR *ior, TAO_ORB_Core *oc ) : ::CORBA::Object (ior, oc), the_TAO_Session_I_Proxy_Broker_ (0) { } #endif /* end #if !defined */
//==-------- kernel_info.cpp - SYCL kernel info methods --------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <CL/sycl/device.hpp> #include <detail/kernel_info.hpp> __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { namespace detail { template <> cl::sycl::range<3> get_kernel_work_group_info_host<info::kernel_work_group::global_work_size>( const cl::sycl::device &Dev) { throw invalid_object_error("This instance of kernel is a host instance"); } template <> size_t get_kernel_work_group_info_host<info::kernel_work_group::work_group_size>( const cl::sycl::device &Dev) { return Dev.get_info<info::device::max_work_group_size>(); } template <> cl::sycl::range<3> get_kernel_work_group_info_host< info::kernel_work_group::compile_work_group_size>( const cl::sycl::device &Dev) { return {0, 0, 0}; } template <> size_t get_kernel_work_group_info_host< info::kernel_work_group::preferred_work_group_size_multiple>( const cl::sycl::device &Dev) { return get_kernel_work_group_info_host< info::kernel_work_group::work_group_size>(Dev); } template <> cl_ulong get_kernel_work_group_info_host<info::kernel_work_group::private_mem_size>( const cl::sycl::device &Dev) { return 0; } } // namespace detail } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl)
/*++ Copyright (c) Microsoft Corporation Licensed under the MIT license. Module Name: - IConsoleInputThread.hpp Abstract: - Defines methods that wrap the thread that reads input from the keyboard and feeds it into the console's input buffer. Author(s): - Hernan Gatta (HeGatta) 29-Mar-2017 --*/ #pragma once namespace Microsoft::Console::Interactivity { class IConsoleInputThread { public: virtual ~IConsoleInputThread() = 0; virtual HANDLE Start() = 0; HANDLE GetHandle() { return _hThread; } DWORD GetThreadId() { return _dwThreadId; } protected: // Prevent accidental copies. IConsoleInputThread(IConsoleInputThread const&) = delete; IConsoleInputThread& operator=(IConsoleInputThread const&) = delete; // .ctor IConsoleInputThread() : _hThread(nullptr), _dwThreadId((DWORD)(-1)) { } // Protected Variables HANDLE _hThread; DWORD _dwThreadId; }; inline IConsoleInputThread::~IConsoleInputThread() {} }
/********************************************************************** Audacity: A Digital Audio Editor Track.cpp Dominic Mazzoni *******************************************************************//** \class Track \brief Fundamental data object of Audacity, placed in the TrackPanel. Classes derived form it include the WaveTrack, NoteTrack, LabelTrack and TimeTrack. *//*******************************************************************/ #include <algorithm> #include <numeric> #include <float.h> #include <wx/file.h> #include <wx/textfile.h> #include <wx/log.h> #include "Track.h" #include "TimeTrack.h" #include "WaveTrack.h" #include "NoteTrack.h" #include "LabelTrack.h" #include "Project.h" #include "DirManager.h" #include "Experimental.h" #ifdef _MSC_VER //Disable truncation warnings #pragma warning( disable : 4786 ) #endif #ifdef __WXDEBUG__ // if we are in a debug build of audacity /// Define this to do extended (slow) debuging of TrackListIterator // #define DEBUG_TLI #endif Track::Track(const std::shared_ptr<DirManager> &projDirManager) : vrulerSize(36,0), mDirManager(projDirManager) { mList = NULL; mSelected = false; mLinked = false; mMute = false; mSolo = false; mY = 0; mHeight = 150; mIndex = 0; #ifdef EXPERIMENTAL_OUTPUT_DISPLAY mYv = mHeight; mHeightv = mHeight; mPerY = 0.5; mVirtualStereo = false; #endif mMinimized = false; mOffset = 0.0; mChannel = MonoChannel; } Track::Track(const Track &orig) { mList = NULL; mY = 0; mIndex = 0; #ifdef EXPERIMENTAL_OUTPUT_DISPLAY mPerY = 0.5; #endif Init(orig); mOffset = orig.mOffset; } // Copy all the track properties except the actual contents void Track::Init(const Track &orig) { mDefaultName = orig.mDefaultName; mName = orig.mName; mDirManager = orig.mDirManager; mSelected = orig.mSelected; mLinked = orig.mLinked; mMute = orig.mMute; mSolo = orig.mSolo; mHeight = orig.mHeight; mMinimized = orig.mMinimized; mChannel = orig.mChannel; #ifdef EXPERIMENTAL_OUTPUT_DISPLAY mVirtualStereo = orig.mVirtualStereo; mHeightv = orig.mHeightv; mYv = orig.mYv; #endif } void Track::SetSelected(bool s) { mSelected = s; } void Track::Merge(const Track &orig) { mSelected = orig.mSelected; mMute = orig.mMute; mSolo = orig.mSolo; } Track::~Track() { } TrackNodePointer Track::GetNode() const { wxASSERT(mList == NULL || this == mNode->get()); return mNode; } // A track can only live on one list at a time, so if you're moving a // track from one list to another, you must call SetOwner() with NULL // pointers first and then with the real pointers. void Track::SetOwner(TrackList *list, TrackNodePointer node) { mList = list; mNode = node; } int Track::GetMinimizedHeight() const { if (GetLink()) { return 20; } return 40; } int Track::GetIndex() const { return mIndex; } void Track::SetIndex(int index) { mIndex = index; } #ifdef EXPERIMENTAL_OUTPUT_DISPLAY int Track::GetY(bool vStereo) const { if(vStereo && mChannel == Track::MonoChannel) return mYv; return mY; } void Track::SetY(int y, bool vStereo) { if(vStereo && mChannel == Track::MonoChannel) mYv = y; else mY = y; } int Track::GetHeight(bool vStereo) const { if (mMinimized) { return GetMinimizedHeight(); } if(vStereo && mChannel == Track::MonoChannel) return mHeightv; return mHeight; } void Track::SetHeight(int h, bool vStereo) { if(vStereo && mChannel == Track::MonoChannel) mHeightv = h; else mHeight = h; if (mList) { mList->RecalcPositions(mNode); mList->ResizedEvent(mNode); } } #else // EXPERIMENTAL_OUTPUT_DISPLAY int Track::GetY() const { return mY; } void Track::SetY(int y) { mY = y; } int Track::GetHeight() const { if (mMinimized) { return GetMinimizedHeight(); } return mHeight; } void Track::SetHeight(int h) { mHeight = h; if (mList) { mList->RecalcPositions(mNode); mList->ResizedEvent(mNode); } } #endif // EXPERIMENTAL_OUTPUT_DISPLAY bool Track::GetMinimized() const { return mMinimized; } void Track::SetMinimized(bool isMinimized) { mMinimized = isMinimized; if (mList) { mList->RecalcPositions(mNode); mList->ResizedEvent(mNode); } } void Track::SetLinked(bool l) { mLinked = l; if (mList) { mList->RecalcPositions(mNode); mList->ResizedEvent(mNode); } } Track *Track::GetLink() const { if (!mList) return nullptr; if (!mList->isNull(mNode)) { if (mLinked) { auto next = mNode; ++next; if (!mList->isNull(next)) { return next->get(); } } if (mList->hasPrev(mNode)) { auto prev = mNode; --prev; auto track = prev->get(); if (track && track->GetLinked()) { return track; } } } return nullptr; } #ifdef EXPERIMENTAL_OUTPUT_DISPLAY void Track::ReorderList(bool resize) { if (mList) { mList->RecalcPositions(mNode); if(resize) mList->ResizedEvent(mNode); } } #endif bool Track::IsSyncLockSelected() const { #ifdef EXPERIMENTAL_SYNC_LOCK AudacityProject *p = GetActiveProject(); if (!p || !p->IsSyncLocked()) return false; SyncLockedTracksIterator git(mList); Track *t = git.StartWith(const_cast<Track*>(this)); if (!t) { // Not in a sync-locked group. return ((this->GetKind() == Track::Wave) || (this->GetKind() == Track::Label)) && GetSelected(); } for (; t; t = git.Next()) { if (t->GetSelected()) return true; } #endif return false; } bool Track::SyncLockAdjust(double oldT1, double newT1) { if (newT1 > oldT1) { // Insert space within the track if (oldT1 > GetEndTime()) return true; auto tmp = Cut(oldT1, GetEndTime()); if (!tmp) return false; bool ret = Paste(newT1, tmp.get()); wxASSERT(ret); // TODO: handle this. return ret; } else if (newT1 < oldT1) { // Remove from the track return Clear(newT1, oldT1); } // fall-through: no change return true; } // TrackListIterator TrackListIterator::TrackListIterator(TrackList * val) : l(val) , cur{} { if (l) cur = l->begin(); } Track *TrackListIterator::StartWith(Track * val) { if (val == NULL) { return First(); } if (l == NULL) { return NULL; } if (val->mList == NULL) return nullptr; cur = val->GetNode(); return cur->get(); } Track *TrackListIterator::First(TrackList * val) { if (val != NULL) { l = val; } if (l == NULL) { return NULL; } cur = l->begin(); if (!l->isNull(cur)) { return cur->get(); } return NULL; } Track *TrackListIterator::Last(bool skiplinked) { if (l == NULL) { return NULL; } cur = l->end(); if (l->hasPrev(cur)) --cur; else return NULL; // With skiplinked set, we won't return the second channel of a linked pair if (skiplinked && l->hasPrev(cur) && !(*cur)->GetLinked() && (*cur)->GetLink()) --cur; return cur->get(); } Track *TrackListIterator::Next(bool skipLinked) { #ifdef DEBUG_TLI // if we are debugging this bit wxASSERT_MSG((!cur || (*l).Contains((*cur).t)), wxT("cur invalid at start of Next(). List changed since iterator created?")); // check that cur is in the list #endif if (!l || l->isNull(cur)) return nullptr; if (skipLinked && (*cur)->GetLinked()) { ++cur; } #ifdef DEBUG_TLI // if we are debugging this bit wxASSERT_MSG((!cur || (*l).Contains((*cur).t)), wxT("cur invalid after skipping linked tracks.")); // check that cur is in the list #endif if (!l->isNull(cur)) { ++cur; } #ifdef DEBUG_TLI // if we are debugging this bit wxASSERT_MSG((!cur || (*l).Contains((*cur).t)), wxT("cur invalid after moving to next track.")); // check that cur is in the list if it is not null #endif if (!l->isNull(cur)) { return cur->get(); } return NULL; } Track *TrackListIterator::Prev(bool skiplinked) { if (!l || l->isNull(cur)) return nullptr; if (!l->hasPrev(cur)) { l->setNull(cur); return nullptr; } --cur; if (skiplinked && l->hasPrev(cur)) { auto prev = cur; --prev; if ((*prev)->GetLinked()) cur = prev; } return cur->get(); } Track *TrackListIterator::RemoveCurrent() { if (!l || l->isNull(cur)) return nullptr; cur = l->Remove(cur->get()); #ifdef DEBUG_TLI // if we are debugging this bit wxASSERT_MSG((!cur || (*l).Contains((*cur).t)), wxT("cur invalid after deletion of track.")); // check that cur is in the list #endif if (!l->isNull(cur)) { return cur->get(); } return NULL; } // // TrackListCondIterator (base class for iterators that iterate over all tracks // that meet a condition) // Track *TrackListCondIterator::StartWith(Track *val) { Track *t = TrackListIterator::StartWith(val); if (t && !this->Condition(t)) return NULL; return t; } Track *TrackListCondIterator::First(TrackList *val) { Track *t = TrackListIterator::First(val); while (t && !this->Condition(t)) { t = TrackListIterator::Next(); } return t; } Track *TrackListCondIterator::Next(bool skiplinked) { while (Track *t = TrackListIterator::Next(skiplinked)) { if (this->Condition(t)) { return t; } } return NULL; } Track *TrackListCondIterator::Prev(bool skiplinked) { while (Track *t = TrackListIterator::Prev(skiplinked)) { if (this->Condition(t)) { return t; } } return NULL; } Track *TrackListCondIterator::Last(bool skiplinked) { Track *t = TrackListIterator::Last(skiplinked); while (t && !this->Condition(t)) { t = TrackListIterator::Prev(skiplinked); } return t; } // TrackListOfKindIterator TrackListOfKindIterator::TrackListOfKindIterator(int kind, TrackList * val) : TrackListCondIterator(val) { this->kind = kind; } bool TrackListOfKindIterator::Condition(Track *t) { return kind == Track::All || t->GetKind() == kind; } //SelectedTrackListOfKindIterator bool SelectedTrackListOfKindIterator::Condition(Track *t) { return TrackListOfKindIterator::Condition(t) && t->GetSelected(); } // VisibleTrackIterator // // Based on TrackListIterator returns only the currently visible tracks. // VisibleTrackIterator::VisibleTrackIterator(AudacityProject *project) : TrackListCondIterator(project->GetTracks()) { mProject = project; mPanelRect.SetTop(mProject->mViewInfo.vpos); mPanelRect.SetSize(mProject->GetTPTracksUsableArea()); } bool VisibleTrackIterator::Condition(Track *t) { wxRect r(0, t->GetY(), 1, t->GetHeight()); return r.Intersects(mPanelRect); } // SyncLockedTracksIterator // // Based on TrackListIterator returns only tracks belonging to the group // in which the starting track is a member. // SyncLockedTracksIterator::SyncLockedTracksIterator(TrackList * val) : TrackListIterator(val), mInLabelSection(false) { } namespace { bool IsSyncLockableNonLabelTrack( const Track *pTrack ) { if ( pTrack->GetKind() == Track::Wave ) return true; #ifdef USE_MIDI else if ( pTrack->GetKind() == Track::Note ) return true; #endif else return false; } } Track *SyncLockedTracksIterator::StartWith(Track * member) { Track *t = NULL; // A sync-locked group consists of any positive number of wave (or note) // tracks followed by any // non-negative number of label tracks. Step back through any label tracks, // and then through the wave tracks above them. while (member && member->GetKind() == Track::Label) { member = l->GetPrev(member); } while (member && IsSyncLockableNonLabelTrack(member)) { t = member; member = l->GetPrev(member); } // Make it current (if t is still NULL there are no wave tracks, so we're // not in a sync-locked group). if (t) cur = t->GetNode(); mInLabelSection = false; return t; } bool SyncLockedTracksIterator::IsGoodNextTrack(const Track *t) const { if (!t) return false; const bool isLabel = ( t->GetKind() == Track::Label ); const bool isSyncLockable = IsSyncLockableNonLabelTrack( t ); if ( !( isLabel || isSyncLockable ) ) { return false; } if (mInLabelSection && !isLabel) { return false; } return true; } Track *SyncLockedTracksIterator::Next(bool skiplinked) { Track *t = TrackListIterator::Next(skiplinked); if (!t) return NULL; if ( ! IsGoodNextTrack(t) ) { l->setNull(cur); return NULL; } mInLabelSection = ( t->GetKind() == Track::Label ); return t; } Track *SyncLockedTracksIterator::Prev(bool skiplinked) { Track *t = TrackListIterator::Prev(skiplinked); // // Ways to end a sync-locked group in reverse // // Beginning of tracks if (!t) return NULL; const bool isLabel = ( t->GetKind() == Track::Label ); const bool isSyncLockable = IsSyncLockableNonLabelTrack( t ); if ( !( isLabel || isSyncLockable ) ) { l->setNull(cur); return NULL; } if ( !mInLabelSection && isLabel ) { l->setNull(cur); return NULL; } mInLabelSection = isLabel; return t; } Track *SyncLockedTracksIterator::Last(bool skiplinked) { if (!l || l->isNull(cur)) return NULL; Track *t = cur->get(); while (const auto next = l->GetNext(t, skiplinked)) { if ( ! IsGoodNextTrack(next) ) break; t = Next(skiplinked); } return t; } // TrackList // // The TrackList sends itself events whenever an update occurs to the list it // is managing. Any other classes that may be interested in get these updates // should use TrackList::Connect() and TrackList::Disconnect(). // DEFINE_EVENT_TYPE(EVT_TRACKLIST_RESIZED); DEFINE_EVENT_TYPE(EVT_TRACKLIST_UPDATED); TrackList::TrackList() : wxEvtHandler() { } TrackList::TrackList(const TrackList &that) : ListOfTracks{} { DoAssign(that); } TrackList& TrackList::operator= (const TrackList &that) { if (this != &that) { this->Clear(); DoAssign(that); } return *this; } TrackList::TrackList(TrackList &&that) { Swap(that); } TrackList &TrackList::operator= (TrackList &&that) { if (this != &that) { this->Clear(); Swap(that); } return *this; } void TrackList::DoAssign(const TrackList &that) { TrackListConstIterator it(&that); for (const Track *track = it.First(); track; track = it.Next()) Add(track->Duplicate()); } void TrackList::Swap(TrackList &that) { ListOfTracks::swap(that); for (auto it = begin(), last = end(); it != last; ++it) (*it)->SetOwner(this, it); for (auto it = that.begin(), last = that.end(); it != last; ++it) (*it)->SetOwner(&that, it); } TrackList::~TrackList() { Clear(false); } void TrackList::RecalcPositions(TrackNodePointer node) { if (isNull(node)) { return; } Track *t; int i = 0; int y = 0; #ifdef EXPERIMENTAL_OUTPUT_DISPLAY int cnt = 0; if (node->prev) { t = node->prev->t; i = t->GetIndex() + 1; if(MONO_WAVE_PAN(t)) y = t->GetY(true) + t->GetHeight(true); else y = t->GetY() + t->GetHeight(); } for (const TrackListNode *n = node; n; n = n->next) { t = n->t; if(MONO_WAVE_PAN(t)) cnt++; if(cnt != 2){ t->SetIndex(i++); t->SetY(y); y += t->GetHeight(); } if(cnt != 0){ t->SetY(y,true); y += t->GetHeight(true); } cnt = 0; } #else // EXPERIMENTAL_OUTPUT_DISPLAY if (hasPrev(node)) { auto prev = node; --prev; t = prev->get(); i = t->GetIndex() + 1; y = t->GetY() + t->GetHeight(); } const auto theEnd = end(); for (auto n = node; n != theEnd; ++n) { t = n->get(); t->SetIndex(i++); t->SetY(y); y += t->GetHeight(); } #endif // EXPERIMENTAL_OUTPUT_DISPLAY } void TrackList::UpdatedEvent(TrackNodePointer node) { wxCommandEvent e(EVT_TRACKLIST_UPDATED); if (!isNull(node)) { e.SetClientData(node->get()); } else { e.SetClientData(NULL); } ProcessEvent(e); } void TrackList::ResizedEvent(TrackNodePointer node) { if (!isNull(node)) { wxCommandEvent e(EVT_TRACKLIST_RESIZED); e.SetClientData(node->get()); ProcessEvent(e); } } void TrackList::Permute(const std::vector<TrackNodePointer> &permutation) { for (const auto iter : permutation) { value_type track = std::move(*iter); erase(iter); Track *pTrack = track.get(); pTrack->SetOwner(this, insert(end(), std::move(track))); } auto n = begin(); RecalcPositions(n); UpdatedEvent(n); ResizedEvent(n); } template<typename TrackKind> Track *TrackList::Add(std::unique_ptr<TrackKind> &&t) { Track *pTrack; push_back(value_type(pTrack = t.release())); auto n = end(); --n; pTrack->SetOwner(this, n); RecalcPositions(n); UpdatedEvent(n); return back().get(); } // Make instantiations for the linker to find template Track *TrackList::Add<TimeTrack>(std::unique_ptr<TimeTrack> &&); #if defined(USE_MIDI) template Track *TrackList::Add<NoteTrack>(std::unique_ptr<NoteTrack> &&); #endif template Track *TrackList::Add<WaveTrack>(std::unique_ptr<WaveTrack> &&); template Track *TrackList::Add<LabelTrack>(std::unique_ptr<LabelTrack> &&); template<typename TrackKind> Track *TrackList::AddToHead(std::unique_ptr<TrackKind> &&t) { Track *pTrack; push_front(value_type(pTrack = t.release())); auto n = begin(); pTrack->SetOwner(this, n); RecalcPositions(n); UpdatedEvent(n); ResizedEvent(n); return front().get(); } // Make instantiations for the linker to find template Track *TrackList::AddToHead<TimeTrack>(std::unique_ptr<TimeTrack> &&); #ifdef __AUDACITY_OLD_STD__ template<typename TrackKind> Track *TrackList::Add(std::shared_ptr<TrackKind> &&t) { push_back(t); auto n = end(); --n; t->SetOwner(this, n); RecalcPositions(n); UpdatedEvent(n); return back().get(); } // Make instantiations for the linker to find template Track *TrackList::Add<Track>(std::shared_ptr<Track> &&); template Track *TrackList::Add<WaveTrack>(std::shared_ptr<WaveTrack> &&); #endif auto TrackList::Replace(Track * t, value_type &&with) -> value_type { value_type holder; if (t && with) { auto node = t->GetNode(); holder = std::move(*node); Track *pTrack = with.get(); *node = std::move(with); pTrack->SetOwner(this, node); RecalcPositions(node); UpdatedEvent(node); ResizedEvent(node); } return holder; } TrackNodePointer TrackList::Remove(Track *t) { TrackNodePointer result(end()); if (t) { auto node = t->GetNode(); if (!isNull(node)) { result = erase(node); if (!isNull(result)) { RecalcPositions(result); } UpdatedEvent(end()); ResizedEvent(result); } } return result; } void TrackList::Clear(bool sendEvent) { ListOfTracks::clear(); if (sendEvent) UpdatedEvent(end()); } void TrackList::Select(Track * t, bool selected /* = true */ ) { if (t) { const auto node = t->GetNode(); if (!isNull(node)) { t->SetSelected(selected); auto next = node; ++next; if (t->GetLinked() && !isNull(next)) { (*next)->SetSelected(selected); } else if (hasPrev(node)) { auto prev = node; --prev; if ((*prev)->GetLinked()) { (*prev)->SetSelected(selected); } } } } } Track *TrackList::GetLink(Track * t) const { if (t) { return t->GetLink(); } return NULL; } /// Return a track in the list that comes after Track t Track *TrackList::GetNext(Track * t, bool linked) const { if (t) { auto node = t->GetNode(); if (!isNull(node)) { if (linked && t->GetLinked()) { ++node; } if (!isNull(node)) { ++node; } if (!isNull(node)) { return node->get(); } } } return NULL; } Track *TrackList::GetPrev(Track * t, bool linked) const { if (t) { auto node = t->GetNode(); if (!isNull(node)) { // linked is true and input track second in team? if (linked && hasPrev(node) && !t->GetLinked() && t->GetLink()) // Make it the first --node; if (hasPrev(node)) { // Back up once --node; // Back up twice sometimes when linked is true if (linked && hasPrev(node) && !(*node)->GetLinked() && (*node)->GetLink()) --node; return node->get(); } } } return NULL; } /// For mono track height of track /// For stereo track combined height of both channels. int TrackList::GetGroupHeight(Track * t) const { int height = t->GetHeight(); t = t->GetLink(); if (t) { height += t->GetHeight(); } #ifdef EXPERIMENTAL_OUTPUT_DISPLAY else if(MONO_WAVE_PAN(t)){ height += t->GetHeight(true); } #endif return height; } bool TrackList::CanMoveUp(Track * t) const { return GetPrev(t, true) != NULL; } bool TrackList::CanMoveDown(Track * t) const { return GetNext(t, true) != NULL; } // This is used when you want to swap the track or pair of // tracks in s1 with the track or pair of tracks in s2. // The complication is that the tracks are stored in a single // linked list, and pairs of tracks are marked only by a flag // in one of the tracks. void TrackList::SwapNodes(TrackNodePointer s1, TrackNodePointer s2) { // if a null pointer is passed in, we want to know about it wxASSERT(!isNull(s1)); wxASSERT(!isNull(s2)); // Deal with first track in each team Track *link; link = (*s1)->GetLink(); bool linked1 = link != nullptr; if (linked1 && !(*s1)->GetLinked()) { s1 = link->GetNode(); } link = (*s2)->GetLink(); bool linked2 = link != nullptr; if (linked2 && !(*s2)->GetLinked()) { s2 = link->GetNode(); } // Safety check... if (s1 == s2) return; // Be sure s1 is the earlier iterator if ((*s1)->GetIndex() >= (*s2)->GetIndex()) { std::swap(s1, s2); std::swap(linked1, linked2); } // Remove tracks value_type save11 = std::move(*s1), save12{}; s1 = erase(s1); if (linked1) { wxASSERT(s1 != s2); save12 = std::move(*s1), s1 = erase(s1); } const bool same = (s1 == s2); value_type save21 = std::move(*s2), save22{}; s2 = erase(s2); if (linked2) save22 = std::move(*s2), s2 = erase(s2); if (same) // We invalidated s1! s1 = s2; // Reinsert them Track *pTrack; if (save22) pTrack = save22.get(), pTrack->SetOwner(this, s1 = insert(s1, std::move(save22))); pTrack = save21.get(), pTrack->SetOwner(this, s1 = insert(s1, std::move(save21))); if (save12) pTrack = save12.get(), pTrack->SetOwner(this, s2 = insert(s2, std::move(save12))); pTrack = save11.get(), pTrack->SetOwner(this, s2 = insert(s2, std::move(save11))); // Now correct the Index in the tracks, and other things RecalcPositions(s1); UpdatedEvent(s1); ResizedEvent(s1); } bool TrackList::MoveUp(Track * t) { if (t) { Track *p = GetPrev(t, true); if (p) { SwapNodes(p->GetNode(), t->GetNode()); return true; } } return false; } bool TrackList::MoveDown(Track * t) { if (t) { Track *n = GetNext(t, true); if (n) { SwapNodes(t->GetNode(), n->GetNode()); return true; } } return false; } bool TrackList::Contains(const Track * t) const { return std::find_if(begin(), end(), [=](const value_type &track) { return t == track.get(); } ) != end(); } bool TrackList::IsEmpty() const { return empty(); } int TrackList::GetCount() const { int cnt = 0; if (!empty()) { cnt = back()->GetIndex() + 1; } return cnt; } TimeTrack *TrackList::GetTimeTrack() { auto iter = std::find_if(begin(), end(), [] (const value_type &t) { return t->GetKind() == Track::Time; } ); if (iter == end()) return nullptr; else return static_cast<TimeTrack*>(iter->get()); } const TimeTrack *TrackList::GetTimeTrack() const { return const_cast<TrackList*>(this)->GetTimeTrack(); } unsigned TrackList::GetNumExportChannels(bool selectionOnly) const { /* counters for tracks panned different places */ int numLeft = 0; int numRight = 0; int numMono = 0; /* track iteration kit */ const Track *tr; TrackListConstIterator iter; for (tr = iter.First(this); tr != NULL; tr = iter.Next()) { // Want only unmuted wave tracks. if ((tr->GetKind() != Track::Wave) || tr->GetMute()) continue; // do we only want selected ones? if (selectionOnly && !(tr->GetSelected())) { //want selected but this one is not continue; } // Found a left channel if (tr->GetChannel() == Track::LeftChannel) { numLeft++; } // Found a right channel else if (tr->GetChannel() == Track::RightChannel) { numRight++; } // Found a mono channel, but it may be panned else if (tr->GetChannel() == Track::MonoChannel) { float pan = ((WaveTrack*)tr)->GetPan(); // Figure out what kind of channel it should be if (pan == -1.0) { // panned hard left numLeft++; } else if (pan == 1.0) { // panned hard right numRight++; } else if (pan == 0) { // panned dead center numMono++; } else { // panned somewhere else numLeft++; numRight++; } } } // if there is stereo content, report 2, else report 1 if (numRight > 0 || numLeft > 0) { return 2; } return 1; } namespace { template<typename Array> Array GetWaveTracks(ListOfTracks::const_iterator p, ListOfTracks::const_iterator end, bool selectionOnly, bool includeMuted) { Array waveTrackArray; for (; p != end; ++p) { const auto &track = *p; if (track->GetKind() == Track::Wave && (includeMuted || !track->GetMute()) && (track->GetSelected() || !selectionOnly)) { waveTrackArray.push_back(static_cast<WaveTrack*>(track.get())); } } return waveTrackArray; } } WaveTrackArray TrackList::GetWaveTrackArray(bool selectionOnly, bool includeMuted) { return GetWaveTracks<WaveTrackArray>(begin(), end(), selectionOnly, includeMuted); } WaveTrackConstArray TrackList::GetWaveTrackConstArray(bool selectionOnly, bool includeMuted) const { return GetWaveTracks<WaveTrackConstArray>(begin(), end(), selectionOnly, includeMuted); } #if defined(USE_MIDI) NoteTrackArray TrackList::GetNoteTrackArray(bool selectionOnly) { NoteTrackArray noteTrackArray; for(const auto &track : *this) { if (track->GetKind() == Track::Note && (track->GetSelected() || !selectionOnly)) { noteTrackArray.push_back(static_cast<NoteTrack*>(track.get())); } } return noteTrackArray; } #endif int TrackList::GetHeight() const { int height = 0; #ifdef EXPERIMENTAL_OUTPUT_DISPLAY if (tail) { const Track *t = tail->t; if(MONO_WAVE_PAN(t)) height = t->GetY(true) + t->GetHeight(true); else height = t->GetY() + t->GetHeight(); } #else if (!empty()) { const auto &track = back(); height = track->GetY() + track->GetHeight(); } #endif return height; } namespace { // Abstract the common pattern of the following three member functions double doubleMin(double a, double b) { return std::min(a, b); } double doubleMax(double a, double b) { return std::max(a, b); } inline double Accumulate (const ListOfTracks &list, double (Track::*memfn)() const, double (*combine)(double, double)) { // Default the answer to zero for empty list if (list.empty()) { return 0.0; } // Otherwise accumulate minimum or maximum of track values auto iter = list.begin(); double acc = (**iter++.*memfn)(); return std::accumulate(iter, list.end(), acc, [=](double acc, const ListOfTracks::value_type &pTrack) { return combine(acc, (*pTrack.*memfn)()); }); } } double TrackList::GetMinOffset() const { return Accumulate(*this, &Track::GetOffset, doubleMin); } double TrackList::GetStartTime() const { return Accumulate(*this, &Track::GetStartTime, doubleMin); } double TrackList::GetEndTime() const { return Accumulate(*this, &Track::GetEndTime, doubleMax); }
/* Copyright 2017 The TensorFlow Authors. 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 "tensorflow/compiler/xla/service/layout_assignment.h" #include <initializer_list> #include <memory> #include <utility> #include <vector> #include "absl/types/span.h" #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/service/algebraic_simplifier.h" #include "tensorflow/compiler/xla/service/computation_layout.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_matchers.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/hlo_parser.h" #include "tensorflow/compiler/xla/shape_layout.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/test_helpers.h" #include "tensorflow/compiler/xla/tests/hlo_verified_test_base.h" #include "tensorflow/compiler/xla/tests/test_utils.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/status_test_util.h" namespace op = xla::testing::opcode_matchers; namespace xla { namespace { using ::testing::ElementsAre; class LayoutAssignmentTest : public HloVerifiedTestBase { protected: void AssignLayouts(HloModule* module, ComputationLayout* entry_computation_layout, ChannelLayoutConstraints* channel_constraints = nullptr) { LayoutAssignment layout_assignment( entry_computation_layout, LayoutAssignment::InstructionCanChangeLayout, /*channel_constraints=*/channel_constraints); EXPECT_IS_OK(layout_assignment.Run(module).status()); } std::vector<int64> LayoutOf(HloModule* module, absl::string_view name) { auto minor_to_major = FindInstruction(module, name)->shape().layout().minor_to_major(); return std::vector<int64>(minor_to_major.begin(), minor_to_major.end()); } void ExpectLayoutIs(const Shape& shape, absl::Span<const int64> minor_to_major) { const Layout expected = LayoutUtil::MakeLayout(minor_to_major); EXPECT_TRUE(LayoutUtil::Equal(shape.layout(), expected)) << "Expected layout " << expected << ", actual " << shape.layout(); } void ExpectTupleLayoutIs( const Shape& shape, std::initializer_list<absl::Span<const int64>> minor_to_majors) { int i = 0; for (const absl::Span<const int64> minor_to_major : minor_to_majors) { const Layout expected = LayoutUtil::MakeLayout(minor_to_major); const Layout& actual = ShapeUtil::GetTupleElementShape(shape, i).layout(); EXPECT_TRUE(LayoutUtil::Equal(actual, expected)) << "Expected tuple element " << i << " layout " << expected << ", actual " << actual; ++i; } } }; TEST_F(LayoutAssignmentTest, ComputationLayout) { // Verify the layouts of the root and parameter instructions of a computation // match the ComputationLayout for two different layouts. std::vector<std::initializer_list<int64>> minor_to_majors = {{0, 1}, {1, 0}}; for (auto& minor_to_major : minor_to_majors) { auto builder = HloComputation::Builder(TestName()); Shape ashape = ShapeUtil::MakeShape(F32, {42, 12}); auto param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, ashape, "param0")); auto param1 = builder.AddInstruction( HloInstruction::CreateParameter(1, ashape, "param1")); auto add = builder.AddInstruction( HloInstruction::CreateBinary(ashape, HloOpcode::kAdd, param0, param1)); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build()); Layout layout = LayoutUtil::MakeLayout(minor_to_major); Shape shape(ashape); *shape.mutable_layout() = layout; const ShapeLayout shape_layout(shape); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = shape_layout; *computation_layout.mutable_parameter_layout(1) = shape_layout; *computation_layout.mutable_result_layout() = shape_layout; AssignLayouts(module, &computation_layout); EXPECT_TRUE(LayoutUtil::Equal(layout, param0->shape().layout())); EXPECT_TRUE(LayoutUtil::Equal(layout, param1->shape().layout())); EXPECT_TRUE(LayoutUtil::Equal(layout, add->shape().layout())); } } TEST_F(LayoutAssignmentTest, ComputationLayoutMixedLayout) { // Verify the layouts of the root and parameter instructions of a computation // match the ComputationLayout which has mixed layout. auto builder = HloComputation::Builder(TestName()); Shape ashape = ShapeUtil::MakeShape(F32, {42, 12}); auto param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, ashape, "param0")); auto param1 = builder.AddInstruction( HloInstruction::CreateParameter(1, ashape, "param1")); builder.AddInstruction( HloInstruction::CreateBinary(ashape, HloOpcode::kAdd, param0, param1)); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build()); Layout col_major_layout = LayoutUtil::MakeLayout({1, 0}); Shape col_major_shape(ashape); *col_major_shape.mutable_layout() = col_major_layout; const ShapeLayout col_major(col_major_shape); Layout row_major_layout = LayoutUtil::MakeLayout({0, 1}); Shape row_major_shape(ashape); *row_major_shape.mutable_layout() = row_major_layout; const ShapeLayout row_major(row_major_shape); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = col_major; *computation_layout.mutable_parameter_layout(1) = row_major; *computation_layout.mutable_result_layout() = col_major; AssignLayouts(module, &computation_layout); EXPECT_TRUE(LayoutUtil::Equal(col_major_layout, param0->shape().layout())); EXPECT_TRUE(LayoutUtil::Equal(row_major_layout, param1->shape().layout())); EXPECT_TRUE(LayoutUtil::Equal( col_major_layout, computation->root_instruction()->shape().layout())); } TEST_F(LayoutAssignmentTest, FusionInstruction) { // Verify that the layout of the fused parameters in a fusion instruction // match that of the fusion operands. Other fused instructions should have no // layout. std::vector<std::initializer_list<int64>> minor_to_majors = {{0, 1}, {1, 0}}; for (auto& minor_to_major : minor_to_majors) { auto builder = HloComputation::Builder(TestName()); auto constant_literal1 = LiteralUtil::CreateR2WithLayout<float>( {{1.0, 2.0}, {3.0, 4.0}}, LayoutUtil::MakeLayout(minor_to_major)); auto constant_literal2 = LiteralUtil::CreateR2WithLayout<float>( {{5.0, 6.0}, {7.0, 8.0}}, LayoutUtil::MakeLayout(minor_to_major)); Shape ashape = constant_literal1.shape(); auto constant1 = builder.AddInstruction( HloInstruction::CreateConstant(std::move(constant_literal1))); auto constant2 = builder.AddInstruction( HloInstruction::CreateConstant(std::move(constant_literal2))); auto add = builder.AddInstruction(HloInstruction::CreateBinary( ashape, HloOpcode::kAdd, constant1, constant2)); auto negate1 = builder.AddInstruction( HloInstruction::CreateUnary(ashape, HloOpcode::kNegate, add)); auto negate2 = builder.AddInstruction( HloInstruction::CreateUnary(ashape, HloOpcode::kNegate, negate1)); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build()); auto fusion = computation->CreateFusionInstruction( {negate2, negate1, add}, HloInstruction::FusionKind::kLoop); Layout layout = LayoutUtil::MakeLayout(minor_to_major); Shape shape(ashape); *shape.mutable_layout() = layout; const ShapeLayout shape_layout(shape); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_result_layout() = shape_layout; AssignLayouts(module, &computation_layout); EXPECT_TRUE(LayoutUtil::Equal( layout, fusion->fused_parameter(0)->shape().layout())); EXPECT_TRUE(LayoutUtil::Equal( layout, fusion->fused_parameter(1)->shape().layout())); EXPECT_TRUE(LayoutUtil::Equal( layout, fusion->fused_expression_root()->shape().layout())); // Inner fused node should not have layout. EXPECT_FALSE(LayoutUtil::HasLayout( fusion->fused_expression_root()->operand(0)->shape())); } } TEST_F(LayoutAssignmentTest, TupleLayout) { // Verify the layouts of a tuple are assigned properly (the element layouts // match their source). auto builder = HloComputation::Builder(TestName()); auto constant0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR2WithLayout<float>( {{1.0, 2.0}, {3.0, 4.0}}, LayoutUtil::MakeLayout({0, 1})))); auto constant1 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR2WithLayout<float>( {{1.0, 2.0}, {3.0, 4.0}}, LayoutUtil::MakeLayout({1, 0})))); auto tuple = builder.AddInstruction( HloInstruction::CreateTuple({constant0, constant1})); // To avoid having to construct a tuple layout in the ComputationLayout below, // make the result of the instruction be an array. auto get_element0 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(constant0->shape(), tuple, 0)); auto negate = builder.AddInstruction(HloInstruction::CreateUnary( constant0->shape(), HloOpcode::kNegate, get_element0)); auto module = CreateNewModule(); module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout( module->entry_computation()->ComputeProgramShape()); AssignLayouts(module, &computation_layout); EXPECT_TRUE( LayoutUtil::LayoutsInShapesEqual(constant0->shape(), constant1->shape())); EXPECT_TRUE(LayoutUtil::HasLayout(tuple->shape())); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual( negate->shape(), computation_layout.result_layout().shape())); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual( ShapeUtil::GetTupleElementShape(tuple->shape(), 1), constant1->shape())); } TEST_F(LayoutAssignmentTest, TupleSelect) { // Verify layouts of a select with tuple operands is assigned properly. auto builder = HloComputation::Builder(TestName()); auto constant0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR2WithLayout<float>( {{1.0, 2.0}, {3.0, 4.0}}, LayoutUtil::MakeLayout({0, 1})))); auto constant1 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR2WithLayout<float>( {{1.0, 2.0}, {3.0, 4.0}}, LayoutUtil::MakeLayout({1, 0})))); auto tuple0 = builder.AddInstruction( HloInstruction::CreateTuple({constant0, constant1})); auto tuple1 = builder.AddInstruction( HloInstruction::CreateTuple({constant0, constant1})); auto pred = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<bool>(true))); auto select = builder.AddInstruction(HloInstruction::CreateTernary( tuple0->shape(), HloOpcode::kTupleSelect, pred, tuple0, tuple1)); auto module = CreateNewModule(); module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout( module->entry_computation()->ComputeProgramShape()); Shape result_shape = ShapeUtil::MakeTupleShape({constant0->shape(), constant1->shape()}); TF_CHECK_OK(computation_layout.mutable_result_layout()->CopyLayoutFromShape( result_shape)); AssignLayouts(module, &computation_layout); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(result_shape, select->shape())); } TEST_F(LayoutAssignmentTest, ConflictingLayoutTuple) { // Construct following computation which has conflicting layouts for two // elements of a tuple which share the same source logicalb buffer: // // %constant = Constant(...) // %inner_tuple = Tuple(%constant) // %nested_tuple = Tuple(%inner_tuple, %inner_tuple) // // Result layout col-major for the first element and row-major for the // second. This results in the conflict where the element of the inner_tuple // needs to be both col and row major. This is resolved by deep-copying the // tuple and assigning the layouts of the copied arrays as needed. auto builder = HloComputation::Builder(TestName()); auto constant = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{1.0, 2.0}, {3.0, 4.0}}))); auto inner_tuple = builder.AddInstruction(HloInstruction::CreateTuple({constant})); auto nested_tuple = builder.AddInstruction( HloInstruction::CreateTuple({inner_tuple, inner_tuple})); auto module = CreateNewModule(); module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout( module->entry_computation()->ComputeProgramShape()); Shape result_shape = nested_tuple->shape(); *ShapeUtil::GetMutableSubshape(&result_shape, /*index=*/{0, 0}) = ShapeUtil::MakeShapeWithLayout(F32, {2, 2}, {1, 0}); *ShapeUtil::GetMutableSubshape(&result_shape, /*index=*/{1, 0}) = ShapeUtil::MakeShapeWithLayout(F32, {2, 2}, {0, 1}); TF_CHECK_OK(computation_layout.mutable_result_layout()->CopyLayoutFromShape( result_shape)); LayoutAssignment layout_assignment(&computation_layout); AssignLayouts(module, &computation_layout); // Layout assignment should have deep copied the result of the computation to // address the layout conflict. This results in several Tuple() and // GetTupleElement() instructions. Running algebraic simplification should // clean up the code to something like: // // %constant = Constant(...) layout={1,0} // %tuple.0 = Tuple(%constant) layout=({1,0}) // %copy = Copy(%constant) layout={0,1} # layout transposed // %tuple.1 = Tuple(%copy) layout=({0,1}) // %tuple.2 = Tuple(%tuple.0, %tuple.1) layout=(({1,0}), ({0,1})) // EXPECT_TRUE( AlgebraicSimplifier(/*is_layout_sensitive=*/true, [](const Shape&, const Shape&) { return false; }) .Run(module) .ValueOrDie()); HloInstruction* root = module->entry_computation()->root_instruction(); // Verify layout of the root and the root's operands. EXPECT_TRUE(ShapeUtil::Equal(result_shape, root->shape())); EXPECT_TRUE(ShapeUtil::Equal(ShapeUtil::GetSubshape(result_shape, {0}), root->operand(0)->shape())); EXPECT_TRUE(ShapeUtil::Equal(ShapeUtil::GetSubshape(result_shape, {1}), root->operand(1)->shape())); // Verify the structure of the HLO graph. EXPECT_THAT(root, op::Tuple(op::Tuple(constant), op::Tuple(op::Copy(constant)))); } TEST_F(LayoutAssignmentTest, ElementwiseAndReshape) { // param -> log -> reshape -> tanh auto builder = HloComputation::Builder(TestName()); Shape ashape = ShapeUtil::MakeShape(F32, {1, 2, 3, 1}); Shape bshape = ShapeUtil::MakeShape(F32, {3, 1, 2}); auto param = builder.AddInstruction( HloInstruction::CreateParameter(0, ashape, "param")); auto log = builder.AddInstruction( HloInstruction::CreateUnary(ashape, HloOpcode::kLog, param)); auto reshape = builder.AddInstruction(HloInstruction::CreateReshape(bshape, log)); auto tanh = builder.AddInstruction( HloInstruction::CreateUnary(bshape, HloOpcode::kTanh, reshape)); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build(tanh)); Shape ashape_with_layout(ashape); Shape bshape_with_layout(bshape); *ashape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({0, 2, 1, 3}); *bshape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({2, 1, 0}); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(ashape_with_layout); *computation_layout.mutable_result_layout() = ShapeLayout(bshape_with_layout); AssignLayouts(module, &computation_layout); auto log_minor_to_major = AsInt64Slice(log->shape().layout().minor_to_major()); EXPECT_GT(PositionInContainer(log_minor_to_major, 1), PositionInContainer(log_minor_to_major, 2)); auto reshape_minor_to_major = AsInt64Slice(reshape->shape().layout().minor_to_major()); EXPECT_GT(PositionInContainer(reshape_minor_to_major, 0), PositionInContainer(reshape_minor_to_major, 2)); } // Test whether LayoutAssignment assigns layouts to elementwise operations to // keep linear indices valid across them, and to transpositions to make them // bitcasts. TEST_F(LayoutAssignmentTest, ElementwiseAndTranspose) { // param -> log -> transpose -> tanh auto builder = HloComputation::Builder(TestName()); Shape ashape = ShapeUtil::MakeShape(F32, {42, 12}); Shape bshape = ShapeUtil::MakeShape(F32, {12, 42}); auto param = builder.AddInstruction( HloInstruction::CreateParameter(0, ashape, "param")); auto log = builder.AddInstruction( HloInstruction::CreateUnary(ashape, HloOpcode::kLog, param)); auto transpose = builder.AddInstruction( HloInstruction::CreateTranspose(bshape, log, {1, 0})); auto tanh = builder.AddInstruction( HloInstruction::CreateUnary(bshape, HloOpcode::kTanh, transpose)); auto module = CreateNewModule(); auto computation = module->AddEntryComputation(builder.Build(tanh)); Shape ashape_with_layout(ashape); Shape bshape_with_layout(bshape); *ashape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({1, 0}); *bshape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({0, 1}); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(ashape_with_layout); *computation_layout.mutable_result_layout() = ShapeLayout(bshape_with_layout); AssignLayouts(module, &computation_layout); EXPECT_TRUE( LayoutUtil::Equal(ashape_with_layout.layout(), log->shape().layout())); EXPECT_TRUE(LayoutUtil::Equal(bshape_with_layout.layout(), transpose->shape().layout())); EXPECT_TRUE( LayoutUtil::Equal(bshape_with_layout.layout(), tanh->shape().layout())); } // Test whether LayoutAssignment assigns layouts to transpositions to make them // bitcasts. TEST_F(LayoutAssignmentTest, BroadcastAndTranspose) { // param -> broadcast -> transpose auto builder = HloComputation::Builder(TestName()); Shape ashape = ShapeUtil::MakeShape(F32, {3, 4}); Shape bshape = ShapeUtil::MakeShape(F32, {2, 3, 4}); Shape cshape = ShapeUtil::MakeShape(F32, {4, 3, 2}); auto param = builder.AddInstruction( HloInstruction::CreateParameter(0, ashape, "param")); auto broadcast = builder.AddInstruction( HloInstruction::CreateBroadcast(bshape, param, {1, 2})); auto transpose = builder.AddInstruction( HloInstruction::CreateTranspose(cshape, broadcast, {2, 1, 0})); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build(transpose)); Shape input_shape_with_layout(ashape); Shape output_shape_with_layout(cshape); *input_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({1, 0}); *output_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({2, 1, 0}); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(input_shape_with_layout); *computation_layout.mutable_result_layout() = ShapeLayout(output_shape_with_layout); AssignLayouts(module, &computation_layout); EXPECT_THAT(broadcast->shape().layout().minor_to_major(), ElementsAre(0, 1, 2)); } TEST_F(LayoutAssignmentTest, ReshapeOperandHasMultipleUsers) { // param[4] -> broadcast[3x4] ------> transpose[4x3]-------- -------> tuple // \ / // \-> tanh[3x4] -> broadcast2[2x3x4] -/ // // The layout of `transpose` is set to {1,0} because it provides a buffer to // the computation result which has a fixed layout.. Therefore, `broadcast` // (the operand of transpose) is expected to have layout {0,1} so that the // transpose is a bitcast. Furthermore, `tanh` is expected to have the same // layout as `broadcast` (i.e. {0,1}) because `tanh` is elementwise. Shape f32_4 = ShapeUtil::MakeShape(F32, {4}); Shape f32_34 = ShapeUtil::MakeShape(F32, {3, 4}); Shape f32_43 = ShapeUtil::MakeShape(F32, {4, 3}); Shape f32_234 = ShapeUtil::MakeShape(F32, {2, 3, 4}); auto builder = HloComputation::Builder(TestName()); auto param = builder.AddInstruction( HloInstruction::CreateParameter(0, f32_4, "param")); auto broadcast = builder.AddInstruction( HloInstruction::CreateBroadcast(f32_34, param, {1})); auto transpose = builder.AddInstruction( HloInstruction::CreateTranspose(f32_43, broadcast, {1, 0})); auto tanh = builder.AddInstruction( HloInstruction::CreateUnary(f32_34, HloOpcode::kTanh, broadcast)); auto broadcast2 = builder.AddInstruction( HloInstruction::CreateBroadcast(f32_234, tanh, {1, 2})); auto tuple = builder.AddInstruction( HloInstruction::CreateTuple({transpose, broadcast2})); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build(tuple)); ComputationLayout computation_layout(computation->ComputeProgramShape()); Shape param_shape_with_layout(f32_4); Shape transpose_shape_with_layout(f32_43); Shape broadcast2_shape_with_layout(f32_234); *param_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({0}); *transpose_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({1, 0}); *broadcast2_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({2, 1, 0}); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(param_shape_with_layout); *computation_layout.mutable_result_layout() = ShapeLayout(ShapeUtil::MakeTupleShape( {transpose_shape_with_layout, broadcast2_shape_with_layout})); AssignLayouts(module, &computation_layout); EXPECT_THAT(broadcast->shape().layout().minor_to_major(), ElementsAre(0, 1)); EXPECT_THAT(transpose->shape().layout().minor_to_major(), ElementsAre(1, 0)); EXPECT_THAT(tanh->shape().layout().minor_to_major(), ElementsAre(0, 1)); } class OperandsMustBeTheSameLayoutAssignment : public LayoutAssignment { public: explicit OperandsMustBeTheSameLayoutAssignment( ComputationLayout* entry_computation_layout) : LayoutAssignment(entry_computation_layout) {} protected: Status PropagateBufferConstraint( const BufferLayoutConstraint& buffer_constraint, LayoutConstraints* constraints) override { const LogicalBuffer& buffer = buffer_constraint.buffer(); const HloInstruction* instruction = buffer.instruction(); // Force the operands' layout to the output layout. for (int64 operand_no = 0; operand_no < instruction->operand_count(); ++operand_no) { const HloInstruction* operand = instruction->operand(operand_no); if (ShapeUtil::Rank(instruction->shape()) != ShapeUtil::Rank(operand->shape())) { continue; } TF_RETURN_IF_ERROR(constraints->SetArrayOperandLayout( buffer_constraint.layout(), instruction, operand_no, /*mandatory=*/true)); } return PropagateBufferConstraintToUses(buffer_constraint, constraints); } }; TEST_F(LayoutAssignmentTest, MakeOperandsTheSame) { // param0 -> concatenate -> reshape // param1 -^ auto builder = HloComputation::Builder(TestName()); Shape ashape = ShapeUtil::MakeShape(F32, {50, 1}); Shape bshape = ShapeUtil::MakeShape(F32, {50, 2}); Shape cshape = ShapeUtil::MakeShape(F32, {100}); auto param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, ashape, "param")); auto param1 = builder.AddInstruction( HloInstruction::CreateParameter(1, ashape, "param")); auto concatenate = builder.AddInstruction( HloInstruction::CreateConcatenate(bshape, {param0, param1}, 1)); auto reshape = builder.AddInstruction( HloInstruction::CreateReshape(cshape, concatenate)); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build(reshape)); Shape param0_shape_with_layout(ashape); Shape param1_shape_with_layout(ashape); *param0_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({0, 1}); *param1_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({1, 0}); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(param0_shape_with_layout); *computation_layout.mutable_parameter_layout(1) = ShapeLayout(param1_shape_with_layout); OperandsMustBeTheSameLayoutAssignment layout_assignment(&computation_layout); EXPECT_IS_OK(layout_assignment.Run(module).status()); EXPECT_EQ(HloOpcode::kCopy, concatenate->operand(0)->opcode()); EXPECT_THAT(concatenate->operand(0)->shape().layout().minor_to_major(), ElementsAre(1, 0)); EXPECT_THAT(concatenate->operand(1)->shape().layout().minor_to_major(), ElementsAre(1, 0)); EXPECT_THAT(concatenate->shape().layout().minor_to_major(), ElementsAre(1, 0)); } // Test layout assignment of a transpose into a bitcast based on its operand. TEST_F(LayoutAssignmentTest, TransposeToBitcastFromOperand) { auto builder = HloComputation::Builder(TestName()); Shape input_shape_with_layout = ShapeUtil::MakeShapeWithLayout(F32, {3, 5, 6, 7}, {2, 0, 3, 1}); auto param = builder.AddInstruction( HloInstruction::CreateParameter(0, input_shape_with_layout, "param")); auto transpose = builder.AddInstruction(HloInstruction::CreateTranspose( ShapeUtil::MakeShape(F32, {6, 7, 3, 5}), param, {2, 3, 0, 1})); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build(transpose)); ComputationLayout computation_layout(computation->ComputeProgramShape()); AssignLayouts(module, &computation_layout); EXPECT_TRUE(ShapeUtil::TransposeIsBitcast(transpose->operand(0)->shape(), transpose->shape(), {2, 3, 0, 1})); } // Test layout assignment of a transpose into a bitcast based on its user. TEST_F(LayoutAssignmentTest, TransposeToBitcastToUser) { auto builder = HloComputation::Builder(TestName()); Shape input_shape = ShapeUtil::MakeShape(F32, {3, 5, 6, 7}); auto constant = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(1.0f))); auto broadcast = builder.AddInstruction( HloInstruction::CreateBroadcast(input_shape, constant, {})); auto transpose = builder.AddInstruction(HloInstruction::CreateTranspose( ShapeUtil::MakeShape(F32, {6, 7, 3, 5}), broadcast, {2, 3, 0, 1})); auto module = CreateNewModule(); HloComputation* computation = module->AddEntryComputation(builder.Build(transpose)); ComputationLayout computation_layout(computation->ComputeProgramShape()); AssignLayouts(module, &computation_layout); EXPECT_TRUE(ShapeUtil::TransposeIsBitcast(transpose->operand(0)->shape(), transpose->shape(), {2, 3, 0, 1})); } // TransposeIsBitcast shouldn't be called without layout information. TEST_F(LayoutAssignmentTest, TransposeIsBitcastFail) { auto builder = HloComputation::Builder(TestName()); Shape input_shape = ShapeUtil::MakeShape(F32, {2, 2, 2}); Shape input_shape_with_layout(input_shape); *input_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({2, 1, 0}); auto param = builder.AddInstruction( HloInstruction::CreateParameter(0, input_shape_with_layout, "param")); auto hlo = builder.AddInstruction( HloInstruction::CreateTranspose(input_shape, param, {0, 2, 1})); // Clear the default layout assigned to the instruction. LayoutUtil::ClearLayout(hlo->mutable_shape()); EXPECT_DEATH(ShapeUtil::TransposeIsBitcast(hlo->operand(0)->shape(), hlo->shape(), hlo->dimensions()), "LayoutUtil::HasLayout"); } // ReshapeIsBitcast shouldn't be called without layout information. TEST_F(LayoutAssignmentTest, ReshapeIsBitcastFail) { auto builder = HloComputation::Builder(TestName()); Shape input_shape = ShapeUtil::MakeShape(F32, {2, 2, 2}); Shape input_shape_with_layout(input_shape); *input_shape_with_layout.mutable_layout() = LayoutUtil::MakeLayout({2, 1, 0}); auto param = builder.AddInstruction( HloInstruction::CreateParameter(0, input_shape_with_layout, "param")); auto hlo = builder.AddInstruction(HloInstruction::CreateReshape(input_shape, param)); // Clear the default layout assigned to the instruction. LayoutUtil::ClearLayout(hlo->mutable_shape()); EXPECT_DEATH( ShapeUtil::ReshapeIsBitcast(hlo->operand(0)->shape(), hlo->shape()), "LayoutUtil::HasLayout"); } // Check that the computation below doesn't crash the compiler. // // Within a fusion computation, only the parameters and result get assigned a // layout. When we run the algebraic simplifier on this computation post layout // assignment, it should not call TransposeIsBitcast on the `transpose` node // inside the fusion computation as TransposeIsBitcast checks both input_shape // and output_shape have layouts. TEST_F(LayoutAssignmentTest, TransposeWithinFusionDoesNotCrash) { const char* module_str = R"( HloModule test_module fused_computation { param_1 = f32[2,2,2]{2,1,0} parameter(1) transpose = f32[2,2,2]{2,1,0} transpose(param_1), dimensions={0,2,1} reduce_1 = f32[] parameter(0) broadcast_1 = f32[2,2,2]{2,1,0} broadcast(reduce_1), dimensions={} ROOT divide_1 = f32[2,2,2]{2,1,0} divide(transpose, broadcast_1) } ENTRY entry_computation { fusion.1 = f32[2,2,2]{2,1,0} parameter(1) reduce.1 = f32[] parameter(0) fusion.2 = f32[2,2,2]{2,1,0} fusion(reduce.1, fusion.1), kind=kLoop, calls=fused_computation ROOT tuple.1 = (f32[2,2,2]{2,1,0}) tuple(fusion.2) } )"; ParseAndVerifyModule(module_str); std::unique_ptr<HloModule> compiled_module = backend() .compiler() ->RunHloPasses(module().Clone(), backend().default_stream_executor(), /*device_allocator=*/nullptr) .ConsumeValueOrDie(); EXPECT_EQ(Status::OK(), backend() .compiler() ->RunBackend(std::move(compiled_module), backend().default_stream_executor(), /*device_allocator=*/nullptr) .status()); } // A GTE inside of a fusion node inherits the layout of its operand (which // should, if we keep following operands, eventually be a parameter). TEST_F(LayoutAssignmentTest, GTEInheritsLayoutFromOperand) { const char* module_str = R"( HloModule test_module fused_computation { fparam = (f32[2,2,2], (f32[2,2,2], f32[2,2,2])) parameter(0) gte0 = f32[2,2,2] get-tuple-element(fparam), index=0 gte1 = (f32[2,2,2], f32[2,2,2]) get-tuple-element(fparam), index=1 gte1a = f32[2,2,2] get-tuple-element(gte1), index=0 gte1b = f32[2,2,2] get-tuple-element(gte1), index=1 add = f32[2,2,2] add(gte1a, gte1b) ROOT fresult = f32[2,2,2] add(gte0, add) } ENTRY entry_computation { param = (f32[2,2,2], (f32[2,2,2], f32[2,2,2])) parameter(0) ROOT fusion = f32[2,2,2] fusion(param), kind=kLoop, calls=fused_computation } )"; ParseAndVerifyModule(module_str); ComputationLayout computation_layout( module().entry_computation()->ComputeProgramShape()); Shape param_shape = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShapeWithLayout(F32, {2, 2, 2}, {0, 1, 2}), ShapeUtil::MakeTupleShape({ ShapeUtil::MakeShapeWithLayout(F32, {2, 2, 2}, {1, 2, 0}), ShapeUtil::MakeShapeWithLayout(F32, {2, 2, 2}, {2, 0, 1}), })}); TF_ASSERT_OK( computation_layout.mutable_parameter_layout(0)->CopyLayoutFromShape( param_shape)); computation_layout.mutable_result_layout()->ResetLayout( LayoutUtil::MakeLayout({2, 1, 0})); AssignLayouts(&module(), &computation_layout); EXPECT_THAT(LayoutOf(&module(), "gte0"), ElementsAre(0, 1, 2)); EXPECT_THAT(LayoutOf(&module(), "gte1a"), ElementsAre(1, 2, 0)); EXPECT_THAT(LayoutOf(&module(), "gte1b"), ElementsAre(2, 0, 1)); EXPECT_THAT(LayoutOf(&module(), "fresult"), ElementsAre(2, 1, 0)); EXPECT_THAT(FindInstruction(&module(), "gte1") ->shape() .tuple_shapes(0) .layout() .minor_to_major(), ElementsAre(1, 2, 0)); EXPECT_THAT(FindInstruction(&module(), "gte1") ->shape() .tuple_shapes(1) .layout() .minor_to_major(), ElementsAre(2, 0, 1)); } TEST_F(LayoutAssignmentTest, ConditionalAsymmetricLayout) { auto builder = HloComputation::Builder(TestName()); auto module = CreateNewModule(); Shape shape = ShapeUtil::MakeShape(F32, {128, 8}); Shape tshape = ShapeUtil::MakeTupleShape({shape, shape}); Shape result_tshape = ShapeUtil::MakeTupleShape({shape}); auto param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, shape, "param0")); auto param1 = builder.AddInstruction( HloInstruction::CreateParameter(1, shape, "param1")); auto pred = builder.AddInstruction(HloInstruction::CreateParameter( 2, ShapeUtil::MakeShape(PRED, {}), "param2")); auto tuple = builder.AddInstruction(HloInstruction::CreateTuple({param0, param1})); auto true_builder = HloComputation::Builder(TestName() + "_TrueBranch"); { auto param = true_builder.AddInstruction( HloInstruction::CreateParameter(0, tshape, "param")); auto gte0 = true_builder.AddInstruction( HloInstruction::CreateGetTupleElement(shape, param, 0)); auto gte1 = true_builder.AddInstruction( HloInstruction::CreateGetTupleElement(shape, param, 1)); auto add = true_builder.AddInstruction( HloInstruction::CreateBinary(shape, HloOpcode::kAdd, gte0, gte1)); true_builder.AddInstruction(HloInstruction::CreateTuple({add})); } HloComputation* true_computation = module->AddEmbeddedComputation(true_builder.Build()); auto false_builder = HloComputation::Builder(TestName() + "_FalseBranch"); { Shape xshape = ShapeUtil::MakeShapeWithLayout(F32, {128, 8}, {0, 1}); false_builder.AddInstruction( HloInstruction::CreateParameter(0, tshape, "param")); // Using infeed as layout assignment does not mess up with it. auto token = false_builder.AddInstruction(HloInstruction::CreateToken()); auto infeed = false_builder.AddInstruction( HloInstruction::CreateInfeed(xshape, token, "")); auto infeed_data = false_builder.AddInstruction( HloInstruction::CreateGetTupleElement(xshape, infeed, 0)); false_builder.AddInstruction(HloInstruction::CreateTuple({infeed_data})); } HloComputation* false_computation = module->AddEmbeddedComputation(false_builder.Build()); builder.AddInstruction(HloInstruction::CreateConditional( result_tshape, pred, tuple, true_computation, tuple, false_computation)); HloComputation* computation = module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout(computation->ComputeProgramShape()); AssignLayouts(module, &computation_layout); const HloInstruction* true_root = true_computation->root_instruction(); const HloInstruction* false_root = false_computation->root_instruction(); EXPECT_THAT(true_root->opcode(), HloOpcode::kTuple); EXPECT_THAT(false_root->opcode(), HloOpcode::kTuple); const HloInstruction* true_result = true_root->operand(0); const HloInstruction* false_result = false_root->operand(0); EXPECT_TRUE(LayoutUtil::Equal(true_result->shape().layout(), false_result->shape().layout())); EXPECT_THAT(false_result->opcode(), HloOpcode::kCopy); } TEST_F(LayoutAssignmentTest, InternalErrorOnBitcast) { auto builder = HloComputation::Builder(TestName()); auto constant0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR2WithLayout<float>( {{1.0, 2.0}, {3.0, 4.0}}, LayoutUtil::MakeLayout({0, 1})))); builder.AddInstruction(HloInstruction::CreateUnary( constant0->shape(), HloOpcode::kBitcast, constant0)); auto module = CreateNewModule(); module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout( module->entry_computation()->ComputeProgramShape()); LayoutAssignment layout_assignment(&computation_layout); Status error_status = layout_assignment.Run(module).status(); EXPECT_FALSE(error_status.ok()); EXPECT_THAT( error_status.error_message(), ::testing::HasSubstr( "Unexpected bitcast operation seen during layout assignment")); } TEST_F(LayoutAssignmentTest, ChannelLayoutMismatch) { // Pin non matching layouts to parameter and root. const char* module_str = R"( HloModule test_module ENTRY entry_computation { param = (f32[2,2]) parameter(0) gte = f32[2,2] get-tuple-element(param), index=0 token = token[] after-all() recv = (f32[2,2], u32[], token[]) recv(token), channel_id=1, sharding={maximal device=1} recv-done = (f32[2,2], token[]) recv-done(recv), channel_id=1, sharding={maximal device=1} ROOT root = f32[2,2] get-tuple-element(recv-done), index=0 send = (f32[2,2], u32[], token[]) send(gte, token), channel_id=1, sharding={maximal device=0} send-done = token[] send-done(send), channel_id=1, sharding={maximal device=0} } )"; ParseAndVerifyModule(module_str); ComputationLayout computation_layout( module().entry_computation()->ComputeProgramShape()); Shape param_shape = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShapeWithLayout(F32, {2, 2}, {0, 1})}); TF_ASSERT_OK( computation_layout.mutable_parameter_layout(0)->CopyLayoutFromShape( param_shape)); computation_layout.mutable_result_layout()->ResetLayout( LayoutUtil::MakeLayout({1, 0})); ChannelLayoutConstraints channel_constraints; AssignLayouts(&module(), &computation_layout, &channel_constraints); EXPECT_THAT(LayoutOf(&module(), "gte"), ElementsAre(0, 1)); EXPECT_THAT(LayoutOf(&module(), "root"), ElementsAre(1, 0)); EXPECT_TRUE(ShapeUtil::Equal( ShapeUtil::GetSubshape(FindInstruction(&module(), "send")->shape(), {0}), ShapeUtil::MakeShapeWithLayout(F32, {2, 2}, {1, 0}))); } TEST_F(LayoutAssignmentTest, AllReduceLayoutMissmatch) { // Pin non matching layouts to parameter and root. const char* module_str = R"( HloModule test_module add { lhs = f32[] parameter(0) rhs = f32[] parameter(1) ROOT add = f32[] add(lhs, rhs) } ENTRY entry_computation { param = (f32[2,2]) parameter(0) gte = f32[2,2] get-tuple-element(param), index=0 ar.0 = f32[2,2] cross-replica-sum(gte), all_reduce_id=0, replica_groups={{0}}, to_apply=add, sharding={maximal device=0} const = f32[2,2] constant(f32[2,2]{{0,1},{2,3}}) ROOT ar.1 = f32[2,2] cross-replica-sum(const), all_reduce_id=0, replica_groups={{0}}, to_apply=add, sharding={maximal device=1} })"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(module_str)); ComputationLayout computation_layout( module->entry_computation()->ComputeProgramShape()); Shape param_shape = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShapeWithLayout(F32, {2, 2}, {0, 1})}); TF_ASSERT_OK( computation_layout.mutable_parameter_layout(0)->CopyLayoutFromShape( param_shape)); computation_layout.mutable_result_layout()->ResetLayout( LayoutUtil::MakeLayout({1, 0})); ChannelLayoutConstraints channel_constraints; AssignLayouts(module.get(), &computation_layout, &channel_constraints); EXPECT_THAT(LayoutOf(module.get(), "gte"), ElementsAre(0, 1)); EXPECT_THAT(LayoutOf(module.get(), "ar.0"), ElementsAre(0, 1)); EXPECT_THAT(LayoutOf(module.get(), "ar.1"), ElementsAre(0, 1)); const HloInstruction* root = module->entry_computation()->root_instruction(); EXPECT_THAT(root->shape().layout().minor_to_major(), ElementsAre(1, 0)); } TEST_F(LayoutAssignmentTest, CopySliceOperandToAvoidImplicitLayoutChange) { const char* module_str = R"( HloModule CopySliceOperandToAvoidImplicitLayoutChange ENTRY CopySliceOperandToAvoidImplicitLayoutChange { par0 = f32[3,4]{1,0} parameter(0) par1 = f32[4,5]{0,1} parameter(1) slice0 = f32[3,4] slice(par1), slice={[1:4],[1:5]} ROOT add0 = f32[3,4]{1,0} add(par0,slice0) } )"; ParseAndVerifyModule(module_str); auto compiled_module = backend() .compiler() ->RunHloPasses(module().Clone(), backend().default_stream_executor(), /*device_allocator=*/nullptr) .ConsumeValueOrDie(); HloInstruction* root = compiled_module->entry_computation()->root_instruction(); Shape shape_copy = ShapeUtil::MakeShapeWithLayout(F32, {4, 5}, {1, 0}); EXPECT_THAT(root, op::Add(op::Parameter(), op::Slice(AllOf(op::Copy(op::Parameter(1)), op::ShapeWithLayout(shape_copy))))); } TEST_F(LayoutAssignmentTest, CopyDSliceOperandToAvoidImplicitLayoutChange) { const char* module_str = R"( HloModule CopyDSliceOperandToAvoidImplicitLayoutChange ENTRY CopyDSliceOperandToAvoidImplicitLayoutChange { par0 = f32[3,4]{1,0} parameter(0) par1 = f32[4,5]{0,1} parameter(1) par2 = s32[2] parameter(2) dslice0 = f32[3,4] dynamic-slice(par1, par2), dynamic_slice_sizes={3,4} ROOT add0 = f32[3,4]{1,0} add(par0,dslice0) } )"; ParseAndVerifyModule(module_str); auto compiled_module = backend() .compiler() ->RunHloPasses(module().Clone(), backend().default_stream_executor(), /*device_allocator=*/nullptr) .ConsumeValueOrDie(); HloInstruction* root = compiled_module->entry_computation()->root_instruction(); Shape shape_copy = ShapeUtil::MakeShapeWithLayout(F32, {4, 5}, {1, 0}); EXPECT_THAT(root, op::Add(op::Parameter(), op::DynamicSlice(AllOf(op::Copy(op::Parameter(1)), op::ShapeWithLayout(shape_copy)), op::Parameter(2)))); } TEST_F(LayoutAssignmentTest, CopyConcatOperandToAvoidImplicitLayoutChange) { const char* module_str = R"( HloModule CopyConcatOperandToAvoidImplicitLayoutChange ENTRY CopyConcatOperandToAvoidImplicitLayoutChange { par0 = f32[3,8]{1,0} parameter(0) par1 = f32[3,5]{0,1} parameter(1) par2 = f32[3,3]{1,0} parameter(2) concat0 = f32[3,8] concatenate(f32[3,5] par1, f32[3,3] par2), dimensions={1} ROOT add0 = f32[3,8]{1,0} add(par0,concat0) } )"; ParseAndVerifyModule(module_str); auto compiled_module = backend() .compiler() ->RunHloPasses(module().Clone(), backend().default_stream_executor(), /*device_allocator=*/nullptr) .ConsumeValueOrDie(); HloInstruction* root = compiled_module->entry_computation()->root_instruction(); Shape shape_copy = ShapeUtil::MakeShapeWithLayout(F32, {3, 5}, {1, 0}); EXPECT_THAT(root, op::Add(op::Parameter(), op::Concatenate(AllOf(op::Copy(op::Parameter(1)), op::ShapeWithLayout(shape_copy)), op::Parameter(2)))); } TEST_F(LayoutAssignmentTest, ConvolutionOperandWithImplicitLayoutChangeNotCopied) { const char* module_str = R"( HloModule ConvolutionOperandWithImplicitLayoutChangeNotCopied ENTRY ConvolutionOperandWithImplicitLayoutChangeNotCopied { par0 = f32[128,3,230,230]{2,3,1,0} parameter(0) par1 = f32[7,7,3,64]{3,2,0,1} parameter(1) ROOT convolution0 = f32[128,64,112,112]{3,2,1,0} convolution(par0, par1), window={size=7x7 stride=2x2}, dim_labels=bf01_01io->bf01, feature_group_count=1 } )"; ParseAndVerifyModule(module_str); auto compiled_module = backend() .compiler() ->RunHloPasses(module().Clone(), backend().default_stream_executor(), /*device_allocator=*/nullptr) .ConsumeValueOrDie(); HloInstruction* root = compiled_module->entry_computation()->root_instruction(); EXPECT_THAT(root, op::Convolution(op::Parameter(0), op::Parameter(1))); } TEST_F(LayoutAssignmentTest, PropagatingLayoutFromResultToOperand) { const char* module_str = R"( HloModule PropagatingLayoutFromResultToOperand ENTRY PropagatingLayoutFromResultToOperand { par0 = f32[4,5]{1,0} parameter(0) ROOT slice0 = f32[3,4]{0,1} slice(par0), slice={[1:4],[1:5]} } )"; ParseAndVerifyModule(module_str); auto compiled_module = backend() .compiler() ->RunHloPasses(module().Clone(), backend().default_stream_executor(), /*device_allocator=*/nullptr) .ConsumeValueOrDie(); HloInstruction* root = compiled_module->entry_computation()->root_instruction(); Shape shape_copy = ShapeUtil::MakeShapeWithLayout(F32, {4, 5}, {0, 1}); EXPECT_THAT(root, op::Slice(AllOf(op::Copy(op::Parameter(0)), op::ShapeWithLayout(shape_copy)))); } TEST_F(LayoutAssignmentTest, TupleCopyOnLayoutMismatch) { // The first infeed uses layout {0,1}, while the second uses layout {1,0}. // The mismatch forces a copy of the tuple. The tuple contains a token, so // layout assignment will fail if it tries to copy the whole tuple. const char* module_str = R"( HloModule TupleCopyOnLayoutMismatch condition.1 (tup: (s32[], token[], f32[512,1024]{0,1})) -> pred[] { tup.1 = (s32[], token[], f32[512,1024]{0,1}) parameter(0) counter.1 = s32[] get-tuple-element(tup.1), index=0 five = s32[] constant(5) ROOT lt = pred[] less-than(counter.1, five) } body.2 (tup: (s32[], token[], f32[512,1024]{0,1})) -> (s32[], token[], f32[512,1024]{0,1}) { tup.2 = (s32[], token[], f32[512,1024]{0,1}) parameter(0) counter.2 = s32[] get-tuple-element(tup.2), index=0 tok.2 = token[] get-tuple-element(tup.2), index=1 ifeed.2 = (f32[512,1024]{1,0}, token[]) infeed(tok.2) next_tok = token[] get-tuple-element(ifeed.2), index=1 next_buf = f32[512,1024]{1,0} get-tuple-element(ifeed.2), index=0 one = s32[] constant(1) next_counter = s32[] add(counter.2, one) ROOT tup = (s32[], token[], f32[512,1024]{0,1}) tuple(next_counter, next_tok, next_buf) } ENTRY main () -> f32[512,1024]{0,1} { start_tok = token[] after-all() ifeed.3 = (f32[512,1024]{0,1}, token[]) infeed(start_tok) itok = token[] get-tuple-element(ifeed.3), index=1 ibuf = f32[512,1024]{0,1} get-tuple-element(ifeed.3), index=0 zero = s32[] constant(0) itup = (s32[], token[], f32[512,1024]{0,1}) tuple(zero, itok, ibuf) loop = (s32[], token[], f32[512,1024]{0,1}) while(itup), condition=condition.1, body=body.2 ROOT result = f32[512,1024]{0,1} get-tuple-element(loop), index=2 } )"; ParseAndVerifyModule(module_str); ComputationLayout computation_layout( module().entry_computation()->ComputeProgramShape()); // Sanity check to verify that there's a layout mismatch. EXPECT_THAT(LayoutOf(&module(), "ibuf"), ElementsAre(0, 1)); EXPECT_THAT(LayoutOf(&module(), "next_buf"), ElementsAre(1, 0)); AssignLayouts(&module(), &computation_layout); // Make sure that layout assignment did not magically eliminate the mismatch, // in which case the test didn't prove anything. EXPECT_THAT(LayoutOf(&module(), "ibuf"), ElementsAre(0, 1)); EXPECT_THAT(LayoutOf(&module(), "next_buf"), ElementsAre(1, 0)); } TEST_F(LayoutAssignmentTest, CustomCallNotLayoutConstrained) { const char* module_str = R"( HloModule CustomCallNotLayoutConstrained ENTRY %CustomCallWithNotLayoutConstrained (p: f32[42,2,3]) -> f32[1,2,3,4] { %p = f32[42,2,3] parameter(0) ROOT %custom-call = f32[1,2,3,4] custom-call(f32[42,2,3] %p), custom_call_target="baz" } )"; // Try with a couple different layouts. In each case the custom calls operand // and result layout should match that of the computation. { TF_ASSERT_OK_AND_ASSIGN( std::unique_ptr<VerifiedHloModule> module, ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())); ComputationLayout computation_layout = module->entry_computation_layout(); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(ShapeUtil::MakeShapeWithLayout(F32, {42, 2, 3}, {0, 2, 1})); *computation_layout.mutable_result_layout() = ShapeLayout( ShapeUtil::MakeShapeWithLayout(F32, {1, 2, 3, 4}, {3, 2, 0, 1})); AssignLayouts(module.get(), &computation_layout); HloInstruction* root = module->entry_computation()->root_instruction(); ASSERT_THAT(root, op::CustomCall(op::Parameter())); ExpectLayoutIs(root->shape(), {3, 2, 0, 1}); ExpectLayoutIs(root->operand(0)->shape(), {0, 2, 1}); } { TF_ASSERT_OK_AND_ASSIGN( std::unique_ptr<VerifiedHloModule> module, ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())); ComputationLayout computation_layout = module->entry_computation_layout(); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(ShapeUtil::MakeShapeWithLayout(F32, {42, 2, 3}, {0, 1, 2})); *computation_layout.mutable_result_layout() = ShapeLayout( ShapeUtil::MakeShapeWithLayout(F32, {1, 2, 3, 4}, {0, 2, 3, 1})); AssignLayouts(module.get(), &computation_layout); HloInstruction* root = module->entry_computation()->root_instruction(); ASSERT_THAT(root, op::CustomCall(op::Parameter())); ExpectLayoutIs(root->shape(), {0, 2, 3, 1}); ExpectLayoutIs(root->operand(0)->shape(), {0, 1, 2}); } } TEST_F(LayoutAssignmentTest, CustomCallLayoutConstrained) { const char* module_str = R"( HloModule CustomCallLayoutConstrained ENTRY %CustomCallWithLayoutConstraints (p0: f32[4,4], p1: f32[2,3]) -> f32[1,2,3,4] { %p0 = f32[4,4] parameter(0) %p1 = f32[2,3] parameter(1) ROOT %custom-call = f32[1,2,3,4]{3,2,0,1} custom-call(f32[4,4] %p0, f32[2,3] %p1), custom_call_target="baz", operand_layout_constraints={f32[4,4]{0,1}, f32[2,3]{1,0}} } )"; TF_ASSERT_OK_AND_ASSIGN( std::unique_ptr<VerifiedHloModule> module, ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())); ComputationLayout computation_layout = module->entry_computation_layout(); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(ShapeUtil::MakeShapeWithLayout(F32, {4, 4}, {1, 0})); *computation_layout.mutable_parameter_layout(1) = ShapeLayout(ShapeUtil::MakeShapeWithLayout(F32, {2, 3}, {1, 0})); *computation_layout.mutable_result_layout() = ShapeLayout( ShapeUtil::MakeShapeWithLayout(F32, {1, 2, 3, 4}, {2, 1, 0, 3})); AssignLayouts(module.get(), &computation_layout); // The custom call should be partially encapsulated in kCopy instructions // because of the layout mismatches. ASSERT_THAT(module->entry_computation()->root_instruction(), op::Copy(op::CustomCall(op::Copy(), op::Parameter()))); const HloInstruction* custom_call = module->entry_computation()->root_instruction()->operand(0); ExpectLayoutIs(custom_call->shape(), {3, 2, 0, 1}); ExpectLayoutIs(custom_call->operand(0)->shape(), {0, 1}); ExpectLayoutIs(custom_call->operand(1)->shape(), {1, 0}); } TEST_F(LayoutAssignmentTest, CustomCallLayoutConstrainedZeroOperands) { const char* module_str = R"( HloModule CustomCallLayoutConstrainedZeroOperands ENTRY %CustomCallLayoutConstrainedZeroOperands () -> f32[1,2,3,4] { ROOT %custom-call = f32[1,2,3,4]{3,2,0,1} custom-call(), custom_call_target="baz", operand_layout_constraints={} } )"; TF_ASSERT_OK_AND_ASSIGN( std::unique_ptr<VerifiedHloModule> module, ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())); ComputationLayout computation_layout = module->entry_computation_layout(); *computation_layout.mutable_result_layout() = ShapeLayout( ShapeUtil::MakeShapeWithLayout(F32, {1, 2, 3, 4}, {2, 1, 0, 3})); AssignLayouts(module.get(), &computation_layout); ASSERT_THAT(module->entry_computation()->root_instruction(), op::Copy(op::CustomCall())); const HloInstruction* custom_call = module->entry_computation()->root_instruction()->operand(0); ExpectLayoutIs(custom_call->shape(), {3, 2, 0, 1}); } TEST_F(LayoutAssignmentTest, CustomCallLayoutConstrainedTupleOperand) { const char* module_str = R"( HloModule CustomCallLayoutConstrainedTupleOperand ENTRY %CustomCallLayoutConstrainedTupleOperand (p0: f32[4,4], p1: f32[2,3]) -> f32[1,2,3,4] { %p0 = f32[4,4] parameter(0) %p1 = f32[2,3] parameter(1) %tuple = (f32[4,4], f32[2,3]) tuple(%p0, %p1) ROOT %custom-call = f32[1,2,3,4]{3,2,0,1} custom-call(%tuple), custom_call_target="baz", operand_layout_constraints={(f32[4,4]{1,0}, f32[2,3]{0,1})} } )"; TF_ASSERT_OK_AND_ASSIGN( std::unique_ptr<VerifiedHloModule> module, ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())); ComputationLayout computation_layout = module->entry_computation_layout(); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(ShapeUtil::MakeShapeWithLayout(F32, {4, 4}, {1, 0})); *computation_layout.mutable_parameter_layout(1) = ShapeLayout(ShapeUtil::MakeShapeWithLayout(F32, {2, 3}, {1, 0})); *computation_layout.mutable_result_layout() = ShapeLayout( ShapeUtil::MakeShapeWithLayout(F32, {1, 2, 3, 4}, {2, 1, 0, 3})); AssignLayouts(module.get(), &computation_layout); HloInstruction* root = module->entry_computation()->root_instruction(); ExpectLayoutIs(root->shape(), {2, 1, 0, 3}); ASSERT_THAT(module->entry_computation()->root_instruction(), op::Copy(op::CustomCall(op::Tuple()))); const HloInstruction* custom_call = module->entry_computation()->root_instruction()->operand(0); ExpectLayoutIs(custom_call->shape(), {3, 2, 0, 1}); ExpectTupleLayoutIs(custom_call->operand(0)->shape(), {{1, 0}, {0, 1}}); } TEST_F(LayoutAssignmentTest, CustomCallLayoutConstrainedTupleResult) { const char* module_str = R"( HloModule CustomCallLayoutConstrainedTupleResult ENTRY %CustomCallLayoutConstrainedTupleResult (p0: f32[4,4]) -> (f32[4,4]{1,0}, f32[2,3]{0,1}) { %p0 = f32[4,4] parameter(0) ROOT %custom-call = (f32[4,4]{1,0}, f32[2,3]{0,1}) custom-call(%p0), custom_call_target="baz", operand_layout_constraints={f32[4,4]{1,0}} } )"; // Try with a couple different layouts. In each case the custom calls operand // and result layout should match that of the computation. TF_ASSERT_OK_AND_ASSIGN( std::unique_ptr<VerifiedHloModule> module, ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())); ComputationLayout computation_layout = module->entry_computation_layout(); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(ShapeUtil::MakeShapeWithLayout(F32, {4, 4}, {1, 0})); *computation_layout.mutable_result_layout() = ShapeLayout(ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShapeWithLayout(F32, {4, 4}, {1, 0}), ShapeUtil::MakeShapeWithLayout(F32, {2, 3}, {1, 0})})); AssignLayouts(module.get(), &computation_layout); ExpectTupleLayoutIs(module->entry_computation()->root_instruction()->shape(), {{1, 0}, {1, 0}}); const HloInstruction* custom_call = FindInstruction(module.get(), "custom-call"); ExpectTupleLayoutIs(custom_call->shape(), {{1, 0}, {0, 1}}); } } // namespace } // namespace xla
//================================================================================================= /*! // \file src/mathtest/operations/smatdmatkron/DCaDDb.cpp // \brief Source file for the DCaDDb sparse matrix/dense matrix Kronecker product math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DiagonalMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/operations/smatdmatkron/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'DCaDDb'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using DCa = blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeA> >; using DDb = blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeB> >; // Creator type definitions using CDCa = blazetest::Creator<DCa>; using CDDb = blazetest::Creator<DDb>; // Running tests with small matrices for( size_t i=0UL; i<=4UL; ++i ) { for( size_t j=0UL; j<=i; ++j ) { for( size_t k=0UL; k<=4UL; ++k ) { RUN_SMATDMATKRON_OPERATION_TEST( CDCa( i, j ), CDDb( k ) ); } } } // Running tests with large matrices RUN_SMATDMATKRON_OPERATION_TEST( CDCa( 9UL, 7UL ), CDDb( 8UL ) ); RUN_SMATDMATKRON_OPERATION_TEST( CDCa( 16UL, 7UL ), CDDb( 15UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix Kronecker product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/tx_check.h> #include <consensus/validation.h> #include <test/data/sighash.json.h> #include <hash.h> #include <script/interpreter.h> #include <script/script.h> #include <serialize.h> #include <streams.h> #include <test/setup_common.h> #include <util/strencodings.h> #include <version.h> #include <boost/test/unit_test.hpp> #include <univalue.h> extern UniValue read_json(const std::string& jsondata); // Old script.cpp SignatureHash function uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001")); if (nIn >= txTo.vin.size()) { return one; } CMutableTransaction txTmp(txTo); // In case concatenating two scripts ends up with two codeseparators, // or an extra one at the end, this prevents all those possible incompatibilities. FindAndDelete(scriptCode, CScript(OP_CODESEPARATOR)); // Blank out other inputs' signatures for (unsigned int i = 0; i < txTmp.vin.size(); i++) txTmp.vin[i].scriptSig = CScript(); txTmp.vin[nIn].scriptSig = scriptCode; // Blank out some of the outputs if ((nHashType & 0x1f) == SIGHASH_NONE) { // Wildcard payee txTmp.vout.clear(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } else if ((nHashType & 0x1f) == SIGHASH_SINGLE) { // Only lock-in the txout payee at same index as txin unsigned int nOut = nIn; if (nOut >= txTmp.vout.size()) { return one; } txTmp.vout.resize(nOut+1); for (unsigned int i = 0; i < nOut; i++) txTmp.vout[i].SetNull(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } // Blank out other inputs completely, not recommended for open transactions if (nHashType & SIGHASH_ANYONECANPAY) { txTmp.vin[0] = txTmp.vin[nIn]; txTmp.vin.resize(1); } // Serialize and hash CHashWriter ss(SER_GETHASH, 0); ss << txTmp << nHashType; return ss.GetHash(); } void static RandomScript(CScript &script) { static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; script = CScript(); int ops = (InsecureRandRange(10)); for (int i=0; i<ops; i++) script << oplist[InsecureRandRange(sizeof(oplist)/sizeof(oplist[0]))]; } void static RandomTransaction(CMutableTransaction &tx, bool fSingle) { tx.nVersion = InsecureRandRange(2) + 1; tx.vin.clear(); tx.vout.clear(); tx.nLockTime = (InsecureRandBool()) ? InsecureRand32() : 0; int ins = (InsecureRandBits(2)) + 1; int outs = fSingle ? ins : (InsecureRandBits(2)) + 1; for (int in = 0; in < ins; in++) { tx.vin.push_back(CTxIn()); CTxIn &txin = tx.vin.back(); txin.prevout.hash = InsecureRand256(); txin.prevout.n = InsecureRandBits(2); RandomScript(txin.scriptSig); txin.nSequence = (InsecureRandBool()) ? InsecureRand32() : std::numeric_limits<uint32_t>::max(); } for (int out = 0; out < outs; out++) { tx.vout.push_back(CTxOut()); CTxOut &txout = tx.vout.back(); txout.nValue = InsecureRandRange(100000000); RandomScript(txout.scriptPubKey); } } BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(sighash_test) { SeedInsecureRand(false); #if defined(PRINT_SIGHASH_JSON) std::cout << "[\n"; std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n"; int nRandomTests = 500; #else int nRandomTests = 50000; #endif for (int i=0; i<nRandomTests; i++) { int nHashType = InsecureRand32(); CMutableTransaction txTo; RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE); CScript scriptCode; RandomScript(scriptCode); int nIn = InsecureRandRange(txTo.vin.size()); uint256 sh, sho; sho = SignatureHashOld(scriptCode, CTransaction(txTo), nIn, nHashType); sh = SignatureHash(scriptCode, txTo, nIn, nHashType, 0, SigVersion::BASE); #if defined(PRINT_SIGHASH_JSON) CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << txTo; std::cout << "\t[\"" ; std::cout << HexStr(ss) << "\", \""; std::cout << HexStr(scriptCode) << "\", "; std::cout << nIn << ", "; std::cout << nHashType << ", \""; std::cout << sho.GetHex() << "\"]"; if (i+1 != nRandomTests) { std::cout << ","; } std::cout << "\n"; #endif BOOST_CHECK(sh == sho); } #if defined(PRINT_SIGHASH_JSON) std::cout << "]\n"; #endif } // Goal: check that SignatureHash generates correct hash BOOST_AUTO_TEST_CASE(sighash_from_data) { UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); if (test.size() < 1) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } if (test.size() == 1) continue; // comment std::string raw_tx, raw_script, sigHashHex; int nIn, nHashType; uint256 sh; CTransactionRef tx; CScript scriptCode = CScript(); try { // deserialize test data raw_tx = test[0].get_str(); raw_script = test[1].get_str(); nIn = test[2].get_int(); nHashType = test[3].get_int(); sigHashHex = test[4].get_str(); CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION); stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(CheckTransaction(*tx, state), strTest); BOOST_CHECK(state.IsValid()); std::vector<unsigned char> raw = ParseHex(raw_script); scriptCode.insert(scriptCode.end(), raw.begin(), raw.end()); } catch (...) { BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest); continue; } sh = SignatureHash(scriptCode, *tx, nIn, nHashType, 0, SigVersion::BASE); BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest); } } BOOST_AUTO_TEST_SUITE_END()
#include "glow.hpp" #include "../valve_sdk/csgostructs.hpp" #include "../options.hpp" Glow::Glow() { } Glow::~Glow() { // We cannot call shutdown here unfortunately. // Reason is not very straightforward but anyways: // - This destructor will be called when the dll unloads // but it cannot distinguish between manual unload // (pressing the Unload button or calling FreeLibrary) // or unload due to game exit. // What that means is that this destructor will be called // when the game exits. // - When the game is exiting, other dlls might already // have been unloaded before us, so it is not safe to // access intermodular variables or functions. // // Trying to call Shutdown here will crash CSGO when it is // exiting (because we try to access g_GlowObjManager). // } void Glow::Shutdown() { // Remove glow from all entities for(auto i = 0; i < g_GlowObjManager->m_GlowObjectDefinitions.Count(); i++) { auto& glowObject = g_GlowObjManager->m_GlowObjectDefinitions[i]; auto entity = reinterpret_cast<C_BasePlayer*>(glowObject.m_pEntity); if(glowObject.IsUnused()) continue; if(!entity || entity->IsDormant()) continue; glowObject.m_flAlpha = 0.0f; } } void Glow::Run() { for(auto i = 0; i < g_GlowObjManager->m_GlowObjectDefinitions.Count(); i++) { auto& glowObject = g_GlowObjManager->m_GlowObjectDefinitions[i]; auto entity = reinterpret_cast<C_BasePlayer*>(glowObject.m_pEntity); if(glowObject.IsUnused()) continue; if(!entity || entity->IsDormant()) continue; auto class_id = entity->GetClientClass()->m_ClassID; auto color = Color{}; switch(class_id) { case ClassId_CCSPlayer: { auto is_enemy = entity->m_iTeamNum() != g_LocalPlayer->m_iTeamNum(); if(entity->HasC4() && is_enemy && g_Options.glow_c4_carrier) { color = g_Options.color_glow_c4_carrier; break; } if(!g_Options.glow_players || !entity->IsAlive()) continue; if(!is_enemy && g_Options.glow_enemies_only) continue; color = is_enemy ? Color(g_Options.color_glow_enemy) : Color(g_Options.color_glow_ally); glowObject.m_nGlowStyle = is_enemy ? g_Options.glow_type : g_Options.glow_team_type; break; } case ClassId_CChicken: if(!g_Options.glow_chickens) continue; entity->m_bShouldGlow() = true; color = g_Options.color_glow_chickens; break; case ClassId_CBaseAnimating: if(!g_Options.glow_defuse_kits) continue; color = g_Options.color_glow_defuse; break; case ClassId_CPlantedC4: if(!g_Options.glow_planted_c4) continue; color = g_Options.color_glow_planted_c4; break; default: { if(entity->IsWeapon()) { if(!g_Options.glow_weapons) continue; color = g_Options.color_glow_weapons; } } } glowObject.m_flRed = color.r() / 255.0f; glowObject.m_flGreen = color.g() / 255.0f; glowObject.m_flBlue = color.b() / 255.0f; glowObject.m_flAlpha = color.a() / 255.0f; glowObject.m_bRenderWhenOccluded = true; glowObject.m_bRenderWhenUnoccluded = false; } }
/*=========================================================================== * * File: Srprogressdlg.CPP * Author: Dave Humphrey (dave@uesp.net) * Created On: 26 November 2011 * * Description * *=========================================================================*/ /* Include Files */ #include "stdafx.h" #include "common/srerrorhandler.h" #include "resource.h" #include "SrProgressDlg.h" #include "common/srlogfile.h" /*=========================================================================== * * Begin Local Definitions * *=========================================================================*/ #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /*=========================================================================== * End of Local Definitions *=========================================================================*/ /*=========================================================================== * * Begin CSrProgressDlg Message Map * *=========================================================================*/ BEGIN_MESSAGE_MAP(CSrProgressDlg, CDialog) //{{AFX_MSG_MAP(CSrProgressDlg) ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() /*=========================================================================== * End of CSrProgressDlg Message Map *=========================================================================*/ /*=========================================================================== * * Function - int SrEditDefaultProgressCallback (pData); * * Default progress update callback. * *=========================================================================*/ int SrEditDefaultProgressCallback (CSrCallback* pCallback) { CSrProgressDlg* pProgressView; if (pCallback == NULL) return (SRCALLBACK_INVALIDINPUT); pProgressView = (CSrProgressDlg *) pCallback->GetUserPtr(); if (pProgressView == NULL) return (SRCALLBACK_INVALIDINPUT); if (pCallback->GetUpdateTitle()) { pProgressView->UpdateTitle(pCallback->GetTitle()); pCallback->SetUpdateTitle(false); } if (pCallback->GetUpdateLabel()) { pProgressView->UpdateLabel(pCallback->GetLabel()); pCallback->SetUpdateLabel(false); } pProgressView->Update(pCallback->GetPercentDone()); if (pProgressView->GetIsCancelled()) { return (SRCALLBACK_USERABORT); } return (SRCALLBACK_OK); } /*=========================================================================== * End of Function SrEditDefaultProgressCallback() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Constructor * *=========================================================================*/ CSrProgressDlg::CSrProgressDlg (const TCHAR* pTitle, const TCHAR* pLabel) : CDialog(CSrProgressDlg::IDD, NULL) { //{{AFX_DATA_INIT(CSrProgressDlg) //}}AFX_DATA_INIT m_Title = pTitle; m_CancelMsg = _T("Are you sure you wish to abort?"); m_Label = pLabel; m_AllowCancel = true; m_PromptCancel = false; m_RunAsModal = true; m_IsCancelled = false; /* Disable the application window if required */ if (m_RunAsModal) AfxGetMainWnd()->EnableWindow(FALSE); Create(CSrProgressDlg::IDD, NULL); ShowWindow(SW_SHOW); } /*=========================================================================== * End of Class CSrProgressDlg Constructor *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Method - void DoDataExchange (pDX); * *=========================================================================*/ void CSrProgressDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSrProgressDlg) DDX_Control(pDX, IDC_FILE_PERCENT, m_PercentLabel); DDX_Control(pDX, IDC_FILE_PROGRESS, m_ProgressCtrl); DDX_Control(pDX, IDC_FILE_LABEL, m_LabelText); DDX_Control(pDX, IDCANCEL, m_CancelButton); //}}AFX_DATA_MAP } /*=========================================================================== * End of Class Method CSrProgressDlg::DoDataExchange() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Event - void OnCancel (void); * *=========================================================================*/ void CSrProgressDlg::OnCancel (void) { int Result; if (!m_AllowCancel) return; if (m_PromptCancel) { Result = MessageBox(m_CancelMsg, _T("Cancel Operation"), MB_YESNO | MB_ICONEXCLAMATION); if (Result != IDYES) return; } AddSrGeneralError("Action aborted by user!"); m_IsCancelled = true; //CDialog::OnCancel(); } /*=========================================================================== * End of Class Event CSrProgressDlg::OnCancel() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Event - void OnDestroy (void); * *=========================================================================*/ void CSrProgressDlg::OnDestroy (void) { /* Enable the application window if required */ if (m_RunAsModal) AfxGetMainWnd()->EnableWindow(FALSE); CDialog::OnDestroy(); } /*=========================================================================== * End of Class Event CSrProgressDlg::OnDestroy() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Event - BOOL OnInitDialog (); * *=========================================================================*/ BOOL CSrProgressDlg::OnInitDialog() { /* Call the base class event */ CDialog::OnInitDialog(); /* Initialize the controls */ m_ProgressCtrl.SetRange(0, 100); m_ProgressCtrl.SetPos(0); m_CancelButton.ShowWindow(m_AllowCancel ? SW_SHOW : SW_HIDE); UpdateControls(); return (TRUE); } /*=========================================================================== * End of Class Event CSrProgressDlg::OnInitDialog() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Method - BOOL Pump (void); * *=========================================================================*/ BOOL CSrProgressDlg::Pump (void) { MSG msg; while (::PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) { if (!AfxGetApp()->PumpMessage()) { ::PostQuitMessage(0); return FALSE; } } /* Simulate the framework's idle processing mechanism */ LONG lIdle = 0; while (AfxGetApp()->OnIdle(lIdle++)); return TRUE; } /*=========================================================================== * End of Class Method CSrProgressDlg::Pump() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Method - void SetProgress (Progress); * *=========================================================================*/ void CSrProgressDlg::SetProgress (const float Progress) { CString Buffer; m_ProgressCtrl.SetPos((int)Progress); Buffer.Format(_T("%d%%"), (int)Progress); m_PercentLabel.SetWindowText(Buffer); m_ProgressCtrl.UpdateWindow(); m_PercentLabel.UpdateWindow(); m_CancelButton.ShowWindow(m_AllowCancel ? SW_SHOW : SW_HIDE); } /*=========================================================================== * End of Class Method CSrProgressDlg::SetProgress() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Method - void UpdateControls (void); * *=========================================================================*/ void CSrProgressDlg::UpdateControls (void) { SetWindowText(m_Title); m_LabelText.SetWindowText(m_Label); m_CancelButton.ShowWindow(m_AllowCancel ? SW_SHOW : SW_HIDE); } /*=========================================================================== * End of Class Method CSrProgressDlg::UpdateControls() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Method - void UpdateLabel (pString); * *=========================================================================*/ void CSrProgressDlg::UpdateLabel (const TCHAR* pString) { m_LabelText.SetWindowText(pString); m_LabelText.RedrawWindow(); } /*=========================================================================== * End of Class Method CSrProgressDlg::UpdateLabel() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Method - void UpdateTitle (pString); * *=========================================================================*/ void CSrProgressDlg::UpdateTitle (const TCHAR* pString) { SetWindowText(pString); RedrawWindow(); } /*=========================================================================== * End of Class Method CSrProgressDlg::UpdateTitle() *=========================================================================*/ /*=========================================================================== * * Class CSrProgressDlg Method - void Update (Percent); * * Main progress update callback. Updates the progress and pumps any * waiting messages. * *=========================================================================*/ void CSrProgressDlg::Update (const float Percent) { SetProgress(Percent); m_CancelButton.ShowWindow(m_AllowCancel ? SW_SHOW : SW_HIDE); Pump(); } /*=========================================================================== * End of Class Method CSrProgressDlg::Update() *=========================================================================*/ /*=========================================================================== * * Function - CSrProgressDlg* ShowSrProgressDlg (pTitle, pLabel, ...); * * Creates and displays a new progress dialog. Ensure to destroy the * dialog using the DestroySrProgressDlg() function. * *=========================================================================*/ CSrProgressDlg* ShowSrProgressDlg (const TCHAR* pTitle, const TCHAR* pLabel, ...) { CSrProgressDlg* pProgressDlg; CString Buffer; va_list Args; va_start(Args, pLabel); Buffer.FormatV(pLabel, Args); va_end(Args); pProgressDlg = new CSrProgressDlg(pTitle, Buffer); return (pProgressDlg); } /*=========================================================================== * End of Function ShowSrProgressDlg() *=========================================================================*/ /*=========================================================================== * * Function - void DestroySrProgressDlg (pProgressDlg); * * Closes and destroys a progress dialog created by ShowSrProgressDlg(). * *=========================================================================*/ void DestroySrProgressDlg (CSrProgressDlg* pProgressDlg) { if (pProgressDlg != NULL) { pProgressDlg->EndDialog(IDOK); delete pProgressDlg; } } /*=========================================================================== * End of Function DestroySrProgressDlg() *=========================================================================*/
// Copyright (c) 2016-2020 The thecoffeecoins Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/modaloverlay.h> #include <qt/forms/ui_modaloverlay.h> #include <chainparams.h> #include <qt/guiutil.h> #include <QEasingCurve> #include <QPropertyAnimation> #include <QResizeEvent> ModalOverlay::ModalOverlay(bool enable_wallet, QWidget *parent) : QWidget(parent), ui(new Ui::ModalOverlay), bestHeaderHeight(0), bestHeaderDate(QDateTime()), layerIsVisible(false), userClosed(false) { ui->setupUi(this); connect(ui->closeButton, &QPushButton::clicked, this, &ModalOverlay::closeClicked); if (parent) { parent->installEventFilter(this); raise(); } blockProcessTime.clear(); setVisible(false); if (!enable_wallet) { ui->infoText->setVisible(false); ui->infoTextStrong->setText(tr("%1 is currently syncing. It will download headers and blocks from peers and validate them until reaching the tip of the block chain.").arg(PACKAGE_NAME)); } m_animation.setTargetObject(this); m_animation.setPropertyName("pos"); m_animation.setDuration(300 /* ms */); m_animation.setEasingCurve(QEasingCurve::OutQuad); } ModalOverlay::~ModalOverlay() { delete ui; } bool ModalOverlay::eventFilter(QObject * obj, QEvent * ev) { if (obj == parent()) { if (ev->type() == QEvent::Resize) { QResizeEvent * rev = static_cast<QResizeEvent*>(ev); resize(rev->size()); if (!layerIsVisible) setGeometry(0, height(), width(), height()); if (m_animation.endValue().toPoint().y() > 0) { m_animation.setEndValue(QPoint(0, height())); } } else if (ev->type() == QEvent::ChildAdded) { raise(); } } return QWidget::eventFilter(obj, ev); } //! Tracks parent widget changes bool ModalOverlay::event(QEvent* ev) { if (ev->type() == QEvent::ParentAboutToChange) { if (parent()) parent()->removeEventFilter(this); } else if (ev->type() == QEvent::ParentChange) { if (parent()) { parent()->installEventFilter(this); raise(); } } return QWidget::event(ev); } void ModalOverlay::setKnownBestHeight(int count, const QDateTime& blockDate) { if (count > bestHeaderHeight) { bestHeaderHeight = count; bestHeaderDate = blockDate; UpdateHeaderSyncLabel(); } } void ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress) { QDateTime currentDate = QDateTime::currentDateTime(); // keep a vector of samples of verification progress at height blockProcessTime.push_front(qMakePair(currentDate.toMSecsSinceEpoch(), nVerificationProgress)); // show progress speed if we have more than one sample if (blockProcessTime.size() >= 2) { double progressDelta = 0; double progressPerHour = 0; qint64 timeDelta = 0; qint64 remainingMSecs = 0; double remainingProgress = 1.0 - nVerificationProgress; for (int i = 1; i < blockProcessTime.size(); i++) { QPair<qint64, double> sample = blockProcessTime[i]; // take first sample after 500 seconds or last available one if (sample.first < (currentDate.toMSecsSinceEpoch() - 500 * 1000) || i == blockProcessTime.size() - 1) { progressDelta = blockProcessTime[0].second - sample.second; timeDelta = blockProcessTime[0].first - sample.first; progressPerHour = progressDelta / (double) timeDelta * 1000 * 3600; remainingMSecs = (progressDelta > 0) ? remainingProgress / progressDelta * timeDelta : -1; break; } } // show progress increase per hour ui->progressIncreasePerH->setText(QString::number(progressPerHour * 100, 'f', 2)+"%"); // show expected remaining time if(remainingMSecs >= 0) { ui->expectedTimeLeft->setText(GUIUtil::formatNiceTimeOffset(remainingMSecs / 1000.0)); } else { ui->expectedTimeLeft->setText(QObject::tr("unknown")); } static const int MAX_SAMPLES = 5000; if (blockProcessTime.count() > MAX_SAMPLES) { blockProcessTime.remove(MAX_SAMPLES, blockProcessTime.count() - MAX_SAMPLES); } } // show the last block date ui->newestBlockDate->setText(blockDate.toString()); // show the percentage done according to nVerificationProgress ui->percentageProgress->setText(QString::number(nVerificationProgress*100, 'f', 2)+"%"); if (!bestHeaderDate.isValid()) // not syncing return; // estimate the number of headers left based on nPowTargetSpacing // and check if the gui is not aware of the best header (happens rarely) int estimateNumHeadersLeft = bestHeaderDate.secsTo(currentDate) / Params().GetConsensus().nPowTargetSpacing; bool hasBestHeader = bestHeaderHeight >= count; // show remaining number of blocks if (estimateNumHeadersLeft < HEADER_HEIGHT_DELTA_SYNC && hasBestHeader) { ui->numberOfBlocksLeft->setText(QString::number(bestHeaderHeight - count)); } else { UpdateHeaderSyncLabel(); ui->expectedTimeLeft->setText(tr("Unknown…")); } } void ModalOverlay::UpdateHeaderSyncLabel() { int est_headers_left = bestHeaderDate.secsTo(QDateTime::currentDateTime()) / Params().GetConsensus().nPowTargetSpacing; ui->numberOfBlocksLeft->setText(tr("Unknown. Syncing Headers (%1, %2%)…").arg(bestHeaderHeight).arg(QString::number(100.0 / (bestHeaderHeight + est_headers_left) * bestHeaderHeight, 'f', 1))); } void ModalOverlay::toggleVisibility() { showHide(layerIsVisible, true); if (!layerIsVisible) userClosed = true; } void ModalOverlay::showHide(bool hide, bool userRequested) { if ( (layerIsVisible && !hide) || (!layerIsVisible && hide) || (!hide && userClosed && !userRequested)) return; Q_EMIT triggered(hide); if (!isVisible() && !hide) setVisible(true); m_animation.setStartValue(QPoint(0, hide ? 0 : height())); // The eventFilter() updates the endValue if it is required for QEvent::Resize. m_animation.setEndValue(QPoint(0, hide ? height() : 0)); m_animation.start(QAbstractAnimation::KeepWhenStopped); layerIsVisible = !hide; } void ModalOverlay::closeClicked() { showHide(true); userClosed = true; }
/****************************************************************************** * Copyright 2019 The Apollo Authors. 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 **/ #include "modules/planning/scenarios/park_and_go/park_and_go_scenario.h" #include "gtest/gtest.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace park_and_go { class ParkAndGoTest : public ::testing::Test { public: virtual void SetUp() {} protected: std::unique_ptr<ParkAndGoScenario> scenario_; }; TEST_F(ParkAndGoTest, VerifyConf) { ScenarioConfig config; EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile( FLAGS_scenario_park_and_go_config_file, &config)); } } // namespace park_and_go } // namespace scenario } // namespace planning } // namespace apollo
// {{{ MIT License // Copyright 2017 Roland Kaminski // 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 <clingo/script.h> #include <clingo/incmode.hh> #include <clingo/control.hh> #include <clingo/ast.hh> #include <gringo/input/nongroundparser.hh> #include <gringo/input/groundtermparser.hh> #include <gringo/input/programbuilder.hh> #include <gringo/input/program.hh> #include <gringo/ground/program.hh> #include <gringo/output/output.hh> #include <gringo/output/statements.hh> #include <gringo/logger.hh> #include <clingo/scripts.hh> #include <potassco/application.h> #include <potassco/program_opts/typed_value.h> #include <climits> #include <iostream> #include <stdexcept> namespace Gringo { using StrVec = std::vector<std::string>; struct GringoOptions { using Foobar = std::vector<Sig>; StrVec defines; Output::OutputOptions outputOptions; Output::OutputFormat outputFormat = Output::OutputFormat::INTERMEDIATE; bool verbose = false; bool wNoOperationUndefined = false; bool wNoAtomUndef = false; bool wNoFileIncluded = false; bool wNoVariableUnbounded = false; bool wNoGlobalVariable = false; bool wNoOther = false; bool rewriteMinimize = false; bool keepFacts = false; Foobar foobar; }; static inline std::vector<std::string> split(std::string const &source, char const *delimiter = " ", bool keepEmpty = false) { std::vector<std::string> results; size_t prev = 0; size_t next = 0; while ((next = source.find_first_of(delimiter, prev)) != std::string::npos) { if (keepEmpty || (next - prev != 0)) { results.push_back(source.substr(prev, next - prev)); } prev = next + 1; } if (prev < source.size()) { results.push_back(source.substr(prev)); } return results; } static inline bool parseFoobar(const std::string& str, GringoOptions::Foobar& foobar) { for (auto &x : split(str, ",")) { auto y = split(x, "/"); if (y.size() != 2) { return false; } unsigned a; if (!Potassco::string_cast<unsigned>(y[1], a)) { return false; } bool sign = !y[0].empty() && y[0][0] == '-'; if (sign) { y[0] = y[0].substr(1); } foobar.emplace_back(y[0].c_str(), a, sign); } return true; } #define LOG if (opts.verbose) std::cerr struct IncrementalControl : Control { IncrementalControl(Output::OutputBase &out, StrVec const &files, GringoOptions const &opts) : out(out) , scripts(g_scripts()) , pb(scripts, prg, out, defs, opts.rewriteMinimize) , parser(pb, incmode) , opts(opts) { using namespace Gringo; // TODO: should go where python script is once refactored out.keepFacts = opts.keepFacts; logger_.enable(Warnings::OperationUndefined, !opts.wNoOperationUndefined); logger_.enable(Warnings::AtomUndefined, !opts.wNoAtomUndef); logger_.enable(Warnings::VariableUnbounded, !opts.wNoVariableUnbounded); logger_.enable(Warnings::FileIncluded, !opts.wNoFileIncluded); logger_.enable(Warnings::GlobalVariable, !opts.wNoGlobalVariable); logger_.enable(Warnings::Other, !opts.wNoOther); for (auto &x : opts.defines) { LOG << "define: " << x << std::endl; parser.parseDefine(x, logger_); } for (auto &x : files) { LOG << "file: " << x << std::endl; parser.pushFile(std::string(x), logger_); } if (files.empty()) { LOG << "reading from stdin" << std::endl; parser.pushFile("-", logger_); } parse(); } Logger &logger() override { return logger_; } void parse() { if (!parser.empty()) { parser.parse(logger_); defs.init(logger_); parsed = true; } } void ground(Control::GroundVec const &parts, Context *context) override { // NOTE: it would be cool to have assumptions in the lparse output auto exit = onExit([this]{ scripts.resetContext(); }); if (context) { scripts.setContext(*context); } parse(); if (parsed) { LOG << "************** parsed program **************" << std::endl << prg; prg.rewrite(defs, logger_); LOG << "************* rewritten program ************" << std::endl << prg; prg.check(logger_); if (logger_.hasError()) { throw std::runtime_error("grounding stopped because of errors"); } parsed = false; } if (!grounded) { if (!initialized_) { initialized_ = true; out.init(incremental_); } out.beginStep(); grounded = true; } if (!parts.empty()) { Ground::Parameters params; std::set<Sig> sigs; for (auto &x : parts) { params.add(x.first, SymVec(x.second)); sigs.emplace(x.first, numeric_cast<uint32_t>(x.second.size()), false); } Ground::Program gPrg(prg.toGround(sigs, out.data, logger_)); LOG << "************* intermediate program *************" << std::endl << gPrg << std::endl; LOG << "*************** grounded program ***************" << std::endl; gPrg.ground(params, scripts, out, logger_); } } void add(std::string const &name, StringVec const &params, std::string const &part) override { Location loc("<block>", 1, 1, "<block>", 1, 1); Input::IdVec idVec; for (auto &x : params) { idVec.emplace_back(loc, x); } parser.pushBlock(name, std::move(idVec), part, logger_); parse(); } Symbol getConst(std::string const &name) override { parse(); auto ret = defs.defs().find(name.c_str()); if (ret != defs.defs().end()) { bool undefined = false; Symbol val = std::get<2>(ret->second)->eval(undefined, logger_); if (!undefined) { return val; } } return Symbol(); } void load(std::string const &filename) override { parser.pushFile(std::string(filename), logger_); parse(); } bool blocked() override { return false; } USolveFuture solve(Assumptions ass, clingo_solve_mode_bitset_t, USolveEventHandler cb) override { grounded = false; out.endStep(ass); out.reset(true); return gringo_make_unique<DefaultSolveFuture>(std::move(cb)); } void interrupt() override { } void *claspFacade() override { return nullptr; } void beginAdd() override { parse(); } void add(clingo_ast_statement_t const &stm) override { Input::parseStatement(pb, logger_, stm); } void endAdd() override { defs.init(logger_); } void registerObserver(UBackend prg, bool replace) override { out.registerObserver(std::move(prg), replace); } Potassco::AbstractStatistics *statistics() override { throw std::runtime_error("statistics not supported (yet)"); } bool isConflicting() noexcept override { return false; } void assignExternal(Potassco::Atom_t ext, Potassco::Value_t val) override { if (auto *b = out.backend_()) { b->external(ext, val); } } SymbolicAtoms &getDomain() override { throw std::runtime_error("domain introspection not supported"); } ConfigProxy &getConf() override { throw std::runtime_error("configuration not supported"); } void registerPropagator(UProp, bool) override { throw std::runtime_error("theory propagators not supported"); } void useEnumAssumption(bool) override { } bool useEnumAssumption() override { return false; } virtual ~IncrementalControl() { } Output::DomainData const &theory() const override { return out.data; } void cleanupDomains() override { } bool beginAddBackend() override { backend_ = out.backend(logger()); return backend_ != nullptr; } Backend *getBackend() override { if (!backend_) { throw std::runtime_error("backend not available"); } return backend_; } Id_t addAtom(Symbol sym) override { return out.addAtom(sym); } void endAddBackend() override { out.endGround(logger()); backend_ = nullptr; } Potassco::Atom_t addProgramAtom() override { return out.data.newAtom(); } Input::GroundTermParser termParser; Output::OutputBase &out; Scripts &scripts; Defines defs; Input::Program prg; Input::NongroundProgramBuilder pb; Input::NonGroundParser parser; GringoOptions const &opts; Logger logger_; Backend *backend_ = nullptr; std::unique_ptr<Input::NongroundProgramBuilder> builder; bool incmode = false; bool parsed = false; bool grounded = false; bool initialized_ = false; bool incremental_ = true; }; #undef LOG static bool parseConst(const std::string& str, std::vector<std::string>& out) { out.push_back(str); return true; } inline void enableAll(GringoOptions& out, bool enable) { out.wNoAtomUndef = !enable; out.wNoFileIncluded = !enable; out.wNoOperationUndefined = !enable; out.wNoVariableUnbounded = !enable; out.wNoGlobalVariable = !enable; out.wNoOther = !enable; } inline bool parseWarning(const std::string& str, GringoOptions& out) { if (str == "none") { enableAll(out, false); return true; } if (str == "all") { enableAll(out, true); return true; } if (str == "no-atom-undefined") { out.wNoAtomUndef = true; return true; } if (str == "atom-undefined") { out.wNoAtomUndef = false; return true; } if (str == "no-file-included") { out.wNoFileIncluded = true; return true; } if (str == "file-included") { out.wNoFileIncluded = false; return true; } if (str == "no-operation-undefined") { out.wNoOperationUndefined = true; return true; } if (str == "operation-undefined") { out.wNoOperationUndefined = false; return true; } if (str == "no-variable-unbounded") { out.wNoVariableUnbounded = true; return true; } if (str == "variable-unbounded") { out.wNoVariableUnbounded = false; return true; } if (str == "no-global-variable") { out.wNoGlobalVariable = true; return true; } if (str == "global-variable") { out.wNoGlobalVariable = false; return true; } if (str == "no-other") { out.wNoOther = true; return true; } if (str == "other") { out.wNoOther = false; return true; } return false; } static bool parseText(const std::string&, GringoOptions& out) { out.outputFormat = Output::OutputFormat::TEXT; return true; } struct GringoApp : public Potassco::Application { using StringSeq = std::vector<std::string>; virtual const char* getName() const { return "gringo"; } virtual const char* getVersion() const { return CLINGO_VERSION_STRING; } virtual HelpOpt getHelpOption() const { return HelpOpt("Print (<n {1=default|2=advanced}) help and exit", 2); } virtual void initOptions(Potassco::ProgramOptions::OptionContext& root) { using namespace Potassco::ProgramOptions; grOpts_.defines.clear(); grOpts_.verbose = false; OptionGroup gringo("Gringo Options"); gringo.addOptions() ("text,t", storeTo(grOpts_, parseText)->flag(), "Print plain text format") ("const,c", storeTo(grOpts_.defines, parseConst)->composing()->arg("<id>=<term>"), "Replace term occurrences of <id> with <term>") ("output,o,@1", storeTo(grOpts_.outputFormat = Output::OutputFormat::INTERMEDIATE, values<Output::OutputFormat>() ("intermediate", Output::OutputFormat::INTERMEDIATE) ("text", Output::OutputFormat::TEXT) ("reify", Output::OutputFormat::REIFY) ("smodels", Output::OutputFormat::SMODELS)), "Choose output format:\n" " intermediate: print intermediate format\n" " text : print plain text format\n" " reify : print program as reified facts\n" " smodels : print smodels format\n" " (only supports basic features)") ("output-debug,@1", storeTo(grOpts_.outputOptions.debug = Output::OutputDebug::NONE, values<Output::OutputDebug>() ("none", Output::OutputDebug::NONE) ("text", Output::OutputDebug::TEXT) ("translate", Output::OutputDebug::TRANSLATE) ("all", Output::OutputDebug::ALL)), "Print debug information during output:\n" " none : no additional info\n" " text : print rules as plain text (prefix %%)\n" " translate: print translated rules as plain text (prefix %%%%)\n" " all : combines text and translate") ("warn,W,@1", storeTo(grOpts_, parseWarning)->arg("<warn>")->composing(), "Enable/disable warnings:\n" " none: disable all warnings\n" " all: enable all warnings\n" " [no-]atom-undefined: a :- b.\n" " [no-]file-included: #include \"a.lp\". #include \"a.lp\".\n" " [no-]operation-undefined: p(1/0).\n" " [no-]variable-unbounded: $x > 10.\n" " [no-]global-variable: :- #count { X } = 1, X = 1.\n" " [no-]other: uncategorized warnings") ("rewrite-minimize,@1", flag(grOpts_.rewriteMinimize = false), "Rewrite minimize constraints into rules") ("keep-facts,@1", flag(grOpts_.keepFacts = false), "Do not remove facts from normal rules") ("reify-sccs,@1", flag(grOpts_.outputOptions.reifySCCs = false), "Calculate SCCs for reified output") ("reify-steps,@1", flag(grOpts_.outputOptions.reifySteps = false), "Add step numbers to reified output") ("foobar,@4", storeTo(grOpts_.foobar, parseFoobar), "Foobar") ; root.add(gringo); OptionGroup basic("Basic Options"); basic.addOptions() ("file,f,@2", storeTo(input_)->composing(), "Input files") ; root.add(basic); } virtual void validateOptions(const Potassco::ProgramOptions::OptionContext&, const Potassco::ProgramOptions::ParsedOptions&, const Potassco::ProgramOptions::ParsedValues&) { } virtual void setup() { } static bool parsePositional(std::string const &, std::string& out) { out = "file"; return true; } virtual Potassco::ProgramOptions::PosOption getPositional() const { return parsePositional; } virtual void printHelp(const Potassco::ProgramOptions::OptionContext& root) { printf("%s version %s\n", getName(), getVersion()); printUsage(); Potassco::ProgramOptions::FileOut out(stdout); root.description(out); printf("\nType '%s --help=2' for further options.\n", getName()); printf("\n"); printUsage(); } virtual void printVersion() { char const *py_version = clingo_script_version_(clingo_ast_script_type_python); char const *lua_version = clingo_script_version_(clingo_ast_script_type_lua); Potassco::Application::printVersion(); printf("\n"); printf("libgringo version " CLINGO_VERSION "\n"); printf("Configuration: %s%s, %s%s\n", py_version ? "with Python " : "without Python", py_version ? py_version : "", lua_version ? "with Lua " : "without Lua", lua_version ? lua_version : ""); printf("License: The MIT License <https://opensource.org/licenses/MIT>\n"); fflush(stdout); } void ground(Output::OutputBase &out) { using namespace Gringo; IncrementalControl inc(out, input_, grOpts_); if (inc.scripts.callable("main")) { inc.incremental_ = true; inc.scripts.main(inc); } else if (inc.incmode) { inc.incremental_ = true; incmode(inc); } else { Control::GroundVec parts; parts.emplace_back("base", SymVec{}); inc.incremental_ = false; inc.ground(parts, nullptr); inc.solve({nullptr, 0}, 0, nullptr)->get(); } } virtual void run() { try { using namespace Gringo; grOpts_.verbose = verbose() == UINT_MAX; Output::OutputPredicates outPreds; for (auto &x : grOpts_.foobar) { outPreds.emplace_back(Location("<cmd>",1,1,"<cmd>", 1,1), x, false); } Potassco::TheoryData data; data.update(); Output::OutputBase out(data, std::move(outPreds), std::cout, grOpts_.outputFormat, grOpts_.outputOptions); ground(out); } catch (GringoError const &e) { std::cerr << e.what() << std::endl; throw std::runtime_error("fatal error"); } catch (...) { throw; } } private: StringSeq input_; GringoOptions grOpts_; }; } // namespace Gringo extern "C" CLINGO_VISIBILITY_DEFAULT int gringo_main_(int argc, char *argv[]) { Gringo::GringoApp app; return app.main(argc, argv); }
#include "Cow.h" #include <iostream> Cow::Cow(unsigned age): Animal(age) { std::cout<<"Cow"<<std::endl; } void Cow::saySomething() const { std::cout<<"Cow: Muuu..."<<std::endl; } void Cow::print() const { std::cout<<"Animal with age "<<m_age<<", Cow"<<std::endl; } Cow::~Cow() { std::cout<<"Bye Cow"<<std::endl; }
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2018 by Blender Foundation. * All rights reserved. * * Contributor(s): MARUI-PlugIn * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/vr/intern/vr_widget_cursor.cpp * \ingroup vr * */ #include "vr_types.h" #include <list> #include "vr_main.h" #include "vr_ui.h" #include "vr_widget_cursor.h" #include "vr_math.h" #include "BLI_math.h" #include "BKE_context.h" #include "BKE_scene.h" #include "DEG_depsgraph.h" #include "DNA_scene_types.h" //#include "ED_undo.h" #include "WM_api.h" #include "WM_types.h" /**************************************************************************************************\ * \class Widget_Cursor * *************************************************************************************************** * Interaction widget for the Blender cursor. * **************************************************************************************************/ Widget_Cursor Widget_Cursor::obj; void Widget_Cursor::cursor_teleport() { /* Convert cursor position from Blender to real space. */ Scene *scene = CTX_data_scene(vr_get_obj()->ctx); static Mat44f m_blender; BKE_scene_cursor_to_mat4(&scene->cursor, m_blender.m); static Mat44f m_real = VR_Math::identity_f; memcpy(m_real.m[3], VR_UI::convert_space(m_blender, VR_SPACE_BLENDER, VR_SPACE_REAL).m[3], sizeof(float) * 3); /* Apply navigation transformation to move from the HMD to the cursor. */ static Mat44f ref = VR_Math::identity_f; memcpy(ref.m[3], VR_UI::hmd_position_get(VR_SPACE_REAL).m[3], sizeof(float) * 3); VR_UI::navigation_apply_transformation(m_real.inverse() * ref, VR_SPACE_REAL); } void Widget_Cursor::cursor_set_to_world_origin() { /* Update the Blender 3D cursor */ bContext *C = vr_get_obj()->ctx; Scene *scene = CTX_data_scene(C); BKE_scene_cursor_from_mat4(&scene->cursor, (float(*)[4])VR_Math::identity_f.m, false); WM_event_add_notifier(C, NC_SCENE | NA_EDITED, scene); DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE); // ED_undo_push(C, "Cursor"); } void Widget_Cursor::cursor_set_to_object_origin() { bContext *C = vr_get_obj()->ctx; if (CTX_data_edit_object(C)) { return; } ListBase ctx_data_list; Object *obact = NULL; int num_objects = 0; CTX_data_selected_objects(C, &ctx_data_list); CollectionPointerLink *ctx_link = (CollectionPointerLink *)ctx_data_list.first; static Mat44f center; memset(center.m, 0, sizeof(float) * 4 * 4); for (; ctx_link; ctx_link = ctx_link->next) { obact = (Object *)ctx_link->ptr.data; if (!obact) { continue; } /* Average object rotations (z-axis). */ *(Coord3Df *)center.m[2] += *(Coord3Df *)obact->obmat[2]; /* Average object positions. */ *(Coord3Df *)center.m[3] += *(Coord3Df *)obact->obmat[3]; ++num_objects; } *(Coord3Df *)center.m[2] /= num_objects; (*(Coord3Df *)center.m[2]).normalize_in_place(); static float rot[3][3]; static float z_axis[3] = {0.0f, 0.0f, 1.0f}; rotation_between_vecs_to_mat3(rot, z_axis, center.m[2]); *(Coord3Df *)center.m[3] /= num_objects; /* Update the Blender 3D cursor */ Scene *scene = CTX_data_scene(C); BKE_scene_cursor_mat3_to_rot(&scene->cursor, rot, false); copy_v3_v3(scene->cursor.location, center.m[3]); WM_event_add_notifier(C, NC_SCENE | NA_EDITED, scene); DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE); // ED_undo_push(C, "Cursor"); } bool Widget_Cursor::has_click(VR_UI::Cursor &c) const { return true; } void Widget_Cursor::click(VR_UI::Cursor &c) { /* Update the Blender 3D cursor */ const Mat44f &m = c.position.get(VR_SPACE_BLENDER); bContext *C = vr_get_obj()->ctx; Scene *scene = CTX_data_scene(C); BKE_scene_cursor_from_mat4(&scene->cursor, (float(*)[4])m.m, false); WM_event_add_notifier(C, NC_SCENE | NA_EDITED, scene); DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE); // ED_undo_push(C, "Cursor"); } void Widget_Cursor::drag_start(VR_UI::Cursor &c) { /* Update the Blender 3D cursor */ const Mat44f &m = c.interaction_position.get(VR_SPACE_BLENDER); bContext *C = vr_get_obj()->ctx; Scene *scene = CTX_data_scene(C); BKE_scene_cursor_from_mat4(&scene->cursor, (float(*)[4])m.m, false); DEG_id_tag_update(&scene->id, 0); } void Widget_Cursor::drag_contd(VR_UI::Cursor &c) { /* Update the Blender 3D cursor */ const Mat44f &m = c.position.get(VR_SPACE_BLENDER); bContext *C = vr_get_obj()->ctx; Scene *scene = CTX_data_scene(C); BKE_scene_cursor_from_mat4(&scene->cursor, (float(*)[4])m.m, false); DEG_id_tag_update(&scene->id, 0); } void Widget_Cursor::drag_stop(VR_UI::Cursor &c) { /* Update the Blender 3D cursor */ const Mat44f &m = c.position.get(VR_SPACE_BLENDER); bContext *C = vr_get_obj()->ctx; Scene *scene = CTX_data_scene(C); BKE_scene_cursor_from_mat4(&scene->cursor, (float(*)[4])m.m, false); WM_event_add_notifier(C, NC_SCENE | NA_EDITED, scene); DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE); // ED_undo_push(C, "Cursor"); }
#include "Point.h" /** * @brief Constructor initializes an empty Point. */ Point::Point() { _xyz = new double[3]; _xyz[0] = 0.0; _xyz[1] = 0.0; _xyz[2] = 0.0; } /** * @brief Destructor */ Point::~Point() { delete [] _xyz; } /** * @brief Converts this Point to a character representation of its attributes. * @details The character array includes the x-coordinate, y-coordinate, and * z-coordinate * @return a character array of this Point's attributes */ std::string Point::toString() { std::stringstream string; string << "Point: x = " << _xyz[0] << ", y = " << _xyz[1] << ", z = " << _xyz[2]; return string.str(); }
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/SwitchStats.h" #include <folly/Memory.h> #include "fboss/agent/PortStats.h" using facebook::fb303::AVG; using facebook::fb303::RATE; using facebook::fb303::SUM; namespace facebook::fboss { // set to empty string, we'll prepend prefix when fbagent collects counters std::string SwitchStats::kCounterPrefix = ""; SwitchStats::SwitchStats() : SwitchStats(fb303::ThreadCachedServiceData::get()->getThreadStats()) {} SwitchStats::SwitchStats(ThreadLocalStatsMap* map) : trapPkts_(map, kCounterPrefix + "trapped.pkts", SUM, RATE), trapPktDrops_(map, kCounterPrefix + "trapped.drops", SUM, RATE), trapPktBogus_(map, kCounterPrefix + "trapped.bogus", SUM, RATE), trapPktErrors_(map, kCounterPrefix + "trapped.error", SUM, RATE), trapPktUnhandled_(map, kCounterPrefix + "trapped.unhandled", SUM, RATE), trapPktToHost_(map, kCounterPrefix + "host.rx", SUM, RATE), trapPktToHostBytes_(map, kCounterPrefix + "host.rx.bytes", SUM, RATE), pktFromHost_(map, kCounterPrefix + "host.tx", SUM, RATE), pktFromHostBytes_(map, kCounterPrefix + "host.tx.bytes", SUM, RATE), trapPktArp_(map, kCounterPrefix + "trapped.arp", SUM, RATE), arpUnsupported_(map, kCounterPrefix + "arp.unsupported", SUM, RATE), arpNotMine_(map, kCounterPrefix + "arp.not_mine", SUM, RATE), arpRequestsRx_(map, kCounterPrefix + "arp.request.rx", SUM, RATE), arpRepliesRx_(map, kCounterPrefix + "arp.reply.rx", SUM, RATE), arpRequestsTx_(map, kCounterPrefix + "arp.request.tx", SUM, RATE), arpRepliesTx_(map, kCounterPrefix + "arp.reply.tx", SUM, RATE), arpBadOp_(map, kCounterPrefix + "arp.bad_op", SUM, RATE), trapPktNdp_(map, kCounterPrefix + "trapped.ndp", SUM, RATE), ipv6NdpBad_(map, kCounterPrefix + "ipv6.ndp.bad", SUM, RATE), ipv4Rx_(map, kCounterPrefix + "trapped.ipv4", SUM, RATE), ipv4TooSmall_(map, kCounterPrefix + "ipv4.too_small", SUM, RATE), ipv4WrongVer_(map, kCounterPrefix + "ipv4.wrong_version", SUM, RATE), ipv4Nexthop_(map, kCounterPrefix + "ipv4.nexthop", SUM, RATE), ipv4Mine_(map, kCounterPrefix + "ipv4.mine", SUM, RATE), ipv4NoArp_(map, kCounterPrefix + "ipv4.no_arp", SUM, RATE), ipv4TtlExceeded_(map, kCounterPrefix + "ipv4.ttl_exceeded", SUM, RATE), ipv6HopExceeded_(map, kCounterPrefix + "ipv6.hop_exceeded", SUM, RATE), udpTooSmall_(map, kCounterPrefix + "udp.too_small", SUM, RATE), dhcpV4Pkt_(map, kCounterPrefix + "dhcpV4.pkt", SUM, RATE), dhcpV4BadPkt_(map, kCounterPrefix + "dhcpV4.bad_pkt", SUM, RATE), dhcpV4DropPkt_(map, kCounterPrefix + "dhcpV4.drop_pkt", SUM, RATE), dhcpV6Pkt_(map, kCounterPrefix + "dhcpV6.pkt", SUM, RATE), dhcpV6BadPkt_(map, kCounterPrefix + "dhcpV6.bad_pkt", SUM, RATE), dhcpV6DropPkt_(map, kCounterPrefix + "dhcpV6.drop_pkt", SUM, RATE), addRouteV4_(map, kCounterPrefix + "route.v4.add", RATE), addRouteV6_(map, kCounterPrefix + "route.v6.add", RATE), delRouteV4_(map, kCounterPrefix + "route.v4.delete", RATE), delRouteV6_(map, kCounterPrefix + "route.v6.delete", RATE), dstLookupFailureV4_( map, kCounterPrefix + "ipv4.dst_lookup_failure", SUM, RATE), dstLookupFailureV6_( map, kCounterPrefix + "ipv6.dst_lookup_failure", SUM, RATE), dstLookupFailure_( map, kCounterPrefix + "ip.dst_lookup_failure", SUM, RATE), updateState_(map, kCounterPrefix + "state_update.us", 50000, 0, 1000000), routeUpdate_(map, kCounterPrefix + "route_update.us", 50, 0, 500), bgHeartbeatDelay_( map, kCounterPrefix + "bg_heartbeat_delay.ms", 100, 0, 20000, AVG, 50, 100), updHeartbeatDelay_( map, kCounterPrefix + "upd_heartbeat_delay.ms", 100, 0, 20000, AVG, 50, 100), packetTxHeartbeatDelay_( map, kCounterPrefix + "packetTx_heartbeat_delay.ms", 100, 0, 20000, AVG, 50, 100), lacpHeartbeatDelay_( map, kCounterPrefix + "lacp_heartbeat_delay.ms", 100, 0, 20000, AVG, 50, 100), neighborCacheHeartbeatDelay_( map, kCounterPrefix + "neighbor_cache_heartbeat_delay.ms", 100, 0, 20000, AVG, 50, 100), bgEventBacklog_( map, kCounterPrefix + "bg_event_backlog", 1, 0, 200, AVG, 50, 100), updEventBacklog_( map, kCounterPrefix + "upd_event_backlog", 1, 0, 200, AVG, 50, 100), packetTxEventBacklog_( map, kCounterPrefix + "packetTx_event_backlog", 1, 0, 200, AVG, 50, 100), lacpEventBacklog_( map, kCounterPrefix + "lacp_event_backlog", 1, 0, 200, AVG, 50, 100), neighborCacheEventBacklog_( map, kCounterPrefix + "neighborCache_event_backlog", 1, 0, 200, AVG, 50, 100), linkStateChange_(map, kCounterPrefix + "link_state.flap", SUM), pcapDistFailure_(map, kCounterPrefix + "pcap_dist_failure.error"), updateStatsExceptions_( map, kCounterPrefix + "update_stats_exceptions", SUM), trapPktTooBig_(map, kCounterPrefix + "trapped.packet_too_big", SUM, RATE), LldpRecvdPkt_(map, kCounterPrefix + "lldp.recvd", SUM, RATE), LldpBadPkt_(map, kCounterPrefix + "lldp.recv_bad", SUM, RATE), LldpValidateMisMatch_( map, kCounterPrefix + "lldp.validate_mismatch", SUM, RATE), LldpNeighborsSize_(map, kCounterPrefix + "lldp.neighbors_size", SUM), LacpRxTimeouts_(map, kCounterPrefix + "lacp.rx_timeout", SUM), LacpMismatchPduTeardown_( map, kCounterPrefix + "lacp.mismatched_pdu_teardown", SUM), MkPduRecvdPkts_(map, kCounterPrefix + "mkpdu.recvd", SUM, RATE), MkPduSendPkts_(map, kCounterPrefix + "mkpdu.send", SUM, RATE), MkPduSendFailure_( map, kCounterPrefix + "mkpdu.err.send_failure", SUM, RATE), MkPduPortNotRegistered_( map, kCounterPrefix + "mkpdu.err.port_not_regd", SUM, RATE), MKAServiceSendFailure_( map, kCounterPrefix + "mka_service.err.send_failure", SUM, RATE), MKAServiceSendSuccess_( map, kCounterPrefix + "mka_service.send", SUM, RATE), MKAServiceRecvSuccess_( map, kCounterPrefix + "mka_service.recvd", SUM, RATE), pfcDeadlockDetectionCount_( map, kCounterPrefix + "pfc_deadlock_detection", SUM), pfcDeadlockRecoveryCount_( map, kCounterPrefix + "pfc_deadlock_recovery", SUM) {} PortStats* FOLLY_NULLABLE SwitchStats::port(PortID portID) { auto it = ports_.find(portID); if (it != ports_.end()) { return it->second.get(); } // Since PortStats needs portName from current switch state, let caller to // decide whether it needs createPortStats function. return nullptr; } AggregatePortStats* FOLLY_NULLABLE SwitchStats::aggregatePort(AggregatePortID aggregatePortID) { auto it = aggregatePortIDToStats_.find(aggregatePortID); return it == aggregatePortIDToStats_.end() ? nullptr : it->second.get(); } PortStats* SwitchStats::createPortStats(PortID portID, std::string portName) { auto rv = ports_.emplace( portID, std::make_unique<PortStats>(portID, portName, this)); DCHECK(rv.second); const auto& it = rv.first; return it->second.get(); } AggregatePortStats* SwitchStats::createAggregatePortStats( AggregatePortID id, std::string name) { auto [it, inserted] = aggregatePortIDToStats_.emplace( id, std::make_unique<AggregatePortStats>(id, name)); CHECK(inserted); return it->second.get(); } } // namespace facebook::fboss
#include "renderer/context/dynamic_functions.h" #include "renderer/context/device.h" #include <string> namespace { template <class Func> Func GetProcedure(const char *const name) { const auto func = reinterpret_cast<Func>(vkGetDeviceProcAddr(estun::DeviceLocator::GetLogicalDevice(), name)); if (func == nullptr) { ES_CORE_ASSERT(std::string("failed to get address of '") + name + std::string("'")); } return func; } } // namespace estun::DynamicFunctions::DynamicFunctions() : vkCreateAccelerationStructureKHR(GetProcedure<PFN_vkCreateAccelerationStructureKHR>("vkCreateAccelerationStructureKHR")), vkDestroyAccelerationStructureKHR(GetProcedure<PFN_vkDestroyAccelerationStructureKHR>("vkDestroyAccelerationStructureKHR")), vkGetAccelerationStructureMemoryRequirementsKHR(GetProcedure<PFN_vkGetAccelerationStructureMemoryRequirementsKHR>("vkGetAccelerationStructureMemoryRequirementsKHR")), vkBindAccelerationStructureMemoryKHR(GetProcedure<PFN_vkBindAccelerationStructureMemoryKHR>("vkBindAccelerationStructureMemoryKHR")), vkGetAccelerationStructureDeviceAddressKHR(GetProcedure<PFN_vkGetAccelerationStructureDeviceAddressKHR>("vkGetAccelerationStructureDeviceAddressKHR")), vkCmdBuildAccelerationStructureKHR(GetProcedure<PFN_vkCmdBuildAccelerationStructureKHR>("vkCmdBuildAccelerationStructureKHR")), vkCreateRayTracingPipelinesKHR(GetProcedure<PFN_vkCreateRayTracingPipelinesKHR>("vkCreateRayTracingPipelinesKHR")), vkGetRayTracingShaderGroupHandlesKHR(GetProcedure<PFN_vkGetRayTracingShaderGroupHandlesKHR>("vkGetRayTracingShaderGroupHandlesKHR")), vkCmdTraceRaysKHR(GetProcedure<PFN_vkCmdTraceRaysKHR>("vkCmdTraceRaysKHR")) { } estun::DynamicFunctions::~DynamicFunctions() { } estun::DynamicFunctions *estun::FunctionsLocator::funcs_ = nullptr;
// Copyright (c) 2017-2019, The Monero Project // // 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. // // Adapted from Java code by Sarang Noether #include <stdlib.h> #include <boost/thread/mutex.hpp> #include <boost/thread/lock_guard.hpp> #include "misc_log_ex.h" #include "span.h" #include "common/perf_timer.h" #include "cryptonote_config.h" extern "C" { #include "crypto/crypto-ops.h" } #include "rctOps.h" #include "multiexp.h" #include "bulletproofs.h" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "bulletproofs" //#define DEBUG_BP #if 0 #define PERF_TIMER_START_BP(x) PERF_TIMER_START_UNIT(x, 1000000) #define PERF_TIMER_STOP_BP(x) PERF_TIMER_STOP(x) #else #define PERF_TIMER_START_BP(x) ((void)0) #define PERF_TIMER_STOP_BP(x) ((void)0) #endif #define STRAUS_SIZE_LIMIT 232 #define PIPPENGER_SIZE_LIMIT 0 namespace rct { static rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b); static rct::keyV vector_powers(const rct::key &x, size_t n); static rct::keyV vector_dup(const rct::key &x, size_t n); static rct::key inner_product(const rct::keyV &a, const rct::keyV &b); static constexpr size_t maxN = 64; static constexpr size_t maxM = BULLETPROOF_MAX_OUTPUTS; static rct::key Hi[maxN*maxM], Gi[maxN*maxM]; static ge_p3 Hi_p3[maxN*maxM], Gi_p3[maxN*maxM]; static std::shared_ptr<straus_cached_data> straus_HiGi_cache; static std::shared_ptr<pippenger_cached_data> pippenger_HiGi_cache; static const rct::key TWO = { {0x02, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 } }; static const rct::key MINUS_ONE = { { 0xec, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 } }; static const rct::key MINUS_INV_EIGHT = { { 0x74, 0xa4, 0x19, 0x7a, 0xf0, 0x7d, 0x0b, 0xf7, 0x05, 0xc2, 0xda, 0x25, 0x2b, 0x5c, 0x0b, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a } }; static const rct::keyV oneN = vector_dup(rct::identity(), maxN); static const rct::keyV twoN = vector_powers(TWO, maxN); static const rct::key ip12 = inner_product(oneN, twoN); static boost::mutex init_mutex; static inline rct::key multiexp(const std::vector<MultiexpData> &data, size_t HiGi_size) { if (HiGi_size > 0) { static_assert(232 <= STRAUS_SIZE_LIMIT, "Straus in precalc mode can only be calculated till STRAUS_SIZE_LIMIT"); return HiGi_size <= 232 && data.size() == HiGi_size ? straus(data, straus_HiGi_cache, 0) : pippenger(data, pippenger_HiGi_cache, HiGi_size, get_pippenger_c(data.size())); } else return data.size() <= 95 ? straus(data, NULL, 0) : pippenger(data, NULL, 0, get_pippenger_c(data.size())); } static inline bool is_reduced(const rct::key &scalar) { return sc_check(scalar.bytes) == 0; } static rct::key get_exponent(const rct::key &base, size_t idx) { static const std::string salt("bulletproof"); std::string hashed = std::string((const char*)base.bytes, sizeof(base)) + salt + tools::get_varint_data(idx); rct::key e; ge_p3 e_p3; rct::hash_to_p3(e_p3, rct::hash2rct(crypto::cn_fast_hash(hashed.data(), hashed.size()))); ge_p3_tobytes(e.bytes, &e_p3); CHECK_AND_ASSERT_THROW_MES(!(e == rct::identity()), "Exponent is point at infinity"); return e; } static void init_exponents() { boost::lock_guard<boost::mutex> lock(init_mutex); static bool init_done = false; if (init_done) return; std::vector<MultiexpData> data; data.reserve(maxN*maxM*2); for (size_t i = 0; i < maxN*maxM; ++i) { Hi[i] = get_exponent(rct::H, i * 2); CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&Hi_p3[i], Hi[i].bytes) == 0, "ge_frombytes_vartime failed"); Gi[i] = get_exponent(rct::H, i * 2 + 1); CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&Gi_p3[i], Gi[i].bytes) == 0, "ge_frombytes_vartime failed"); data.push_back({rct::zero(), Gi_p3[i]}); data.push_back({rct::zero(), Hi_p3[i]}); } straus_HiGi_cache = straus_init_cache(data, STRAUS_SIZE_LIMIT); pippenger_HiGi_cache = pippenger_init_cache(data, 0, PIPPENGER_SIZE_LIMIT); MINFO("Hi/Gi cache size: " << (sizeof(Hi)+sizeof(Gi))/1024 << " kB"); MINFO("Hi_p3/Gi_p3 cache size: " << (sizeof(Hi_p3)+sizeof(Gi_p3))/1024 << " kB"); MINFO("Straus cache size: " << straus_get_cache_size(straus_HiGi_cache)/1024 << " kB"); MINFO("Pippenger cache size: " << pippenger_get_cache_size(pippenger_HiGi_cache)/1024 << " kB"); size_t cache_size = (sizeof(Hi)+sizeof(Hi_p3))*2 + straus_get_cache_size(straus_HiGi_cache) + pippenger_get_cache_size(pippenger_HiGi_cache); MINFO("Total cache size: " << cache_size/1024 << "kB"); init_done = true; } /* Given two scalar arrays, construct a vector commitment */ static rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b) { CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), "Incompatible sizes of a and b"); CHECK_AND_ASSERT_THROW_MES(a.size() <= maxN*maxM, "Incompatible sizes of a and maxN"); std::vector<MultiexpData> multiexp_data; multiexp_data.reserve(a.size()*2); for (size_t i = 0; i < a.size(); ++i) { multiexp_data.emplace_back(a[i], Gi_p3[i]); multiexp_data.emplace_back(b[i], Hi_p3[i]); } return multiexp(multiexp_data, 2 * a.size()); } /* Compute a custom vector-scalar commitment */ static rct::key cross_vector_exponent8(size_t size, const std::vector<ge_p3> &A, size_t Ao, const std::vector<ge_p3> &B, size_t Bo, const rct::keyV &a, size_t ao, const rct::keyV &b, size_t bo, const rct::keyV *scale, const ge_p3 *extra_point, const rct::key *extra_scalar) { CHECK_AND_ASSERT_THROW_MES(size + Ao <= A.size(), "Incompatible size for A"); CHECK_AND_ASSERT_THROW_MES(size + Bo <= B.size(), "Incompatible size for B"); CHECK_AND_ASSERT_THROW_MES(size + ao <= a.size(), "Incompatible size for a"); CHECK_AND_ASSERT_THROW_MES(size + bo <= b.size(), "Incompatible size for b"); CHECK_AND_ASSERT_THROW_MES(size <= maxN*maxM, "size is too large"); CHECK_AND_ASSERT_THROW_MES(!scale || size == scale->size() / 2, "Incompatible size for scale"); CHECK_AND_ASSERT_THROW_MES(!!extra_point == !!extra_scalar, "only one of extra point/scalar present"); std::vector<MultiexpData> multiexp_data; multiexp_data.resize(size*2 + (!!extra_point)); for (size_t i = 0; i < size; ++i) { sc_mul(multiexp_data[i*2].scalar.bytes, a[ao+i].bytes, INV_EIGHT.bytes);; multiexp_data[i*2].point = A[Ao+i]; sc_mul(multiexp_data[i*2+1].scalar.bytes, b[bo+i].bytes, INV_EIGHT.bytes); if (scale) sc_mul(multiexp_data[i*2+1].scalar.bytes, multiexp_data[i*2+1].scalar.bytes, (*scale)[Bo+i].bytes); multiexp_data[i*2+1].point = B[Bo+i]; } if (extra_point) { sc_mul(multiexp_data.back().scalar.bytes, extra_scalar->bytes, INV_EIGHT.bytes); multiexp_data.back().point = *extra_point; } return multiexp(multiexp_data, 0); } /* Given a scalar, construct a vector of powers */ static rct::keyV vector_powers(const rct::key &x, size_t n) { rct::keyV res(n); if (n == 0) return res; res[0] = rct::identity(); if (n == 1) return res; res[1] = x; for (size_t i = 2; i < n; ++i) { sc_mul(res[i].bytes, res[i-1].bytes, x.bytes); } return res; } /* Given a scalar, return the sum of its powers from 0 to n-1 */ static rct::key vector_power_sum(rct::key x, size_t n) { if (n == 0) return rct::zero(); rct::key res = rct::identity(); if (n == 1) return res; const bool is_power_of_2 = (n & (n - 1)) == 0; if (is_power_of_2) { sc_add(res.bytes, res.bytes, x.bytes); while (n > 2) { sc_mul(x.bytes, x.bytes, x.bytes); sc_muladd(res.bytes, x.bytes, res.bytes, res.bytes); n /= 2; } } else { rct::key prev = x; for (size_t i = 1; i < n; ++i) { if (i > 1) sc_mul(prev.bytes, prev.bytes, x.bytes); sc_add(res.bytes, res.bytes, prev.bytes); } } return res; } /* Given two scalar arrays, construct the inner product */ static rct::key inner_product(const epee::span<const rct::key> &a, const epee::span<const rct::key> &b) { CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), "Incompatible sizes of a and b"); rct::key res = rct::zero(); for (size_t i = 0; i < a.size(); ++i) { sc_muladd(res.bytes, a[i].bytes, b[i].bytes, res.bytes); } return res; } static rct::key inner_product(const rct::keyV &a, const rct::keyV &b) { return inner_product(epee::span<const rct::key>(a.data(), a.size()), epee::span<const rct::key>(b.data(), b.size())); } /* Given two scalar arrays, construct the Hadamard product */ static rct::keyV hadamard(const rct::keyV &a, const rct::keyV &b) { CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), "Incompatible sizes of a and b"); rct::keyV res(a.size()); for (size_t i = 0; i < a.size(); ++i) { sc_mul(res[i].bytes, a[i].bytes, b[i].bytes); } return res; } /* folds a curvepoint array using a two way scaled Hadamard product */ static void hadamard_fold(std::vector<ge_p3> &v, const rct::keyV *scale, const rct::key &a, const rct::key &b) { CHECK_AND_ASSERT_THROW_MES((v.size() & 1) == 0, "Vector size should be even"); const size_t sz = v.size() / 2; for (size_t n = 0; n < sz; ++n) { ge_dsmp c[2]; ge_dsm_precomp(c[0], &v[n]); ge_dsm_precomp(c[1], &v[sz + n]); rct::key sa, sb; if (scale) sc_mul(sa.bytes, a.bytes, (*scale)[n].bytes); else sa = a; if (scale) sc_mul(sb.bytes, b.bytes, (*scale)[sz + n].bytes); else sb = b; ge_double_scalarmult_precomp_vartime2_p3(&v[n], sa.bytes, c[0], sb.bytes, c[1]); } v.resize(sz); } /* Add two vectors */ static rct::keyV vector_add(const rct::keyV &a, const rct::keyV &b) { CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), "Incompatible sizes of a and b"); rct::keyV res(a.size()); for (size_t i = 0; i < a.size(); ++i) { sc_add(res[i].bytes, a[i].bytes, b[i].bytes); } return res; } /* Add a scalar to all elements of a vector */ static rct::keyV vector_add(const rct::keyV &a, const rct::key &b) { rct::keyV res(a.size()); for (size_t i = 0; i < a.size(); ++i) { sc_add(res[i].bytes, a[i].bytes, b.bytes); } return res; } /* Subtract a scalar from all elements of a vector */ static rct::keyV vector_subtract(const rct::keyV &a, const rct::key &b) { rct::keyV res(a.size()); for (size_t i = 0; i < a.size(); ++i) { sc_sub(res[i].bytes, a[i].bytes, b.bytes); } return res; } /* Multiply a scalar and a vector */ static rct::keyV vector_scalar(const epee::span<const rct::key> &a, const rct::key &x) { rct::keyV res(a.size()); for (size_t i = 0; i < a.size(); ++i) { sc_mul(res[i].bytes, a[i].bytes, x.bytes); } return res; } static rct::keyV vector_scalar(const rct::keyV &a, const rct::key &x) { return vector_scalar(epee::span<const rct::key>(a.data(), a.size()), x); } /* Create a vector from copies of a single value */ static rct::keyV vector_dup(const rct::key &x, size_t N) { return rct::keyV(N, x); } static rct::key sm(rct::key y, int n, const rct::key &x) { while (n--) sc_mul(y.bytes, y.bytes, y.bytes); sc_mul(y.bytes, y.bytes, x.bytes); return y; } /* Compute the inverse of a scalar, the clever way */ static rct::key invert(const rct::key &x) { rct::key _1, _10, _100, _11, _101, _111, _1001, _1011, _1111; _1 = x; sc_mul(_10.bytes, _1.bytes, _1.bytes); sc_mul(_100.bytes, _10.bytes, _10.bytes); sc_mul(_11.bytes, _10.bytes, _1.bytes); sc_mul(_101.bytes, _10.bytes, _11.bytes); sc_mul(_111.bytes, _10.bytes, _101.bytes); sc_mul(_1001.bytes, _10.bytes, _111.bytes); sc_mul(_1011.bytes, _10.bytes, _1001.bytes); sc_mul(_1111.bytes, _100.bytes, _1011.bytes); rct::key inv; sc_mul(inv.bytes, _1111.bytes, _1.bytes); inv = sm(inv, 123 + 3, _101); inv = sm(inv, 2 + 2, _11); inv = sm(inv, 1 + 4, _1111); inv = sm(inv, 1 + 4, _1111); inv = sm(inv, 4, _1001); inv = sm(inv, 2, _11); inv = sm(inv, 1 + 4, _1111); inv = sm(inv, 1 + 3, _101); inv = sm(inv, 3 + 3, _101); inv = sm(inv, 3, _111); inv = sm(inv, 1 + 4, _1111); inv = sm(inv, 2 + 3, _111); inv = sm(inv, 2 + 2, _11); inv = sm(inv, 1 + 4, _1011); inv = sm(inv, 2 + 4, _1011); inv = sm(inv, 6 + 4, _1001); inv = sm(inv, 2 + 2, _11); inv = sm(inv, 3 + 2, _11); inv = sm(inv, 3 + 2, _11); inv = sm(inv, 1 + 4, _1001); inv = sm(inv, 1 + 3, _111); inv = sm(inv, 2 + 4, _1111); inv = sm(inv, 1 + 4, _1011); inv = sm(inv, 3, _101); inv = sm(inv, 2 + 4, _1111); inv = sm(inv, 3, _101); inv = sm(inv, 1 + 2, _11); #ifdef DEBUG_BP rct::key tmp; sc_mul(tmp.bytes, inv.bytes, x.bytes); CHECK_AND_ASSERT_THROW_MES(tmp == rct::identity(), "invert failed"); #endif return inv; } static rct::keyV invert(rct::keyV x) { rct::keyV scratch; scratch.reserve(x.size()); rct::key acc = rct::identity(); for (size_t n = 0; n < x.size(); ++n) { scratch.push_back(acc); if (n == 0) acc = x[0]; else sc_mul(acc.bytes, acc.bytes, x[n].bytes); } acc = invert(acc); rct::key tmp; for (int i = x.size(); i-- > 0; ) { sc_mul(tmp.bytes, acc.bytes, x[i].bytes); sc_mul(x[i].bytes, acc.bytes, scratch[i].bytes); acc = tmp; } return x; } /* Compute the slice of a vector */ static epee::span<const rct::key> slice(const rct::keyV &a, size_t start, size_t stop) { CHECK_AND_ASSERT_THROW_MES(start < a.size(), "Invalid start index"); CHECK_AND_ASSERT_THROW_MES(stop <= a.size(), "Invalid stop index"); CHECK_AND_ASSERT_THROW_MES(start < stop, "Invalid start/stop indices"); return epee::span<const rct::key>(&a[start], stop - start); } static rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1) { rct::key data[3]; data[0] = hash_cache; data[1] = mash0; data[2] = mash1; rct::hash_to_scalar(hash_cache, data, sizeof(data)); return hash_cache; } static rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1, const rct::key &mash2) { rct::key data[4]; data[0] = hash_cache; data[1] = mash0; data[2] = mash1; data[3] = mash2; rct::hash_to_scalar(hash_cache, data, sizeof(data)); return hash_cache; } static rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1, const rct::key &mash2, const rct::key &mash3) { rct::key data[5]; data[0] = hash_cache; data[1] = mash0; data[2] = mash1; data[3] = mash2; data[4] = mash3; rct::hash_to_scalar(hash_cache, data, sizeof(data)); return hash_cache; } /* Given a value v (0..2^N-1) and a mask gamma, construct a range proof */ Bulletproof bulletproof_PROVE(const rct::key &sv, const rct::key &gamma) { return bulletproof_PROVE(rct::keyV(1, sv), rct::keyV(1, gamma)); } Bulletproof bulletproof_PROVE(uint64_t v, const rct::key &gamma) { return bulletproof_PROVE(std::vector<uint64_t>(1, v), rct::keyV(1, gamma)); } /* Given a set of values v (0..2^N-1) and masks gamma, construct a range proof */ Bulletproof bulletproof_PROVE(const rct::keyV &sv, const rct::keyV &gamma) { CHECK_AND_ASSERT_THROW_MES(sv.size() == gamma.size(), "Incompatible sizes of sv and gamma"); CHECK_AND_ASSERT_THROW_MES(!sv.empty(), "sv is empty"); for (const rct::key &sve: sv) CHECK_AND_ASSERT_THROW_MES(is_reduced(sve), "Invalid sv input"); for (const rct::key &g: gamma) CHECK_AND_ASSERT_THROW_MES(is_reduced(g), "Invalid gamma input"); init_exponents(); PERF_TIMER_UNIT(PROVE, 1000000); constexpr size_t logN = 6; // log2(64) constexpr size_t N = 1<<logN; size_t M, logM; for (logM = 0; (M = 1<<logM) <= maxM && M < sv.size(); ++logM); CHECK_AND_ASSERT_THROW_MES(M <= maxM, "sv/gamma are too large"); const size_t logMN = logM + logN; const size_t MN = M * N; rct::keyV V(sv.size()); rct::keyV aL(MN), aR(MN); rct::keyV aL8(MN), aR8(MN); rct::key tmp, tmp2; PERF_TIMER_START_BP(PROVE_v); for (size_t i = 0; i < sv.size(); ++i) { rct::key gamma8, sv8; sc_mul(gamma8.bytes, gamma[i].bytes, INV_EIGHT.bytes); sc_mul(sv8.bytes, sv[i].bytes, INV_EIGHT.bytes); rct::addKeys2(V[i], gamma8, sv8, rct::H); } PERF_TIMER_STOP_BP(PROVE_v); PERF_TIMER_START_BP(PROVE_aLaR); for (size_t j = 0; j < M; ++j) { for (size_t i = N; i-- > 0; ) { if (j < sv.size() && (sv[j][i/8] & (((uint64_t)1)<<(i%8)))) { aL[j*N+i] = rct::identity(); aL8[j*N+i] = INV_EIGHT; aR[j*N+i] = aR8[j*N+i] = rct::zero(); } else { aL[j*N+i] = aL8[j*N+i] = rct::zero(); aR[j*N+i] = MINUS_ONE; aR8[j*N+i] = MINUS_INV_EIGHT; } } } PERF_TIMER_STOP_BP(PROVE_aLaR); // DEBUG: Test to ensure this recovers the value #ifdef DEBUG_BP for (size_t j = 0; j < M; ++j) { uint64_t test_aL = 0, test_aR = 0; for (size_t i = 0; i < N; ++i) { if (aL[j*N+i] == rct::identity()) test_aL += ((uint64_t)1)<<i; if (aR[j*N+i] == rct::zero()) test_aR += ((uint64_t)1)<<i; } uint64_t v_test = 0; if (j < sv.size()) for (int n = 0; n < 8; ++n) v_test |= (((uint64_t)sv[j][n]) << (8*n)); CHECK_AND_ASSERT_THROW_MES(test_aL == v_test, "test_aL failed"); CHECK_AND_ASSERT_THROW_MES(test_aR == v_test, "test_aR failed"); } #endif try_again: rct::key hash_cache = rct::hash_to_scalar(V); PERF_TIMER_START_BP(PROVE_step1); // PAPER LINES 38-39 rct::key alpha = rct::skGen(); rct::key ve = vector_exponent(aL8, aR8); rct::key A; sc_mul(tmp.bytes, alpha.bytes, INV_EIGHT.bytes); rct::addKeys(A, ve, rct::scalarmultBase(tmp)); // PAPER LINES 40-42 rct::keyV sL = rct::skvGen(MN), sR = rct::skvGen(MN); rct::key rho = rct::skGen(); ve = vector_exponent(sL, sR); rct::key S; rct::addKeys(S, ve, rct::scalarmultBase(rho)); S = rct::scalarmultKey(S, INV_EIGHT); // PAPER LINES 43-45 rct::key y = hash_cache_mash(hash_cache, A, S); if (y == rct::zero()) { PERF_TIMER_STOP_BP(PROVE_step1); MINFO("y is 0, trying again"); goto try_again; } rct::key z = hash_cache = rct::hash_to_scalar(y); if (z == rct::zero()) { PERF_TIMER_STOP_BP(PROVE_step1); MINFO("z is 0, trying again"); goto try_again; } // Polynomial construction by coefficients rct::keyV l0 = vector_subtract(aL, z); const rct::keyV &l1 = sL; // This computes the ugly sum/concatenation from PAPER LINE 65 rct::keyV zero_twos(MN); const rct::keyV zpow = vector_powers(z, M+2); for (size_t i = 0; i < MN; ++i) { zero_twos[i] = rct::zero(); for (size_t j = 1; j <= M; ++j) { if (i >= (j-1)*N && i < j*N) { CHECK_AND_ASSERT_THROW_MES(1+j < zpow.size(), "invalid zpow index"); CHECK_AND_ASSERT_THROW_MES(i-(j-1)*N < twoN.size(), "invalid twoN index"); sc_muladd(zero_twos[i].bytes, zpow[1+j].bytes, twoN[i-(j-1)*N].bytes, zero_twos[i].bytes); } } } rct::keyV r0 = vector_add(aR, z); const auto yMN = vector_powers(y, MN); r0 = hadamard(r0, yMN); r0 = vector_add(r0, zero_twos); rct::keyV r1 = hadamard(yMN, sR); // Polynomial construction before PAPER LINE 46 rct::key t1_1 = inner_product(l0, r1); rct::key t1_2 = inner_product(l1, r0); rct::key t1; sc_add(t1.bytes, t1_1.bytes, t1_2.bytes); rct::key t2 = inner_product(l1, r1); PERF_TIMER_STOP_BP(PROVE_step1); PERF_TIMER_START_BP(PROVE_step2); // PAPER LINES 47-48 rct::key tau1 = rct::skGen(), tau2 = rct::skGen(); rct::key T1, T2; ge_p3 p3; sc_mul(tmp.bytes, t1.bytes, INV_EIGHT.bytes); sc_mul(tmp2.bytes, tau1.bytes, INV_EIGHT.bytes); ge_double_scalarmult_base_vartime_p3(&p3, tmp.bytes, &ge_p3_H, tmp2.bytes); ge_p3_tobytes(T1.bytes, &p3); sc_mul(tmp.bytes, t2.bytes, INV_EIGHT.bytes); sc_mul(tmp2.bytes, tau2.bytes, INV_EIGHT.bytes); ge_double_scalarmult_base_vartime_p3(&p3, tmp.bytes, &ge_p3_H, tmp2.bytes); ge_p3_tobytes(T2.bytes, &p3); // PAPER LINES 49-51 rct::key x = hash_cache_mash(hash_cache, z, T1, T2); if (x == rct::zero()) { PERF_TIMER_STOP_BP(PROVE_step2); MINFO("x is 0, trying again"); goto try_again; } // PAPER LINES 52-53 rct::key taux; sc_mul(taux.bytes, tau1.bytes, x.bytes); rct::key xsq; sc_mul(xsq.bytes, x.bytes, x.bytes); sc_muladd(taux.bytes, tau2.bytes, xsq.bytes, taux.bytes); for (size_t j = 1; j <= sv.size(); ++j) { CHECK_AND_ASSERT_THROW_MES(j+1 < zpow.size(), "invalid zpow index"); sc_muladd(taux.bytes, zpow[j+1].bytes, gamma[j-1].bytes, taux.bytes); } rct::key mu; sc_muladd(mu.bytes, x.bytes, rho.bytes, alpha.bytes); // PAPER LINES 54-57 rct::keyV l = l0; l = vector_add(l, vector_scalar(l1, x)); rct::keyV r = r0; r = vector_add(r, vector_scalar(r1, x)); PERF_TIMER_STOP_BP(PROVE_step2); PERF_TIMER_START_BP(PROVE_step3); rct::key t = inner_product(l, r); // DEBUG: Test if the l and r vectors match the polynomial forms #ifdef DEBUG_BP rct::key test_t; const rct::key t0 = inner_product(l0, r0); sc_muladd(test_t.bytes, t1.bytes, x.bytes, t0.bytes); sc_muladd(test_t.bytes, t2.bytes, xsq.bytes, test_t.bytes); CHECK_AND_ASSERT_THROW_MES(test_t == t, "test_t check failed"); #endif // PAPER LINES 32-33 rct::key x_ip = hash_cache_mash(hash_cache, x, taux, mu, t); if (x_ip == rct::zero()) { PERF_TIMER_STOP_BP(PROVE_step3); MINFO("x_ip is 0, trying again"); goto try_again; } // These are used in the inner product rounds size_t nprime = MN; std::vector<ge_p3> Gprime(MN); std::vector<ge_p3> Hprime(MN); rct::keyV aprime(MN); rct::keyV bprime(MN); const rct::key yinv = invert(y); rct::keyV yinvpow(MN); yinvpow[0] = rct::identity(); yinvpow[1] = yinv; for (size_t i = 0; i < MN; ++i) { Gprime[i] = Gi_p3[i]; Hprime[i] = Hi_p3[i]; if (i > 1) sc_mul(yinvpow[i].bytes, yinvpow[i-1].bytes, yinv.bytes); aprime[i] = l[i]; bprime[i] = r[i]; } rct::keyV L(logMN); rct::keyV R(logMN); int round = 0; rct::keyV w(logMN); // this is the challenge x in the inner product protocol PERF_TIMER_STOP_BP(PROVE_step3); PERF_TIMER_START_BP(PROVE_step4); // PAPER LINE 13 const rct::keyV *scale = &yinvpow; while (nprime > 1) { // PAPER LINE 15 nprime /= 2; // PAPER LINES 16-17 PERF_TIMER_START_BP(PROVE_inner_product); rct::key cL = inner_product(slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size())); rct::key cR = inner_product(slice(aprime, nprime, aprime.size()), slice(bprime, 0, nprime)); PERF_TIMER_STOP_BP(PROVE_inner_product); // PAPER LINES 18-19 PERF_TIMER_START_BP(PROVE_LR); sc_mul(tmp.bytes, cL.bytes, x_ip.bytes); L[round] = cross_vector_exponent8(nprime, Gprime, nprime, Hprime, 0, aprime, 0, bprime, nprime, scale, &ge_p3_H, &tmp); sc_mul(tmp.bytes, cR.bytes, x_ip.bytes); R[round] = cross_vector_exponent8(nprime, Gprime, 0, Hprime, nprime, aprime, nprime, bprime, 0, scale, &ge_p3_H, &tmp); PERF_TIMER_STOP_BP(PROVE_LR); // PAPER LINES 21-22 w[round] = hash_cache_mash(hash_cache, L[round], R[round]); if (w[round] == rct::zero()) { PERF_TIMER_STOP_BP(PROVE_step4); MINFO("w[round] is 0, trying again"); goto try_again; } // PAPER LINES 24-25 const rct::key winv = invert(w[round]); if (nprime > 1) { PERF_TIMER_START_BP(PROVE_hadamard2); hadamard_fold(Gprime, NULL, winv, w[round]); hadamard_fold(Hprime, scale, w[round], winv); PERF_TIMER_STOP_BP(PROVE_hadamard2); } // PAPER LINES 28-29 PERF_TIMER_START_BP(PROVE_prime); aprime = vector_add(vector_scalar(slice(aprime, 0, nprime), w[round]), vector_scalar(slice(aprime, nprime, aprime.size()), winv)); bprime = vector_add(vector_scalar(slice(bprime, 0, nprime), winv), vector_scalar(slice(bprime, nprime, bprime.size()), w[round])); PERF_TIMER_STOP_BP(PROVE_prime); scale = NULL; ++round; } PERF_TIMER_STOP_BP(PROVE_step4); // PAPER LINE 58 (with inclusions from PAPER LINE 8 and PAPER LINE 20) return Bulletproof(std::move(V), A, S, T1, T2, taux, mu, std::move(L), std::move(R), aprime[0], bprime[0], t); } Bulletproof bulletproof_PROVE(const std::vector<uint64_t> &v, const rct::keyV &gamma) { CHECK_AND_ASSERT_THROW_MES(v.size() == gamma.size(), "Incompatible sizes of v and gamma"); // vG + gammaH PERF_TIMER_START_BP(PROVE_v); rct::keyV sv(v.size()); for (size_t i = 0; i < v.size(); ++i) { sv[i] = rct::zero(); sv[i].bytes[0] = v[i] & 255; sv[i].bytes[1] = (v[i] >> 8) & 255; sv[i].bytes[2] = (v[i] >> 16) & 255; sv[i].bytes[3] = (v[i] >> 24) & 255; sv[i].bytes[4] = (v[i] >> 32) & 255; sv[i].bytes[5] = (v[i] >> 40) & 255; sv[i].bytes[6] = (v[i] >> 48) & 255; sv[i].bytes[7] = (v[i] >> 56) & 255; } PERF_TIMER_STOP_BP(PROVE_v); return bulletproof_PROVE(sv, gamma); } struct proof_data_t { rct::key x, y, z, x_ip; std::vector<rct::key> w; size_t logM, inv_offset; }; /* Given a range proof, determine if it is valid */ bool bulletproof_VERIFY(const std::vector<const Bulletproof*> &proofs) { init_exponents(); PERF_TIMER_START_BP(VERIFY); const size_t logN = 6; const size_t N = 1 << logN; // sanity and figure out which proof is longest size_t max_length = 0; size_t nV = 0; std::vector<proof_data_t> proof_data; proof_data.reserve(proofs.size()); size_t inv_offset = 0; std::vector<rct::key> to_invert; to_invert.reserve(11 * sizeof(proofs)); size_t max_logM = 0; for (const Bulletproof *p: proofs) { const Bulletproof &proof = *p; // check scalar range CHECK_AND_ASSERT_MES(is_reduced(proof.taux), false, "Input scalar not in range"); CHECK_AND_ASSERT_MES(is_reduced(proof.mu), false, "Input scalar not in range"); CHECK_AND_ASSERT_MES(is_reduced(proof.a), false, "Input scalar not in range"); CHECK_AND_ASSERT_MES(is_reduced(proof.b), false, "Input scalar not in range"); CHECK_AND_ASSERT_MES(is_reduced(proof.t), false, "Input scalar not in range"); CHECK_AND_ASSERT_MES(proof.V.size() >= 1, false, "V does not have at least one element"); CHECK_AND_ASSERT_MES(proof.L.size() == proof.R.size(), false, "Mismatched L and R sizes"); CHECK_AND_ASSERT_MES(proof.L.size() > 0, false, "Empty proof"); max_length = std::max(max_length, proof.L.size()); nV += proof.V.size(); // Reconstruct the challenges PERF_TIMER_START_BP(VERIFY_start); proof_data.resize(proof_data.size() + 1); proof_data_t &pd = proof_data.back(); rct::key hash_cache = rct::hash_to_scalar(proof.V); pd.y = hash_cache_mash(hash_cache, proof.A, proof.S); CHECK_AND_ASSERT_MES(!(pd.y == rct::zero()), false, "y == 0"); pd.z = hash_cache = rct::hash_to_scalar(pd.y); CHECK_AND_ASSERT_MES(!(pd.z == rct::zero()), false, "z == 0"); pd.x = hash_cache_mash(hash_cache, pd.z, proof.T1, proof.T2); CHECK_AND_ASSERT_MES(!(pd.x == rct::zero()), false, "x == 0"); pd.x_ip = hash_cache_mash(hash_cache, pd.x, proof.taux, proof.mu, proof.t); CHECK_AND_ASSERT_MES(!(pd.x_ip == rct::zero()), false, "x_ip == 0"); PERF_TIMER_STOP_BP(VERIFY_start); size_t M; for (pd.logM = 0; (M = 1<<pd.logM) <= maxM && M < proof.V.size(); ++pd.logM); CHECK_AND_ASSERT_MES(proof.L.size() == 6+pd.logM, false, "Proof is not the expected size"); max_logM = std::max(pd.logM, max_logM); const size_t rounds = pd.logM+logN; CHECK_AND_ASSERT_MES(rounds > 0, false, "Zero rounds"); PERF_TIMER_START_BP(VERIFY_line_21_22); // PAPER LINES 21-22 // The inner product challenges are computed per round pd.w.resize(rounds); for (size_t i = 0; i < rounds; ++i) { pd.w[i] = hash_cache_mash(hash_cache, proof.L[i], proof.R[i]); CHECK_AND_ASSERT_MES(!(pd.w[i] == rct::zero()), false, "w[i] == 0"); } PERF_TIMER_STOP_BP(VERIFY_line_21_22); pd.inv_offset = inv_offset; for (size_t i = 0; i < rounds; ++i) to_invert.push_back(pd.w[i]); to_invert.push_back(pd.y); inv_offset += rounds + 1; } CHECK_AND_ASSERT_MES(max_length < 32, false, "At least one proof is too large"); size_t maxMN = 1u << max_length; rct::key tmp; std::vector<MultiexpData> multiexp_data; multiexp_data.reserve(nV + (2 * (max_logM + logN) + 4) * proofs.size() + 2 * maxMN); multiexp_data.resize(2 * maxMN); PERF_TIMER_START_BP(VERIFY_line_24_25_invert); const std::vector<rct::key> inverses = invert(to_invert); PERF_TIMER_STOP_BP(VERIFY_line_24_25_invert); // setup weighted aggregates rct::key z1 = rct::zero(); rct::key z3 = rct::zero(); rct::keyV m_z4(maxMN, rct::zero()), m_z5(maxMN, rct::zero()); rct::key m_y0 = rct::zero(), y1 = rct::zero(); int proof_data_index = 0; rct::keyV w_cache; rct::keyV proof8_V, proof8_L, proof8_R; for (const Bulletproof *p: proofs) { const Bulletproof &proof = *p; const proof_data_t &pd = proof_data[proof_data_index++]; CHECK_AND_ASSERT_MES(proof.L.size() == 6+pd.logM, false, "Proof is not the expected size"); const size_t M = 1 << pd.logM; const size_t MN = M*N; const rct::key weight_y = rct::skGen(); const rct::key weight_z = rct::skGen(); // pre-multiply some points by 8 proof8_V.resize(proof.V.size()); for (size_t i = 0; i < proof.V.size(); ++i) proof8_V[i] = rct::scalarmult8(proof.V[i]); proof8_L.resize(proof.L.size()); for (size_t i = 0; i < proof.L.size(); ++i) proof8_L[i] = rct::scalarmult8(proof.L[i]); proof8_R.resize(proof.R.size()); for (size_t i = 0; i < proof.R.size(); ++i) proof8_R[i] = rct::scalarmult8(proof.R[i]); rct::key proof8_T1 = rct::scalarmult8(proof.T1); rct::key proof8_T2 = rct::scalarmult8(proof.T2); rct::key proof8_S = rct::scalarmult8(proof.S); rct::key proof8_A = rct::scalarmult8(proof.A); PERF_TIMER_START_BP(VERIFY_line_61); // PAPER LINE 61 sc_mulsub(m_y0.bytes, proof.taux.bytes, weight_y.bytes, m_y0.bytes); const rct::keyV zpow = vector_powers(pd.z, M+3); rct::key k; const rct::key ip1y = vector_power_sum(pd.y, MN); sc_mulsub(k.bytes, zpow[2].bytes, ip1y.bytes, rct::zero().bytes); for (size_t j = 1; j <= M; ++j) { CHECK_AND_ASSERT_MES(j+2 < zpow.size(), false, "invalid zpow index"); sc_mulsub(k.bytes, zpow[j+2].bytes, ip12.bytes, k.bytes); } PERF_TIMER_STOP_BP(VERIFY_line_61); PERF_TIMER_START_BP(VERIFY_line_61rl_new); sc_muladd(tmp.bytes, pd.z.bytes, ip1y.bytes, k.bytes); sc_sub(tmp.bytes, proof.t.bytes, tmp.bytes); sc_muladd(y1.bytes, tmp.bytes, weight_y.bytes, y1.bytes); for (size_t j = 0; j < proof8_V.size(); j++) { sc_mul(tmp.bytes, zpow[j+2].bytes, weight_y.bytes); multiexp_data.emplace_back(tmp, proof8_V[j]); } sc_mul(tmp.bytes, pd.x.bytes, weight_y.bytes); multiexp_data.emplace_back(tmp, proof8_T1); rct::key xsq; sc_mul(xsq.bytes, pd.x.bytes, pd.x.bytes); sc_mul(tmp.bytes, xsq.bytes, weight_y.bytes); multiexp_data.emplace_back(tmp, proof8_T2); PERF_TIMER_STOP_BP(VERIFY_line_61rl_new); PERF_TIMER_START_BP(VERIFY_line_62); // PAPER LINE 62 multiexp_data.emplace_back(weight_z, proof8_A); sc_mul(tmp.bytes, pd.x.bytes, weight_z.bytes); multiexp_data.emplace_back(tmp, proof8_S); PERF_TIMER_STOP_BP(VERIFY_line_62); // Compute the number of rounds for the inner product const size_t rounds = pd.logM+logN; CHECK_AND_ASSERT_MES(rounds > 0, false, "Zero rounds"); PERF_TIMER_START_BP(VERIFY_line_24_25); // Basically PAPER LINES 24-25 // Compute the curvepoints from G[i] and H[i] rct::key yinvpow = rct::identity(); rct::key ypow = rct::identity(); const rct::key *winv = &inverses[pd.inv_offset]; const rct::key yinv = inverses[pd.inv_offset + rounds]; // precalc PERF_TIMER_START_BP(VERIFY_line_24_25_precalc); w_cache.resize(1<<rounds); w_cache[0] = winv[0]; w_cache[1] = pd.w[0]; for (size_t j = 1; j < rounds; ++j) { const size_t slots = 1<<(j+1); for (size_t s = slots; s-- > 0; --s) { sc_mul(w_cache[s].bytes, w_cache[s/2].bytes, pd.w[j].bytes); sc_mul(w_cache[s-1].bytes, w_cache[s/2].bytes, winv[j].bytes); } } PERF_TIMER_STOP_BP(VERIFY_line_24_25_precalc); for (size_t i = 0; i < MN; ++i) { rct::key g_scalar = proof.a; rct::key h_scalar; if (i == 0) h_scalar = proof.b; else sc_mul(h_scalar.bytes, proof.b.bytes, yinvpow.bytes); // Convert the index to binary IN REVERSE and construct the scalar exponent sc_mul(g_scalar.bytes, g_scalar.bytes, w_cache[i].bytes); sc_mul(h_scalar.bytes, h_scalar.bytes, w_cache[(~i) & (MN-1)].bytes); // Adjust the scalars using the exponents from PAPER LINE 62 sc_add(g_scalar.bytes, g_scalar.bytes, pd.z.bytes); CHECK_AND_ASSERT_MES(2+i/N < zpow.size(), false, "invalid zpow index"); CHECK_AND_ASSERT_MES(i%N < twoN.size(), false, "invalid twoN index"); sc_mul(tmp.bytes, zpow[2+i/N].bytes, twoN[i%N].bytes); if (i == 0) { sc_add(tmp.bytes, tmp.bytes, pd.z.bytes); sc_sub(h_scalar.bytes, h_scalar.bytes, tmp.bytes); } else { sc_muladd(tmp.bytes, pd.z.bytes, ypow.bytes, tmp.bytes); sc_mulsub(h_scalar.bytes, tmp.bytes, yinvpow.bytes, h_scalar.bytes); } sc_mulsub(m_z4[i].bytes, g_scalar.bytes, weight_z.bytes, m_z4[i].bytes); sc_mulsub(m_z5[i].bytes, h_scalar.bytes, weight_z.bytes, m_z5[i].bytes); if (i == 0) { yinvpow = yinv; ypow = pd.y; } else if (i != MN-1) { sc_mul(yinvpow.bytes, yinvpow.bytes, yinv.bytes); sc_mul(ypow.bytes, ypow.bytes, pd.y.bytes); } } PERF_TIMER_STOP_BP(VERIFY_line_24_25); // PAPER LINE 26 PERF_TIMER_START_BP(VERIFY_line_26_new); sc_muladd(z1.bytes, proof.mu.bytes, weight_z.bytes, z1.bytes); for (size_t i = 0; i < rounds; ++i) { sc_mul(tmp.bytes, pd.w[i].bytes, pd.w[i].bytes); sc_mul(tmp.bytes, tmp.bytes, weight_z.bytes); multiexp_data.emplace_back(tmp, proof8_L[i]); sc_mul(tmp.bytes, winv[i].bytes, winv[i].bytes); sc_mul(tmp.bytes, tmp.bytes, weight_z.bytes); multiexp_data.emplace_back(tmp, proof8_R[i]); } sc_mulsub(tmp.bytes, proof.a.bytes, proof.b.bytes, proof.t.bytes); sc_mul(tmp.bytes, tmp.bytes, pd.x_ip.bytes); sc_muladd(z3.bytes, tmp.bytes, weight_z.bytes, z3.bytes); PERF_TIMER_STOP_BP(VERIFY_line_26_new); } // now check all proofs at once PERF_TIMER_START_BP(VERIFY_step2_check); sc_sub(tmp.bytes, m_y0.bytes, z1.bytes); multiexp_data.emplace_back(tmp, rct::G); sc_sub(tmp.bytes, z3.bytes, y1.bytes); multiexp_data.emplace_back(tmp, rct::H); for (size_t i = 0; i < maxMN; ++i) { multiexp_data[i * 2] = {m_z4[i], Gi_p3[i]}; multiexp_data[i * 2 + 1] = {m_z5[i], Hi_p3[i]}; } if (!(multiexp(multiexp_data, 2 * maxMN) == rct::identity())) { PERF_TIMER_STOP_BP(VERIFY_step2_check); MERROR("Verification failure"); return false; } PERF_TIMER_STOP_BP(VERIFY_step2_check); PERF_TIMER_STOP_BP(VERIFY); return true; } bool bulletproof_VERIFY(const std::vector<Bulletproof> &proofs) { std::vector<const Bulletproof*> proof_pointers; proof_pointers.reserve(proofs.size()); for (const Bulletproof &proof: proofs) proof_pointers.push_back(&proof); return bulletproof_VERIFY(proof_pointers); } bool bulletproof_VERIFY(const Bulletproof &proof) { std::vector<const Bulletproof*> proofs; proofs.push_back(&proof); return bulletproof_VERIFY(proofs); } }
#include <iostream> #include <string> class Base { protected: int ID; std::string name; int wage; public: Base(int id, std::string n, int w) { ID = id; name = n; wage = w; } virtual void print() { printf("ID: %d\n", ID); printf("name: %s\n", name.c_str()); printf("wage: %d\n", wage); } }; class manager : public Base { public: manager(int id, std::string n) : Base(id, n, 80000) {} void print() { Base::print(); } }; class Technician : public Base { private: int hour; public: Technician(int id, std::string n, int h) : Base(id, n, h * 100) { hour = h; } void print() { Base::print(); printf("hour: %d\n", hour); } }; int main() { #ifndef ONLINE_JUDGE freopen("1.in", "r", stdin); freopen("1.out", "w", stdout); freopen("1.err", "w", stderr); #endif int type; while (~scanf("%d", &type), type) { if (type == 2) { int id, hour; std::string name; std::cin >> id >> name >> hour; Technician t(id, name, hour); t.print(); } else { int id; std::string name; std::cin >> id >> name; manager m(id, name); m.print(); } } #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); fclose(stderr); #endif return 0; }
//===- StackProtector.cpp - Stack Protector Insertion ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This pass inserts stack protectors into functions which need them. A variable // with a random value in it is stored onto the stack before the local variables // are allocated. Upon exiting the block, the stored value is checked. If it's // changed, then there was some sort of violation and the program aborts. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/StackProtector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/BranchProbabilityInfo.h" #include "llvm/Analysis/EHPersonalities.h" #include "llvm/Analysis/MemoryLocation.h" #include "llvm/Analysis/OptimizationRemarkEmitter.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/TargetLowering.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/IR/User.h" #include "llvm/InitializePasses.h" #include "llvm/Pass.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include <utility> using namespace llvm; #define DEBUG_TYPE "stack-protector" STATISTIC(NumFunProtected, "Number of functions protected"); STATISTIC(NumAddrTaken, "Number of local variables that have their address" " taken."); static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true), cl::Hidden); char StackProtector::ID = 0; StackProtector::StackProtector() : FunctionPass(ID), SSPBufferSize(8) { initializeStackProtectorPass(*PassRegistry::getPassRegistry()); } INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE, "Insert stack protectors", false, true) INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE, "Insert stack protectors", false, true) FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); } void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetPassConfig>(); AU.addPreserved<DominatorTreeWrapperPass>(); } bool StackProtector::runOnFunction(Function &Fn) { F = &Fn; M = F->getParent(); DominatorTreeWrapperPass *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); DT = DTWP ? &DTWP->getDomTree() : nullptr; TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); Trip = TM->getTargetTriple(); TLI = TM->getSubtargetImpl(Fn)->getTargetLowering(); HasPrologue = false; HasIRCheck = false; Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size"); if (Attr.isStringAttribute() && Attr.getValueAsString().getAsInteger(10, SSPBufferSize)) return false; // Invalid integer string if (!RequiresStackProtector()) return false; // TODO(etienneb): Functions with funclets are not correctly supported now. // Do nothing if this is funclet-based personality. if (Fn.hasPersonalityFn()) { EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn()); if (isFuncletEHPersonality(Personality)) return false; } ++NumFunProtected; return InsertStackProtectors(); } /// \param [out] IsLarge is set to true if a protectable array is found and /// it is "large" ( >= ssp-buffer-size). In the case of a structure with /// multiple arrays, this gets set if any of them is large. bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, bool Strong, bool InStruct) const { if (!Ty) return false; if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { if (!AT->getElementType()->isIntegerTy(8)) { // If we're on a non-Darwin platform or we're inside of a structure, don't // add stack protectors unless the array is a character array. // However, in strong mode any array, regardless of type and size, // triggers a protector. if (!Strong && (InStruct || !Trip.isOSDarwin())) return false; } // If an array has more than SSPBufferSize bytes of allocated space, then we // emit stack protectors. if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) { IsLarge = true; return true; } if (Strong) // Require a protector for all arrays in strong mode return true; } const StructType *ST = dyn_cast<StructType>(Ty); if (!ST) return false; bool NeedsProtector = false; for (StructType::element_iterator I = ST->element_begin(), E = ST->element_end(); I != E; ++I) if (ContainsProtectableArray(*I, IsLarge, Strong, true)) { // If the element is a protectable array and is large (>= SSPBufferSize) // then we are done. If the protectable array is not large, then // keep looking in case a subsequent element is a large array. if (IsLarge) return true; NeedsProtector = true; } return NeedsProtector; } bool StackProtector::HasAddressTaken(const Instruction *AI, uint64_t AllocSize) { const DataLayout &DL = M->getDataLayout(); for (const User *U : AI->users()) { const auto *I = cast<Instruction>(U); // If this instruction accesses memory make sure it doesn't access beyond // the bounds of the allocated object. Optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I); if (MemLoc.hasValue() && MemLoc->Size.hasValue() && MemLoc->Size.getValue() > AllocSize) return true; switch (I->getOpcode()) { case Instruction::Store: if (AI == cast<StoreInst>(I)->getValueOperand()) return true; break; case Instruction::AtomicCmpXchg: // cmpxchg conceptually includes both a load and store from the same // location. So, like store, the value being stored is what matters. if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand()) return true; break; case Instruction::PtrToInt: if (AI == cast<PtrToIntInst>(I)->getOperand(0)) return true; break; case Instruction::Call: { // Ignore intrinsics that do not become real instructions. // TODO: Narrow this to intrinsics that have store-like effects. const auto *CI = cast<CallInst>(I); if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd()) return true; break; } case Instruction::Invoke: return true; case Instruction::GetElementPtr: { // If the GEP offset is out-of-bounds, or is non-constant and so has to be // assumed to be potentially out-of-bounds, then any memory access that // would use it could also be out-of-bounds meaning stack protection is // required. const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); unsigned TypeSize = DL.getIndexTypeSizeInBits(I->getType()); APInt Offset(TypeSize, 0); APInt MaxOffset(TypeSize, AllocSize); if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.ugt(MaxOffset)) return true; // Adjust AllocSize to be the space remaining after this offset. if (HasAddressTaken(I, AllocSize - Offset.getLimitedValue())) return true; break; } case Instruction::BitCast: case Instruction::Select: case Instruction::AddrSpaceCast: if (HasAddressTaken(I, AllocSize)) return true; break; case Instruction::PHI: { // Keep track of what PHI nodes we have already visited to ensure // they are only visited once. const auto *PN = cast<PHINode>(I); if (VisitedPHIs.insert(PN).second) if (HasAddressTaken(PN, AllocSize)) return true; break; } case Instruction::Load: case Instruction::AtomicRMW: case Instruction::Ret: // These instructions take an address operand, but have load-like or // other innocuous behavior that should not trigger a stack protector. // atomicrmw conceptually has both load and store semantics, but the // value being stored must be integer; so if a pointer is being stored, // we'll catch it in the PtrToInt case above. break; default: // Conservatively return true for any instruction that takes an address // operand, but is not handled above. return true; } } return false; } /// Search for the first call to the llvm.stackprotector intrinsic and return it /// if present. static const CallInst *findStackProtectorIntrinsic(Function &F) { for (const BasicBlock &BB : F) for (const Instruction &I : BB) if (const auto *II = dyn_cast<IntrinsicInst>(&I)) if (II->getIntrinsicID() == Intrinsic::stackprotector) return II; return nullptr; } /// Check whether or not this function needs a stack protector based /// upon the stack protector level. /// /// We use two heuristics: a standard (ssp) and strong (sspstrong). /// The standard heuristic which will add a guard variable to functions that /// call alloca with a either a variable size or a size >= SSPBufferSize, /// functions with character buffers larger than SSPBufferSize, and functions /// with aggregates containing character buffers larger than SSPBufferSize. The /// strong heuristic will add a guard variables to functions that call alloca /// regardless of size, functions with any buffer regardless of type and size, /// functions with aggregates that contain any buffer regardless of type and /// size, and functions that contain stack-based variables that have had their /// address taken. bool StackProtector::RequiresStackProtector() { bool Strong = false; bool NeedsProtector = false; if (F->hasFnAttribute(Attribute::SafeStack)) return false; // We are constructing the OptimizationRemarkEmitter on the fly rather than // using the analysis pass to avoid building DominatorTree and LoopInfo which // are not available this late in the IR pipeline. OptimizationRemarkEmitter ORE(F); if (F->hasFnAttribute(Attribute::StackProtectReq)) { ORE.emit([&]() { return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F) << "Stack protection applied to function " << ore::NV("Function", F) << " due to a function attribute or command-line switch"; }); NeedsProtector = true; Strong = true; // Use the same heuristic as strong to determine SSPLayout } else if (F->hasFnAttribute(Attribute::StackProtectStrong)) Strong = true; else if (!F->hasFnAttribute(Attribute::StackProtect)) return false; for (const BasicBlock &BB : *F) { for (const Instruction &I : BB) { if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { if (AI->isArrayAllocation()) { auto RemarkBuilder = [&]() { return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray", &I) << "Stack protection applied to function " << ore::NV("Function", F) << " due to a call to alloca or use of a variable length " "array"; }; if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { // A call to alloca with size >= SSPBufferSize requires // stack protectors. Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray)); ORE.emit(RemarkBuilder); NeedsProtector = true; } else if (Strong) { // Require protectors for all alloca calls in strong mode. Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_SmallArray)); ORE.emit(RemarkBuilder); NeedsProtector = true; } } else { // A call to alloca with a variable size requires protectors. Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray)); ORE.emit(RemarkBuilder); NeedsProtector = true; } continue; } bool IsLarge = false; if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { Layout.insert(std::make_pair(AI, IsLarge ? MachineFrameInfo::SSPLK_LargeArray : MachineFrameInfo::SSPLK_SmallArray)); ORE.emit([&]() { return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I) << "Stack protection applied to function " << ore::NV("Function", F) << " due to a stack allocated buffer or struct containing a " "buffer"; }); NeedsProtector = true; continue; } if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize( AI->getAllocatedType()))) { ++NumAddrTaken; Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf)); ORE.emit([&]() { return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", &I) << "Stack protection applied to function " << ore::NV("Function", F) << " due to the address of a local variable being taken"; }); NeedsProtector = true; } // Clear any PHIs that we visited, to make sure we examine all uses of // any subsequent allocas that we look at. VisitedPHIs.clear(); } } } return NeedsProtector; } /// Create a stack guard loading and populate whether SelectionDAG SSP is /// supported. static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M, IRBuilder<> &B, bool *SupportsSelectionDAGSP = nullptr) { Value *Guard = TLI->getIRStackGuard(B); auto GuardMode = TLI->getTargetMachine().Options.StackProtectorGuard; if ((GuardMode == llvm::StackProtectorGuards::TLS || GuardMode == llvm::StackProtectorGuards::None) && Guard) return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard"); // Use SelectionDAG SSP handling, since there isn't an IR guard. // // This is more or less weird, since we optionally output whether we // should perform a SelectionDAG SP here. The reason is that it's strictly // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also // mutating. There is no way to get this bit without mutating the IR, so // getting this bit has to happen in this right time. // // We could have define a new function TLI::supportsSelectionDAGSP(), but that // will put more burden on the backends' overriding work, especially when it // actually conveys the same information getIRStackGuard() already gives. if (SupportsSelectionDAGSP) *SupportsSelectionDAGSP = true; TLI->insertSSPDeclarations(*M); return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard)); } /// Insert code into the entry block that stores the stack guard /// variable onto the stack: /// /// entry: /// StackGuardSlot = alloca i8* /// StackGuard = <stack guard> /// call void @llvm.stackprotector(StackGuard, StackGuardSlot) /// /// Returns true if the platform/triple supports the stackprotectorcreate pseudo /// node. static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, const TargetLoweringBase *TLI, AllocaInst *&AI) { bool SupportsSelectionDAGSP = false; IRBuilder<> B(&F->getEntryBlock().front()); PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot"); Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP); B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), {GuardSlot, AI}); return SupportsSelectionDAGSP; } /// InsertStackProtectors - Insert code into the prologue and epilogue of the /// function. /// /// - The prologue code loads and stores the stack guard onto the stack. /// - The epilogue checks the value stored in the prologue against the original /// value. It calls __stack_chk_fail if they differ. bool StackProtector::InsertStackProtectors() { // If the target wants to XOR the frame pointer into the guard value, it's // impossible to emit the check in IR, so the target *must* support stack // protection in SDAG. bool SupportsSelectionDAGSP = TLI->useStackGuardXorFP() || (EnableSelectionDAGSP && !TM->Options.EnableFastISel && !TM->Options.EnableGlobalISel); AllocaInst *AI = nullptr; // Place on stack that stores the stack guard. for (Function::iterator I = F->begin(), E = F->end(); I != E;) { BasicBlock *BB = &*I++; ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); if (!RI) continue; // Generate prologue instrumentation if not already generated. if (!HasPrologue) { HasPrologue = true; SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI); } // SelectionDAG based code generation. Nothing else needs to be done here. // The epilogue instrumentation is postponed to SelectionDAG. if (SupportsSelectionDAGSP) break; // Find the stack guard slot if the prologue was not created by this pass // itself via a previous call to CreatePrologue(). if (!AI) { const CallInst *SPCall = findStackProtectorIntrinsic(*F); assert(SPCall && "Call to llvm.stackprotector is missing"); AI = cast<AllocaInst>(SPCall->getArgOperand(1)); } // Set HasIRCheck to true, so that SelectionDAG will not generate its own // version. SelectionDAG called 'shouldEmitSDCheck' to check whether // instrumentation has already been generated. HasIRCheck = true; // If we're instrumenting a block with a musttail call, the check has to be // inserted before the call rather than between it and the return. The // verifier guarantees that a musttail call is either directly before the // return or with a single correct bitcast of the return value in between so // we don't need to worry about many situations here. Instruction *CheckLoc = RI; Instruction *Prev = RI->getPrevNonDebugInstruction(); if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall()) CheckLoc = Prev; else if (Prev) { Prev = Prev->getPrevNonDebugInstruction(); if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall()) CheckLoc = Prev; } // Generate epilogue instrumentation. The epilogue intrumentation can be // function-based or inlined depending on which mechanism the target is // providing. if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) { // Generate the function-based epilogue instrumentation. // The target provides a guard check function, generate a call to it. IRBuilder<> B(CheckLoc); LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard"); CallInst *Call = B.CreateCall(GuardCheck, {Guard}); Call->setAttributes(GuardCheck->getAttributes()); Call->setCallingConv(GuardCheck->getCallingConv()); } else { // Generate the epilogue with inline instrumentation. // If we do not support SelectionDAG based calls, generate IR level // calls. // // For each block with a return instruction, convert this: // // return: // ... // ret ... // // into this: // // return: // ... // %1 = <stack guard> // %2 = load StackGuardSlot // %3 = cmp i1 %1, %2 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk // // SP_return: // ret ... // // CallStackCheckFailBlk: // call void @__stack_chk_fail() // unreachable // Create the FailBB. We duplicate the BB every time since the MI tail // merge pass will merge together all of the various BB into one including // fail BB generated by the stack protector pseudo instruction. BasicBlock *FailBB = CreateFailBB(); // Split the basic block before the return instruction. BasicBlock *NewBB = BB->splitBasicBlock(CheckLoc->getIterator(), "SP_return"); // Update the dominator tree if we need to. if (DT && DT->isReachableFromEntry(BB)) { DT->addNewBlock(NewBB, BB); DT->addNewBlock(FailBB, BB); } // Remove default branch instruction to the new BB. BB->getTerminator()->eraseFromParent(); // Move the newly created basic block to the point right after the old // basic block so that it's in the "fall through" position. NewBB->moveAfter(BB); // Generate the stack protector instructions in the old basic block. IRBuilder<> B(BB); Value *Guard = getStackGuard(TLI, M, B); LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true); Value *Cmp = B.CreateICmpEQ(Guard, LI2); auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true); auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false); MDNode *Weights = MDBuilder(F->getContext()) .createBranchWeights(SuccessProb.getNumerator(), FailureProb.getNumerator()); B.CreateCondBr(Cmp, NewBB, FailBB, Weights); } } // Return if we didn't modify any basic blocks. i.e., there are no return // statements in the function. return HasPrologue; } /// CreateFailBB - Create a basic block to jump to when the stack protector /// check fails. BasicBlock *StackProtector::CreateFailBB() { LLVMContext &Context = F->getContext(); BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); IRBuilder<> B(FailBB); if (F->getSubprogram()) B.SetCurrentDebugLocation( DILocation::get(Context, 0, 0, F->getSubprogram())); if (Trip.isOSOpenBSD()) { FunctionCallee StackChkFail = M->getOrInsertFunction( "__stack_smash_handler", Type::getVoidTy(Context), Type::getInt8PtrTy(Context)); B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); } else { FunctionCallee StackChkFail = M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context)); B.CreateCall(StackChkFail, {}); } B.CreateUnreachable(); return FailBB; } bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const { return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator()); } void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const { if (Layout.empty()) return; for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) { if (MFI.isDeadObjectIndex(I)) continue; const AllocaInst *AI = MFI.getObjectAllocation(I); if (!AI) continue; SSPLayoutMap::const_iterator LI = Layout.find(AI); if (LI == Layout.end()) continue; MFI.setObjectSSPLayout(I, LI->second); } }
#include "../utility/String.hpp" #include "RETypeDB.hpp" #include "RETypeDefinition.hpp" #include "MurmurHash.hpp" namespace sdk::murmur_hash { sdk::RETypeDefinition* type() { static auto t = sdk::RETypeDB::get()->find_type("via.murmur_hash"); return t; } uint32_t calc32(std::wstring_view str) { static auto calc_method = type()->get_method("calc32"); return calc_method->call<uint32_t>(sdk::get_thread_context(), sdk::VM::create_managed_string(str)); } uint32_t calc32(std::string_view str) { return calc32(utility::widen(str)); } }
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; int* a = new int[n+1]; a[0] = 0; a[1] =1; a[2] = 1; a[3] = 1; for(int i=4;i<=n;i++){ a[i] = 1 + min(a[i-1],min(a[i-2],a[i-3])); } cout<<a[n]; return 0; }
#include <vector> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include "main.h" #include "wallet.h" #include "util.h" using namespace std; BOOST_AUTO_TEST_SUITE(util_tests) BOOST_AUTO_TEST_CASE(util_criticalsection) { CCriticalSection cs; do { LOCK(cs); break; BOOST_ERROR("break was swallowed!"); } while(0); do { TRY_LOCK(cs, lockTest); if (lockTest) break; BOOST_ERROR("break was swallowed!"); } while(0); } BOOST_AUTO_TEST_CASE(util_MedianFilter) { CMedianFilter<int> filter(5, 15); BOOST_CHECK_EQUAL(filter.median(), 15); filter.input(20); // [15 20] BOOST_CHECK_EQUAL(filter.median(), 17); filter.input(30); // [15 20 30] BOOST_CHECK_EQUAL(filter.median(), 20); filter.input(3); // [3 15 20 30] BOOST_CHECK_EQUAL(filter.median(), 17); filter.input(7); // [3 7 15 20 30] BOOST_CHECK_EQUAL(filter.median(), 15); filter.input(18); // [3 7 18 20 30] BOOST_CHECK_EQUAL(filter.median(), 18); filter.input(0); // [0 3 7 18 30] BOOST_CHECK_EQUAL(filter.median(), 7); } static const unsigned char ParseHex_expected[65] = { 0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, 0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, 0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, 0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, 0x5f }; BOOST_AUTO_TEST_CASE(util_ParseHex) { std::vector<unsigned char> result; std::vector<unsigned char> expected(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)); // Basic test vector result = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end()); // Spaces between bytes must be supported result = ParseHex("12 34 56 78"); BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78); // Stop parsing at invalid value result = ParseHex("1234 invalid 1234"); BOOST_CHECK(result.size() == 2 && result[0] == 0x12 && result[1] == 0x34); } BOOST_AUTO_TEST_CASE(util_HexStr) { BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)), "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + 5, true), "04 67 8a fd b0"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected, true), ""); std::vector<unsigned char> ParseHex_vec(ParseHex_expected, ParseHex_expected + 5); BOOST_CHECK_EQUAL( HexStr(ParseHex_vec, true), "04 67 8a fd b0"); } BOOST_AUTO_TEST_CASE(util_DateTimeStrFormat) { /*These are platform-dependant and thus removed to avoid useless test failures BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 0), "1970-01-01 00:00:00"); BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 0x7FFFFFFF), "2038-01-19 03:14:07"); // Formats used within ICP BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 1317425777), "2011-09-30 23:36:17"); BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M", 1317425777), "2011-09-30 23:36"); */ } BOOST_AUTO_TEST_CASE(util_ParseParameters) { const char *argv_test[] = {"-ignored", "-a", "-b", "-ccc=argument", "-ccc=multiple", "f", "-d=e"}; ParseParameters(0, (char**)argv_test); BOOST_CHECK(mapArgs.empty() && mapMultiArgs.empty()); ParseParameters(1, (char**)argv_test); BOOST_CHECK(mapArgs.empty() && mapMultiArgs.empty()); ParseParameters(5, (char**)argv_test); // expectation: -ignored is ignored (program name argument), // -a, -b and -ccc end up in map, -d ignored because it is after // a non-option argument (non-GNU option parsing) BOOST_CHECK(mapArgs.size() == 3 && mapMultiArgs.size() == 3); BOOST_CHECK(mapArgs.count("-a") && mapArgs.count("-b") && mapArgs.count("-ccc") && !mapArgs.count("f") && !mapArgs.count("-d")); BOOST_CHECK(mapMultiArgs.count("-a") && mapMultiArgs.count("-b") && mapMultiArgs.count("-ccc") && !mapMultiArgs.count("f") && !mapMultiArgs.count("-d")); BOOST_CHECK(mapArgs["-a"] == "" && mapArgs["-ccc"] == "multiple"); BOOST_CHECK(mapMultiArgs["-ccc"].size() == 2); } BOOST_AUTO_TEST_CASE(util_GetArg) { mapArgs.clear(); mapArgs["strtest1"] = "string..."; // strtest2 undefined on purpose mapArgs["inttest1"] = "12345"; mapArgs["inttest2"] = "81985529216486895"; // inttest3 undefined on purpose mapArgs["booltest1"] = ""; // booltest2 undefined on purpose mapArgs["booltest3"] = "0"; mapArgs["booltest4"] = "1"; BOOST_CHECK_EQUAL(GetArg("strtest1", "default"), "string..."); BOOST_CHECK_EQUAL(GetArg("strtest2", "default"), "default"); BOOST_CHECK_EQUAL(GetArg("inttest1", -1), 12345); BOOST_CHECK_EQUAL(GetArg("inttest2", -1), 81985529216486895LL); BOOST_CHECK_EQUAL(GetArg("inttest3", -1), -1); BOOST_CHECK_EQUAL(GetBoolArg("booltest1", false), true); BOOST_CHECK_EQUAL(GetBoolArg("booltest2", false), false); BOOST_CHECK_EQUAL(GetBoolArg("booltest3", false), false); BOOST_CHECK_EQUAL(GetBoolArg("booltest4", false), true); } BOOST_AUTO_TEST_CASE(util_WildcardMatch) { BOOST_CHECK(WildcardMatch("127.0.0.1", "*")); BOOST_CHECK(WildcardMatch("127.0.0.1", "127.*")); BOOST_CHECK(WildcardMatch("abcdef", "a?cde?")); BOOST_CHECK(!WildcardMatch("abcdef", "a?cde??")); BOOST_CHECK(WildcardMatch("abcdef", "a*f")); BOOST_CHECK(!WildcardMatch("abcdef", "a*x")); BOOST_CHECK(WildcardMatch("", "*")); } BOOST_AUTO_TEST_CASE(util_FormatMoney) { BOOST_CHECK_EQUAL(FormatMoney(0, false), "0.00"); BOOST_CHECK_EQUAL(FormatMoney((COIN/10000)*123456789, false), "12345.6789"); BOOST_CHECK_EQUAL(FormatMoney(COIN, true), "+1.00"); BOOST_CHECK_EQUAL(FormatMoney(-COIN, false), "-1.00"); BOOST_CHECK_EQUAL(FormatMoney(-COIN, true), "-1.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000, false), "100000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000, false), "10000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000, false), "1000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100000, false), "100000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10000, false), "10000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*1000, false), "1000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100, false), "100.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10, false), "10.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN, false), "1.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10, false), "0.10"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100, false), "0.01"); BOOST_CHECK_EQUAL(FormatMoney(COIN/1000, false), "0.001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10000, false), "0.0001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100000, false), "0.00001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/1000000, false), "0.000001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10000000, false), "0.0000001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100000000, false), "0.00000001"); } BOOST_AUTO_TEST_CASE(util_ParseMoney) { int64 ret = 0; BOOST_CHECK(ParseMoney("0.0", ret)); BOOST_CHECK_EQUAL(ret, 0); BOOST_CHECK(ParseMoney("12345.6789", ret)); BOOST_CHECK_EQUAL(ret, (COIN/10000)*123456789); BOOST_CHECK(ParseMoney("100000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100000000); BOOST_CHECK(ParseMoney("10000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10000000); BOOST_CHECK(ParseMoney("1000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*1000000); BOOST_CHECK(ParseMoney("100000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100000); BOOST_CHECK(ParseMoney("10000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10000); BOOST_CHECK(ParseMoney("1000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*1000); BOOST_CHECK(ParseMoney("100.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100); BOOST_CHECK(ParseMoney("10.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10); BOOST_CHECK(ParseMoney("1.00", ret)); BOOST_CHECK_EQUAL(ret, COIN); BOOST_CHECK(ParseMoney("0.1", ret)); BOOST_CHECK_EQUAL(ret, COIN/10); BOOST_CHECK(ParseMoney("0.01", ret)); BOOST_CHECK_EQUAL(ret, COIN/100); BOOST_CHECK(ParseMoney("0.001", ret)); BOOST_CHECK_EQUAL(ret, COIN/1000); BOOST_CHECK(ParseMoney("0.0001", ret)); BOOST_CHECK_EQUAL(ret, COIN/10000); BOOST_CHECK(ParseMoney("0.00001", ret)); BOOST_CHECK_EQUAL(ret, COIN/100000); BOOST_CHECK(ParseMoney("0.000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/1000000); BOOST_CHECK(ParseMoney("0.0000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/10000000); BOOST_CHECK(ParseMoney("0.00000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/100000000); // Attempted 63 bit overflow should fail BOOST_CHECK(!ParseMoney("92233720368.54775808", ret)); } BOOST_AUTO_TEST_CASE(util_IsHex) { BOOST_CHECK(IsHex("00")); BOOST_CHECK(IsHex("00112233445566778899aabbccddeeffAABBCCDDEEFF")); BOOST_CHECK(IsHex("ff")); BOOST_CHECK(IsHex("FF")); BOOST_CHECK(!IsHex("")); BOOST_CHECK(!IsHex("0")); BOOST_CHECK(!IsHex("a")); BOOST_CHECK(!IsHex("eleven")); BOOST_CHECK(!IsHex("00xx00")); BOOST_CHECK(!IsHex("0x0000")); } BOOST_AUTO_TEST_CASE(util_seed_insecure_rand) { int i; int count=0; seed_insecure_rand(true); for (int mod=2;mod<11;mod++) { int mask = 1; // Really rough binomal confidence approximation. int err = 30*10000./mod*sqrt((1./mod*(1-1./mod))/10000.); //mask is 2^ceil(log2(mod))-1 while(mask<mod-1)mask=(mask<<1)+1; count = 0; //How often does it get a zero from the uniform range [0,mod)? for (i=0;i<10000;i++) { uint32_t rval; do{ rval=insecure_rand()&mask; }while(rval>=(uint32_t)mod); count += rval==0; } BOOST_CHECK(count<=10000/mod+err); BOOST_CHECK(count>=10000/mod-err); } } BOOST_AUTO_TEST_CASE(util_TimingResistantEqual) { BOOST_CHECK(TimingResistantEqual(std::string(""), std::string(""))); BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string(""))); BOOST_CHECK(!TimingResistantEqual(std::string(""), std::string("abc"))); BOOST_CHECK(!TimingResistantEqual(std::string("a"), std::string("aa"))); BOOST_CHECK(!TimingResistantEqual(std::string("aa"), std::string("a"))); BOOST_CHECK(TimingResistantEqual(std::string("abc"), std::string("abc"))); BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("aba"))); } BOOST_AUTO_TEST_SUITE_END()
#include "pch.h" #include "graphics/staticmeshcomponent.h" #include "graphics/renderer.h" namespace engine { void StaticMeshComponent::registerObject() { Context::getInstance()->registerObject<StaticMeshComponent>(); } StaticMeshComponent::StaticMeshComponent() { } StaticMeshComponent::~StaticMeshComponent() { } void StaticMeshComponent::render() { for (int i = 0; i < m_models.size(); i++) { m_models[i]->renderObjects(); } } void StaticMeshComponent::addModel(std::shared_ptr<ModelBase>& model) { m_models.push_back(model); } }
// Copyright (c) 2014-2019, The ByteRub Project // // 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "chaingen.h" #include "tx_validation.h" #include "device/device.hpp" using namespace epee; using namespace crypto; using namespace cryptonote; namespace { struct tx_builder { void step1_init(size_t version = 1, uint64_t unlock_time = 0) { m_tx.vin.clear(); m_tx.vout.clear(); m_tx.signatures.clear(); m_tx.version = version; m_tx.unlock_time = unlock_time; m_tx_key = keypair::generate(hw::get_device("default")); add_tx_pub_key_to_extra(m_tx, m_tx_key.pub); } void step2_fill_inputs(const account_keys& sender_account_keys, const std::vector<tx_source_entry>& sources) { BOOST_FOREACH(const tx_source_entry& src_entr, sources) { m_in_contexts.push_back(keypair()); keypair& in_ephemeral = m_in_contexts.back(); crypto::key_image img; std::unordered_map<crypto::public_key, cryptonote::subaddress_index> subaddresses; subaddresses[sender_account_keys.m_account_address.m_spend_public_key] = {0,0}; auto& out_key = reinterpret_cast<const crypto::public_key&>(src_entr.outputs[src_entr.real_output].second.dest); generate_key_image_helper(sender_account_keys, subaddresses, out_key, src_entr.real_out_tx_key, src_entr.real_out_additional_tx_keys, src_entr.real_output_in_tx_index, in_ephemeral, img, hw::get_device(("default"))); // put key image into tx input txin_to_key input_to_key; input_to_key.amount = src_entr.amount; input_to_key.k_image = img; // fill outputs array and use relative offsets BOOST_FOREACH(const tx_source_entry::output_entry& out_entry, src_entr.outputs) input_to_key.key_offsets.push_back(out_entry.first); input_to_key.key_offsets = absolute_output_offsets_to_relative(input_to_key.key_offsets); m_tx.vin.push_back(input_to_key); } } void step3_fill_outputs(const std::vector<tx_destination_entry>& destinations) { size_t output_index = 0; BOOST_FOREACH(const tx_destination_entry& dst_entr, destinations) { crypto::key_derivation derivation; crypto::public_key out_eph_public_key; crypto::generate_key_derivation(dst_entr.addr.m_view_public_key, m_tx_key.sec, derivation); crypto::derive_public_key(derivation, output_index, dst_entr.addr.m_spend_public_key, out_eph_public_key); tx_out out; out.amount = dst_entr.amount; txout_to_key tk; tk.key = out_eph_public_key; out.target = tk; m_tx.vout.push_back(out); output_index++; } } void step4_calc_hash() { get_transaction_prefix_hash(m_tx, m_tx_prefix_hash); } void step5_sign(const std::vector<tx_source_entry>& sources) { m_tx.signatures.clear(); size_t i = 0; BOOST_FOREACH(const tx_source_entry& src_entr, sources) { std::vector<const crypto::public_key*> keys_ptrs; std::vector<crypto::public_key> keys(src_entr.outputs.size()); size_t j = 0; BOOST_FOREACH(const tx_source_entry::output_entry& o, src_entr.outputs) { keys[j] = rct::rct2pk(o.second.dest); keys_ptrs.push_back(&keys[j]); ++j; } m_tx.signatures.push_back(std::vector<crypto::signature>()); std::vector<crypto::signature>& sigs = m_tx.signatures.back(); sigs.resize(src_entr.outputs.size()); generate_ring_signature(m_tx_prefix_hash, boost::get<txin_to_key>(m_tx.vin[i]).k_image, keys_ptrs, m_in_contexts[i].sec, src_entr.real_output, sigs.data()); i++; } } transaction m_tx; keypair m_tx_key; std::vector<keypair> m_in_contexts; crypto::hash m_tx_prefix_hash; }; transaction make_simple_tx_with_unlock_time(const std::vector<test_event_entry>& events, const cryptonote::block& blk_head, const cryptonote::account_base& from, const cryptonote::account_base& to, uint64_t amount, uint64_t unlock_time) { std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_head, from, to, amount, TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(1, unlock_time); builder.step2_fill_inputs(from.get_keys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); return builder.m_tx; }; crypto::public_key generate_invalid_pub_key() { for (int i = 0; i <= 0xFF; ++i) { crypto::public_key key; memset(&key, i, sizeof(crypto::public_key)); if (!crypto::check_key(key)) { return key; } } throw std::runtime_error("invalid public key wasn't found"); return crypto::public_key(); } crypto::key_image generate_invalid_key_image() { crypto::key_image key_image; // a random key image plucked from the blockchain if (!epee::string_tools::hex_to_pod("6b9f5d1be7c950dc6e4e258c6ef75509412ba9ecaaf90e6886140151d1365b5e", key_image)) throw std::runtime_error("invalid key image wasn't found"); return key_image; } } //---------------------------------------------------------------------------------------------------------------------- // Tests bool gen_tx_big_version::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(1 + 1, 0); builder.step2_fill_inputs(miner_account.get_keys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_unlock_time::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS_N(events, blk_1, blk_0, miner_account, 10); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); auto make_tx_with_unlock_time = [&](uint64_t unlock_time) -> transaction { return make_simple_tx_with_unlock_time(events, blk_1, miner_account, miner_account, MK_COINS(1), unlock_time); }; std::list<transaction> txs_0; txs_0.push_back(make_tx_with_unlock_time(0)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(get_block_height(blk_1r) - 1)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(get_block_height(blk_1r))); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(get_block_height(blk_1r) + 1)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(get_block_height(blk_1r) + 2)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(ts_start - 1)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(time(0) + 60 * 60)); events.push_back(txs_0.back()); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); return true; } bool gen_tx_input_is_not_txin_to_key::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); MAKE_NEXT_BLOCK(events, blk_tmp, blk_0r, miner_account); events.pop_back(); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(blk_tmp.miner_tx); auto make_tx_with_input = [&](const txin_v& tx_input) -> transaction { std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.m_tx.vin.push_back(tx_input); builder.step3_fill_outputs(destinations); return builder.m_tx; }; DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(make_tx_with_input(txin_to_script())); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(make_tx_with_input(txin_to_scripthash())); return true; } bool gen_tx_no_inputs_no_outputs::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); tx_builder builder; builder.step1_init(); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_no_inputs_has_outputs::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step3_fill_outputs(destinations); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_has_inputs_no_outputs::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); destinations.clear(); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); events.push_back(builder.m_tx); MAKE_NEXT_BLOCK_TX1(events, blk_1, blk_0r, miner_account, builder.m_tx); return true; } bool gen_tx_invalid_input_amount::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); sources.front().amount++; tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_input_wo_key_offsets::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); builder.step3_fill_outputs(destinations); txin_to_key& in_to_key = boost::get<txin_to_key>(builder.m_tx.vin.front()); uint64_t key_offset = in_to_key.key_offsets.front(); in_to_key.key_offsets.pop_back(); CHECK_AND_ASSERT_MES(in_to_key.key_offsets.empty(), false, "txin contained more than one key_offset"); builder.step4_calc_hash(); in_to_key.key_offsets.push_back(key_offset); builder.step5_sign(sources); in_to_key.key_offsets.pop_back(); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_key_offest_points_to_foreign_key::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); MAKE_NEXT_BLOCK(events, blk_1, blk_0, miner_account); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); MAKE_ACCOUNT(events, alice_account); MAKE_ACCOUNT(events, bob_account); MAKE_TX_LIST_START(events, txs_0, miner_account, bob_account, MK_COINS(15) + 1, blk_1); MAKE_TX_LIST(events, txs_0, miner_account, alice_account, MK_COINS(15) + 1, blk_1); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); std::vector<tx_source_entry> sources_bob; std::vector<tx_destination_entry> destinations_bob; fill_tx_sources_and_destinations(events, blk_2, bob_account, miner_account, MK_COINS(15) + 1 - TESTS_DEFAULT_FEE, TESTS_DEFAULT_FEE, 0, sources_bob, destinations_bob); std::vector<tx_source_entry> sources_alice; std::vector<tx_destination_entry> destinations_alice; fill_tx_sources_and_destinations(events, blk_2, alice_account, miner_account, MK_COINS(15) + 1 - TESTS_DEFAULT_FEE, TESTS_DEFAULT_FEE, 0, sources_alice, destinations_alice); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(bob_account.get_keys(), sources_bob); txin_to_key& in_to_key = boost::get<txin_to_key>(builder.m_tx.vin.front()); in_to_key.key_offsets.front() = sources_alice.front().outputs.front().first; builder.step3_fill_outputs(destinations_bob); builder.step4_calc_hash(); builder.step5_sign(sources_bob); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_sender_key_offest_not_exist::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); txin_to_key& in_to_key = boost::get<txin_to_key>(builder.m_tx.vin.front()); in_to_key.key_offsets.front() = std::numeric_limits<uint64_t>::max(); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_mixed_key_offest_not_exist::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); MAKE_NEXT_BLOCK(events, blk_1, blk_0, miner_account); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); MAKE_ACCOUNT(events, alice_account); MAKE_ACCOUNT(events, bob_account); MAKE_TX_LIST_START(events, txs_0, miner_account, bob_account, MK_COINS(1) + TESTS_DEFAULT_FEE, blk_1); MAKE_TX_LIST(events, txs_0, miner_account, alice_account, MK_COINS(1) + TESTS_DEFAULT_FEE, blk_1); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_2, bob_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 1, sources, destinations); sources.front().outputs[(sources.front().real_output + 1) % 2].first = std::numeric_limits<uint64_t>::max(); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(bob_account.get_keys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_key_image_not_derive_from_tx_key::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); txin_to_key& in_to_key = boost::get<txin_to_key>(builder.m_tx.vin.front()); keypair kp = keypair::generate(hw::get_device("default")); key_image another_ki; crypto::generate_key_image(kp.pub, kp.sec, another_ki); in_to_key.k_image = another_ki; builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); // Tx with invalid key image can't be subscribed, so create empty signature builder.m_tx.signatures.resize(1); builder.m_tx.signatures[0].resize(1); builder.m_tx.signatures[0][0] = crypto::signature{}; DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_key_image_is_invalid::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); txin_to_key& in_to_key = boost::get<txin_to_key>(builder.m_tx.vin.front()); in_to_key.k_image = generate_invalid_key_image(); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); // Tx with invalid key image can't be subscribed, so create empty signature builder.m_tx.signatures.resize(1); builder.m_tx.signatures[0].resize(1); builder.m_tx.signatures[0][0] = crypto::signature{}; DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_check_input_unlock_time::generate(std::vector<test_event_entry>& events) const { static const size_t tests_count = 6; uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS_N(events, blk_1, blk_0, miner_account, tests_count - 1); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); std::array<account_base, tests_count> accounts; for (size_t i = 0; i < tests_count; ++i) { MAKE_ACCOUNT(events, acc); accounts[i] = acc; } std::list<transaction> txs_0; auto make_tx_to_acc = [&](size_t acc_idx, uint64_t unlock_time) { txs_0.push_back(make_simple_tx_with_unlock_time(events, blk_1, miner_account, accounts[acc_idx], MK_COINS(1) + TESTS_DEFAULT_FEE, unlock_time)); events.push_back(txs_0.back()); }; uint64_t blk_3_height = get_block_height(blk_1r) + 2; make_tx_to_acc(0, 0); make_tx_to_acc(1, blk_3_height - 1); make_tx_to_acc(2, blk_3_height); make_tx_to_acc(3, blk_3_height + 1); make_tx_to_acc(4, time(0) - 1); make_tx_to_acc(5, time(0) + 60 * 60); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); std::list<transaction> txs_1; auto make_tx_from_acc = [&](size_t acc_idx, bool invalid) { transaction tx = make_simple_tx_with_unlock_time(events, blk_2, accounts[acc_idx], miner_account, MK_COINS(1), 0); if (invalid) { DO_CALLBACK(events, "mark_invalid_tx"); } else { txs_1.push_back(tx); } events.push_back(tx); }; make_tx_from_acc(0, false); make_tx_from_acc(1, false); make_tx_from_acc(2, false); make_tx_from_acc(3, true); make_tx_from_acc(4, false); make_tx_from_acc(5, true); MAKE_NEXT_BLOCK_TX_LIST(events, blk_3, blk_2, miner_account, txs_1); return true; } bool gen_tx_txout_to_key_has_invalid_key::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); builder.step3_fill_outputs(destinations); txout_to_key& out_to_key = boost::get<txout_to_key>(builder.m_tx.vout.front().target); out_to_key.key = generate_invalid_pub_key(); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_output_with_zero_amount::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); builder.step3_fill_outputs(destinations); builder.m_tx.vout.front().amount = 0; builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_output_is_not_txout_to_key::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<tx_source_entry> sources; std::vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), TESTS_DEFAULT_FEE, 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); builder.m_tx.vout.push_back(tx_out()); builder.m_tx.vout.back().amount = 1; builder.m_tx.vout.back().target = txout_to_script(); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); builder.step1_init(); builder.step2_fill_inputs(miner_account.get_keys(), sources); builder.m_tx.vout.push_back(tx_out()); builder.m_tx.vout.back().amount = 1; builder.m_tx.vout.back().target = txout_to_scripthash(); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_signatures_are_invalid::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); MAKE_NEXT_BLOCK(events, blk_1, blk_0, miner_account); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); MAKE_ACCOUNT(events, alice_account); MAKE_ACCOUNT(events, bob_account); MAKE_TX_LIST_START(events, txs_0, miner_account, bob_account, MK_COINS(1) + TESTS_DEFAULT_FEE, blk_1); MAKE_TX_LIST(events, txs_0, miner_account, alice_account, MK_COINS(1) + TESTS_DEFAULT_FEE, blk_1); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); MAKE_TX(events, tx_0, miner_account, miner_account, MK_COINS(60), blk_2); events.pop_back(); MAKE_TX_MIX(events, tx_1, bob_account, miner_account, MK_COINS(1), 1, blk_2); events.pop_back(); // Tx with nmix = 0 without signatures DO_CALLBACK(events, "mark_invalid_tx"); blobdata sr_tx = t_serializable_object_to_blob(static_cast<transaction_prefix>(tx_0)); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 0 have a few inputs, and not enough signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = t_serializable_object_to_blob(tx_0); sr_tx.resize(sr_tx.size() - sizeof(crypto::signature)); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 0 have a few inputs, and too many signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = t_serializable_object_to_blob(tx_0); sr_tx.insert(sr_tx.end(), sr_tx.end() - sizeof(crypto::signature), sr_tx.end()); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 1 without signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = t_serializable_object_to_blob(static_cast<transaction_prefix>(tx_1)); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 1 have not enough signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = t_serializable_object_to_blob(tx_1); sr_tx.resize(sr_tx.size() - sizeof(crypto::signature)); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 1 have too many signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = t_serializable_object_to_blob(tx_1); sr_tx.insert(sr_tx.end(), sr_tx.end() - sizeof(crypto::signature), sr_tx.end()); events.push_back(serialized_transaction(sr_tx)); return true; }
// // _IND_PASS_TEST16_CPP_ // // Copyright (C) 2017-2020 Tactical Computing Laboratories, LLC // All Rights Reserved // contact@tactcomplabs.com // // See LICENSE in the top level directory for licensing details // // #include <iostream> #include "CoreGen/CoreGenBackend/CoreGenBackend.h" std::string PROJNAME = "TEST16"; std::string PROJROOT = "./"; std::string ARCHROOT = "./"; std::string PROJYAML = "../TEST16.yaml"; std::string TARGETPASS = "DanglingNodePass"; int main( int argc, char **argv ){ CoreGenBackend *CG = new CoreGenBackend(PROJNAME, PROJROOT, ARCHROOT); if( !CG ){ std::cout << "ERROR : FAILED TO CREATE COREGEN OBJECT" << std::endl; return -1; } if( !CG->ReadIR( PROJYAML ) ){ std::cout << "ERROR : FAILED TO READ YAML IR:" << CG->GetErrStr() << std::endl; delete CG; return -1; } if( !CG->BuildDAG() ){ std::cout << "ERROR : FAILED TO BUILD THE DAG:" << CG->GetErrStr() << std::endl; delete CG; return -1; } if( !CG->InitPassMgr() ){ std::cout << "ERROR : FAILED TO INIT THE PASS MANAGER:" << CG->GetErrStr() << std::endl; delete CG; return -1; } if( !CG->ExecutePass(TARGETPASS) ){ std::cout << "ERROR : FAILED TO EXECUTE PASS : " << TARGETPASS << " : " << CG->GetErrStr() << std::endl; delete CG; return -1; } delete CG; return 0; }
// ======================================================================== // // Copyright 2009-2018 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 "TextureVolume.h" #include "TextureVolume_ispc.h" #include "../common/Data.h" namespace ospray { std::string TextureVolume::toString() const { return "ospray::TextureVolume"; } void TextureVolume::commit() { if (this->ispcEquivalent) ispc::delete_uniform(ispcEquivalent); auto v = dynamic_cast<Volume*>(getParamObject("volume")); if (v == nullptr) throw std::runtime_error("no volume specified on 'volume' texture!"); volume = v; this->ispcEquivalent = ispc::TextureVolume_create(v->getIE()); } OSP_REGISTER_TEXTURE(TextureVolume, volume); } // ::ospray
#include "duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp" #include "duckdb/execution/operator/aggregate/physical_simple_aggregate.hpp" #include "duckdb/execution/operator/aggregate/physical_window.hpp" #include "duckdb/execution/operator/filter/physical_filter.hpp" #include "duckdb/execution/operator/helper/physical_execute.hpp" #include "duckdb/execution/operator/helper/physical_limit.hpp" #include "duckdb/execution/operator/helper/physical_pragma.hpp" #include "duckdb/execution/operator/helper/physical_prepare.hpp" #include "duckdb/execution/operator/helper/physical_prune_columns.hpp" #include "duckdb/execution/operator/helper/physical_transaction.hpp" #include "duckdb/execution/operator/join/physical_blockwise_nl_join.hpp" #include "duckdb/execution/operator/join/physical_comparison_join.hpp" #include "duckdb/execution/operator/join/physical_cross_product.hpp" #include "duckdb/execution/operator/join/physical_delim_join.hpp" #include "duckdb/execution/operator/join/physical_hash_join.hpp" #include "duckdb/execution/operator/join/physical_join.hpp" #include "duckdb/execution/operator/join/physical_nested_loop_join.hpp" #include "duckdb/execution/operator/join/physical_piecewise_merge_join.hpp" #include "duckdb/execution/operator/order/physical_order.hpp" #include "duckdb/execution/operator/order/physical_top_n.hpp" #include "duckdb/execution/operator/persistent/buffered_csv_reader.hpp" #include "duckdb/execution/operator/persistent/physical_copy_from_file.hpp" #include "duckdb/execution/operator/persistent/physical_copy_to_file.hpp" #include "duckdb/execution/operator/persistent/physical_delete.hpp" #include "duckdb/execution/operator/persistent/physical_insert.hpp" #include "duckdb/execution/operator/persistent/physical_update.hpp" #include "duckdb/execution/operator/projection/physical_projection.hpp" #include "duckdb/execution/operator/scan/physical_chunk_scan.hpp" #include "duckdb/execution/operator/scan/physical_dummy_scan.hpp" #include "duckdb/execution/operator/scan/physical_empty_result.hpp" #include "duckdb/execution/operator/scan/physical_expression_scan.hpp" #include "duckdb/execution/operator/scan/physical_index_scan.hpp" #include "duckdb/execution/operator/scan/physical_table_function.hpp" #include "duckdb/execution/operator/scan/physical_table_scan.hpp" #include "duckdb/execution/operator/schema/physical_alter.hpp" #include "duckdb/execution/operator/schema/physical_create_index.hpp" #include "duckdb/execution/operator/schema/physical_create_schema.hpp" #include "duckdb/execution/operator/schema/physical_create_sequence.hpp" #include "duckdb/execution/operator/schema/physical_create_table.hpp" #include "duckdb/execution/operator/schema/physical_create_view.hpp" #include "duckdb/execution/operator/schema/physical_drop.hpp" #include "duckdb/execution/operator/set/physical_union.hpp" #include "duckdb/execution/operator/set/physical_recursive_cte.hpp"
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2020 Inviwo Foundation * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwopy/pyglmmattypes.h> #include <inviwopy/pyglmtypes.h> #include <inviwo/core/util/ostreamjoiner.h> #include <pybind11/operators.h> #include <pybind11/numpy.h> #include <pybind11/stl_bind.h> #include <map> #include <string> #include <algorithm> #include <warn/push> #include <warn/ignore/self-assign-overloaded> namespace inviwo { namespace py = pybind11; namespace { template <typename T, size_t N> using ith_T = T; template <typename V, typename T, std::size_t... I> void addInitImpl(py::class_<V> &pyv, std::index_sequence<I...>) { pyv.def(py::init<ith_T<T, I>...>()); } template <typename T, typename V, unsigned C, typename Indices = std::make_index_sequence<C>> void addInit(py::class_<V> &pyv) { addInitImpl<V, T>(pyv, Indices{}); } } // namespace template <typename T, int Cols, int Rows> void matxx(py::module &m, const std::string &prefix, const std::string &name, const std::string &postfix) { using Mat = typename util::glmtype<T, Cols, Rows>::type; static_assert(std::is_standard_layout<Mat>::value, "has to be standard_layout"); static_assert(std::is_trivially_copyable<Mat>::value, "has to be trivially_copyable"); static_assert(py::detail::is_pod_struct<Mat>::value, "has to be pod"); using ColumnVector = typename Mat::col_type; using RowVector = typename Mat::row_type; using Mat2 = typename util::glmtype<T, 2, Cols>::type; using Mat3 = typename util::glmtype<T, 3, Cols>::type; using Mat4 = typename util::glmtype<T, 4, Cols>::type; const auto classname = [&]() { std::stringstream ss; ss << prefix << name << Cols; if (Cols != Rows) { ss << "x" << Rows; } ss << postfix; return ss.str(); }(); py::class_<Mat> pym(m, classname.c_str(), py::buffer_protocol{}); addInit<T, Mat, Cols * Rows>(pym); addInit<ColumnVector, Mat, Cols>(pym); pym.def(py::init<T>()) .def(py::init<>()) .def(py::init([](py::array_t<T> arr) { if (arr.ndim() != 2) throw std::invalid_argument{"Invalid dimensions"}; if (arr.shape(0) != Cols) throw std::invalid_argument{"Invalid dimensions"}; if (arr.shape(1) != Rows) throw std::invalid_argument{"Invalid dimensions"}; Mat res; std::copy(arr.data(0), arr.data(0) + Cols * Rows, glm::value_ptr(res)); return res; })) .def(py::self + py::self) .def(py::self - py::self) .def(py::self += py::self) .def(py::self -= py::self) .def(py::self == py::self) .def(py::self != py::self) .def(py::self + T()) .def(py::self - T()) .def(py::self * T()) .def(py::self / T()) .def(py::self += T()) .def(py::self -= T()) .def(py::self *= T()) .def(py::self /= T()) .def("__getitem__", [](Mat &v, int idx) { return &v[idx]; }, py::return_value_policy::reference_internal) .def("__getitem__", [](Mat &m, int idx, int idy) { return m[idx][idy]; }) .def("__setitem__", [](Mat &m, int idx, ColumnVector &t) { return m[idx] = t; }) .def("__setitem__", [](Mat &m, int idx, int idy, T &t) { return m[idx][idy] = t; }) .def(py::self * RowVector()) .def(ColumnVector() * py::self) .def(py::self * Mat2()) .def(py::self * Mat3()) .def(py::self * Mat4()) .def_property_readonly( "array", [](Mat &self) { return py::array_t<T>(std::vector<size_t>{Rows, Cols}, glm::value_ptr(self)); }) .def("__repr__", [](Mat &m) { std::ostringstream oss; // oss << m; This fails for some reason on GCC 5.4 oss << "["; for (int col = 0; col < Cols; col++) { oss << "["; for (int row = 0; row < Rows; row++) { if (row != 0) oss << " "; oss << m[col][row]; } oss << "]"; } oss << "]"; return oss.str(); }) .def_buffer([](Mat &mat) -> py::buffer_info { return py::buffer_info( glm::value_ptr(mat), /* Pointer to buffer */ sizeof(T), /* Size of one scalar */ py::format_descriptor<T>::format(), /* Python struct-style format descriptor */ 2, /* Number of dimensions */ {Rows, Cols}, /* Buffer dimensions */ {sizeof(T), sizeof(T) * Rows} /* Strides (in bytes) for each index */ ); }); py::bind_vector<std::vector<Mat>>(m, classname + "Vector", "Vectors of glm matrices"); } template <typename T, int Cols> void matx(py::module &m, const std::string &prefix, const std::string &name, const std::string &postfix) { matxx<T, Cols, 2>(m, prefix, name, postfix); matxx<T, Cols, 3>(m, prefix, name, postfix); matxx<T, Cols, 4>(m, prefix, name, postfix); } template <typename T> void mat(py::module &m, const std::string &prefix, const std::string &name = "mat", const std::string &postfix = "") { matx<T, 2>(m, prefix, name, postfix); matx<T, 3>(m, prefix, name, postfix); matx<T, 4>(m, prefix, name, postfix); } void exposeGLMMatTypes(py::module &glmModule) { mat<float>(glmModule, ""); mat<double>(glmModule, "d"); mat<int>(glmModule, "i"); mat<unsigned int>(glmModule, "u"); } } // namespace inviwo #include <warn/pop>
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include "IResearchQueryCommon.h" #include "Aql/OptimizerRulesFeature.h" #include "IResearch/IResearchLink.h" #include "IResearch/IResearchLinkHelper.h" #include "IResearch/IResearchView.h" #include "Transaction/StandaloneContext.h" #include "Utils/OperationOptions.h" #include "Utils/SingleCollectionTransaction.h" #include "VocBase/LogicalCollection.h" #include "VocBase/ManagedDocumentResult.h" #include <velocypack/Iterator.h> extern const char* ARGV0; // defined in main.cpp namespace { static const VPackBuilder systemDatabaseBuilder = dbArgsBuilder(); static const VPackSlice systemDatabaseArgs = systemDatabaseBuilder.slice(); // ----------------------------------------------------------------------------- // --SECTION-- setup / tear-down // ----------------------------------------------------------------------------- class IResearchQueryJoinTest : public IResearchQueryTest {}; } // namespace // ----------------------------------------------------------------------------- // --SECTION-- test suite // ----------------------------------------------------------------------------- TEST_F(IResearchQueryJoinTest, Subquery) { TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL, testDBInfo(server.server())); std::shared_ptr<arangodb::LogicalCollection> entities; std::shared_ptr<arangodb::LogicalCollection> links; std::shared_ptr<arangodb::LogicalView> entities_view; std::shared_ptr<arangodb::LogicalView> links_view; // entities collection { auto json = VPackParser::fromJson("{ \"name\": \"entities\" }"); entities = vocbase.createCollection(json->slice()); ASSERT_NE(nullptr, entities); } // links collection { auto json = VPackParser::fromJson("{ \"name\": \"links\", \"type\": 3 }"); links = vocbase.createCollection(json->slice()); ASSERT_NE(nullptr, links); } // entities view { auto json = VPackParser::fromJson( "{ \"name\" : \"entities_view\", \"writebufferSizeMax\": 33554432, " "\"consolidationPolicy\": { \"type\": \"bytes_accum\", \"threshold\": " "0.10000000149011612 }, \"globallyUniqueId\": \"hB4A95C21732A/218\", " "\"id\": \"218\", \"writebufferActive\": 0, " "\"consolidationIntervalMsec\": 60000, \"cleanupIntervalStep\": 10, " "\"links\": { \"entities\": { \"analyzers\": [ \"identity\" ], " "\"fields\": {}, \"includeAllFields\": true, \"storeValues\": \"id\", " "\"trackListPositions\": false } }, \"type\": \"arangosearch\", " "\"writebufferIdle\": 64 }"); ASSERT_TRUE( arangodb::LogicalView::create(entities_view, vocbase, json->slice()).ok()); ASSERT_NE(nullptr, entities_view); } // links view { auto json = VPackParser::fromJson( "{ \"name\" : \"links_view\", \"writebufferSizeMax\": 33554432, " "\"consolidationPolicy\": { \"type\": \"bytes_accum\", \"threshold\": " "0.10000000149011612 }, \"globallyUniqueId\": \"hB4A95C21732A/181\", " "\"id\": \"181\", \"writebufferActive\": 0, " "\"consolidationIntervalMsec\": 60000, \"cleanupIntervalStep\": 10, " "\"links\": { \"links\": { \"analyzers\": [ \"identity\" ], " "\"fields\": {}, \"includeAllFields\": true, \"storeValues\": \"id\", " "\"trackListPositions\": false } }, \"type\": \"arangosearch\", " "\"writebufferIdle\": 64 }"); ASSERT_TRUE( arangodb::LogicalView::create(links_view, vocbase, json->slice()).ok()); ASSERT_NE(nullptr, links_view); } std::vector<std::string> const collections{"entities", "links"}; // populate views with the data { arangodb::OperationOptions opt; arangodb::transaction::Methods trx(arangodb::transaction::StandaloneContext::Create(vocbase), collections, collections, collections, arangodb::transaction::Options()); EXPECT_TRUE(trx.begin().ok()); // insert into entities collection { auto builder = VPackParser::fromJson( "[{ \"_key\": \"person1\", \"_id\": \"entities/person1\", \"_rev\": " "\"_YOr40eu--_\", \"type\": \"person\", \"id\": \"person1\" }," " { \"_key\": \"person5\", \"_id\": \"entities/person5\", \"_rev\": " "\"_YOr48rO---\", \"type\": \"person\", \"id\": \"person5\" }," " { \"_key\": \"person4\", \"_id\": \"entities/person4\", \"_rev\": " "\"_YOr5IGu--_\", \"type\": \"person\", \"id\": \"person4\" }," " { \"_key\": \"person3\", \"_id\": \"entities/person3\", \"_rev\": " "\"_YOr5PBK--_\", \"type\": \"person\", \"id\": \"person3\" }, " " { \"_key\": \"person2\", \"_id\": \"entities/person2\", \"_rev\": " "\"_YOr5Umq--_\", \"type\": \"person\", \"id\": \"person2\" } ]"); auto root = builder->slice(); ASSERT_TRUE(root.isArray()); arangodb::ManagedDocumentResult mmdr; for (auto doc : arangodb::velocypack::ArrayIterator(root)) { auto const res = entities->insert(&trx, doc, mmdr, opt); EXPECT_TRUE(res.ok()); } } // insert into links collection { auto builder = VPackParser::fromJson( "[ { \"_key\": \"3301\", \"_id\": \"links/3301\", \"_from\": " "\"entities/person1\", \"_to\": \"entities/person2\", \"_rev\": " "\"_YOrbp_S--_\", \"type\": \"relationship\", \"subType\": " "\"married\", \"from\": \"person1\", \"to\": \"person2\" }," " { \"_key\": \"3377\", \"_id\": \"links/3377\", \"_from\": " "\"entities/person4\", \"_to\": \"entities/person5\", \"_rev\": " "\"_YOrbxN2--_\", \"type\": \"relationship\", \"subType\": " "\"married\", \"from\": \"person4\", \"to\": \"person5\" }," " { \"_key\": \"3346\", \"_id\": \"links/3346\", \"_from\": " "\"entities/person1\", \"_to\": \"entities/person3\", \"_rev\": " "\"_YOrb4kq--_\", \"type\": \"relationship\", \"subType\": " "\"married\", \"from\": \"person1\", \"to\": \"person3\" }]"); auto root = builder->slice(); ASSERT_TRUE(root.isArray()); arangodb::ManagedDocumentResult mmdr; for (auto doc : arangodb::velocypack::ArrayIterator(root)) { auto const res = links->insert(&trx, doc, mmdr, opt); EXPECT_TRUE(res.ok()); } } EXPECT_TRUE(trx.commit().ok()); EXPECT_TRUE((arangodb::iresearch::IResearchLinkHelper::find(*entities, *entities_view) ->commit() .ok())); EXPECT_TRUE((arangodb::iresearch::IResearchLinkHelper::find(*links, *links_view) ->commit() .ok())); } // check query { auto expectedResultBuilder = VPackParser::fromJson( "[ { \"id\": \"person1\", \"marriedIds\": [\"person2\", \"person3\"] }," " { \"id\": \"person2\", \"marriedIds\": [\"person1\" ] }," " { \"id\": \"person3\", \"marriedIds\": [\"person1\" ] }," " { \"id\": \"person4\", \"marriedIds\": [\"person5\" ] }," " { \"id\": \"person5\", \"marriedIds\": [\"person4\" ] } ]"); std::string const query = "FOR org IN entities_view SEARCH org.type == 'person' " "LET marriedIds = (" "LET entityIds = (" " FOR l IN links_view SEARCH l.type == 'relationship' AND l.subType " "== 'married' AND (l.from == org.id OR l.to == org.id)" " RETURN DISTINCT l.from == org.id ? l.to : l.from" ") " "FOR entityId IN entityIds SORT entityId RETURN entityId " ") " "LIMIT 10 " "SORT org._key " "RETURN { id: org._key, marriedIds: marriedIds }"; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); auto expectedResult = expectedResultBuilder->slice(); EXPECT_TRUE(expectedResult.isArray()); arangodb::velocypack::ArrayIterator expectedResultIt(expectedResult); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedResultIt.size(), resultIt.size()); // Check documents for (; resultIt.valid(); resultIt.next(), expectedResultIt.next()) { ASSERT_TRUE(expectedResultIt.valid()); auto const expectedDoc = expectedResultIt.value(); auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(expectedDoc), resolved, true))); } EXPECT_FALSE(expectedResultIt.valid()); } } TEST_F(IResearchQueryJoinTest, DuplicateDataSource) { static std::vector<std::string> const EMPTY; auto createJson = VPackParser::fromJson( "{ \ \"name\": \"testView\", \ \"type\": \"arangosearch\" \ }"); TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL, testDBInfo(server.server())); std::shared_ptr<arangodb::LogicalCollection> logicalCollection1; std::shared_ptr<arangodb::LogicalCollection> logicalCollection2; std::shared_ptr<arangodb::LogicalCollection> logicalCollection3; // add collection_1 { auto collectionJson = VPackParser::fromJson("{ \"name\": \"collection_1\" }"); logicalCollection1 = vocbase.createCollection(collectionJson->slice()); ASSERT_NE(nullptr, logicalCollection1); } // add collection_2 { auto collectionJson = VPackParser::fromJson("{ \"name\": \"collection_2\" }"); logicalCollection2 = vocbase.createCollection(collectionJson->slice()); ASSERT_NE(nullptr, logicalCollection2); } // add collection_3 { auto collectionJson = VPackParser::fromJson("{ \"name\": \"collection_3\" }"); logicalCollection3 = vocbase.createCollection(collectionJson->slice()); ASSERT_NE(nullptr, logicalCollection3); } // add view auto view = std::dynamic_pointer_cast<arangodb::iresearch::IResearchView>( vocbase.createView(createJson->slice())); ASSERT_FALSE(!view); // add logical collection with the same name as view { auto collectionJson = VPackParser::fromJson("{ \"name\": \"testView\" }"); // TRI_vocbase_t::createCollection(...) throws exception instead of returning a nullptr EXPECT_ANY_THROW(vocbase.createCollection(collectionJson->slice())); } // add link to collection { auto updateJson = VPackParser::fromJson( "{ \"links\": {" "\"collection_1\": { \"analyzers\": [ \"test_analyzer\", \"identity\" " "], \"includeAllFields\": true, \"trackListPositions\": true }," "\"collection_2\": { \"analyzers\": [ \"test_analyzer\", \"identity\" " "], \"includeAllFields\": true }" "}}"); EXPECT_TRUE(view->properties(updateJson->slice(), true).ok()); arangodb::velocypack::Builder builder; builder.openObject(); view->properties(builder, arangodb::LogicalDataSource::Serialization::Properties); builder.close(); auto slice = builder.slice(); EXPECT_TRUE(slice.isObject()); EXPECT_EQ(slice.get("name").copyString(), "testView"); EXPECT_TRUE(slice.get("type").copyString() == arangodb::iresearch::DATA_SOURCE_TYPE.name()); EXPECT_TRUE(slice.get("deleted").isNone()); // no system properties auto tmpSlice = slice.get("links"); EXPECT_TRUE(tmpSlice.isObject() && 2 == tmpSlice.length()); } std::deque<arangodb::ManagedDocumentResult> insertedDocsView; // populate view with the data { arangodb::OperationOptions opt; arangodb::transaction::Methods trx(arangodb::transaction::StandaloneContext::Create(vocbase), EMPTY, EMPTY, EMPTY, arangodb::transaction::Options()); EXPECT_TRUE(trx.begin().ok()); // insert into collections { irs::utf8_path resource; resource /= irs::string_ref(arangodb::tests::testResourceDir); resource /= irs::string_ref("simple_sequential.json"); auto builder = arangodb::basics::VelocyPackHelper::velocyPackFromFile(resource.utf8()); auto root = builder.slice(); ASSERT_TRUE(root.isArray()); size_t i = 0; std::shared_ptr<arangodb::LogicalCollection> collections[]{logicalCollection1, logicalCollection2}; for (auto doc : arangodb::velocypack::ArrayIterator(root)) { insertedDocsView.emplace_back(); auto const res = collections[i % 2]->insert(&trx, doc, insertedDocsView.back(), opt); EXPECT_TRUE(res.ok()); ++i; } } // insert into collection_3 std::deque<arangodb::ManagedDocumentResult> insertedDocsCollection; { irs::utf8_path resource; resource /= irs::string_ref(arangodb::tests::testResourceDir); resource /= irs::string_ref("simple_sequential_order.json"); auto builder = arangodb::basics::VelocyPackHelper::velocyPackFromFile(resource.utf8()); auto root = builder.slice(); ASSERT_TRUE(root.isArray()); for (auto doc : arangodb::velocypack::ArrayIterator(root)) { insertedDocsCollection.emplace_back(); auto const res = logicalCollection3->insert(&trx, doc, insertedDocsCollection.back(), opt); EXPECT_TRUE(res.ok()); } } EXPECT_TRUE(trx.commit().ok()); EXPECT_TRUE( (arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH 1 ==1 OPTIONS " "{ waitForSync: true } RETURN d") .result.ok())); // commit } // using search keyword for collection is prohibited { std::string const query = "LET c=5 FOR x IN collection_1 SEARCH x.seq == c RETURN x"; auto const boundParameters = VPackParser::fromJson("{ }"); // arangodb::aql::ExecutionPlan::fromNodeFor(...) throws TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND auto queryResult = arangodb::tests::executeQuery(vocbase, query, boundParameters); EXPECT_TRUE(queryResult.result.is(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND)); } // using search keyword for bound collection is prohibited { std::string const query = "LET c=5 FOR x IN @@dataSource SEARCH x.seq == c RETURN x"; auto const boundParameters = VPackParser::fromJson("{ \"@dataSource\" : \"collection_1\" }"); auto queryResult = arangodb::tests::executeQuery(vocbase, query, boundParameters); EXPECT_TRUE(queryResult.result.is(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND)); } } TEST_F(IResearchQueryJoinTest, test) { static std::vector<std::string> const EMPTY; auto createJson = VPackParser::fromJson( "{ \ \"name\": \"testView\", \ \"type\": \"arangosearch\" \ }"); TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL, testDBInfo(server.server())); std::shared_ptr<arangodb::LogicalCollection> logicalCollection1; std::shared_ptr<arangodb::LogicalCollection> logicalCollection2; std::shared_ptr<arangodb::LogicalCollection> logicalCollection3; // add collection_1 { auto collectionJson = VPackParser::fromJson("{ \"name\": \"collection_1\" }"); logicalCollection1 = vocbase.createCollection(collectionJson->slice()); ASSERT_NE(nullptr, logicalCollection1); } // add collection_2 { auto collectionJson = VPackParser::fromJson("{ \"name\": \"collection_2\" }"); logicalCollection2 = vocbase.createCollection(collectionJson->slice()); ASSERT_NE(nullptr, logicalCollection2); } // add collection_3 { auto collectionJson = VPackParser::fromJson("{ \"name\": \"collection_3\" }"); logicalCollection3 = vocbase.createCollection(collectionJson->slice()); ASSERT_NE(nullptr, logicalCollection3); } // add view auto view = std::dynamic_pointer_cast<arangodb::iresearch::IResearchView>( vocbase.createView(createJson->slice())); ASSERT_FALSE(!view); // add link to collection { auto updateJson = VPackParser::fromJson( "{ \"links\": {" "\"collection_1\": { \"analyzers\": [ \"test_analyzer\", \"identity\" " "], \"includeAllFields\": true, \"trackListPositions\": true }," "\"collection_2\": { \"analyzers\": [ \"test_analyzer\", \"identity\" " "], \"includeAllFields\": true }" "}}"); EXPECT_TRUE(view->properties(updateJson->slice(), true).ok()); arangodb::velocypack::Builder builder; builder.openObject(); view->properties(builder, arangodb::LogicalDataSource::Serialization::Properties); builder.close(); auto slice = builder.slice(); EXPECT_TRUE(slice.isObject()); EXPECT_EQ(slice.get("name").copyString(), "testView"); EXPECT_TRUE(slice.get("type").copyString() == arangodb::iresearch::DATA_SOURCE_TYPE.name()); EXPECT_TRUE(slice.get("deleted").isNone()); // no system properties auto tmpSlice = slice.get("links"); EXPECT_TRUE(tmpSlice.isObject() && 2 == tmpSlice.length()); } std::deque<arangodb::ManagedDocumentResult> insertedDocsView; // populate view with the data { arangodb::OperationOptions opt; arangodb::transaction::Methods trx(arangodb::transaction::StandaloneContext::Create(vocbase), EMPTY, EMPTY, EMPTY, arangodb::transaction::Options()); EXPECT_TRUE(trx.begin().ok()); // insert into collections { irs::utf8_path resource; resource /= irs::string_ref(arangodb::tests::testResourceDir); resource /= irs::string_ref("simple_sequential.json"); auto builder = arangodb::basics::VelocyPackHelper::velocyPackFromFile(resource.utf8()); auto root = builder.slice(); ASSERT_TRUE(root.isArray()); size_t i = 0; std::shared_ptr<arangodb::LogicalCollection> collections[]{logicalCollection1, logicalCollection2}; for (auto doc : arangodb::velocypack::ArrayIterator(root)) { insertedDocsView.emplace_back(); auto const res = collections[i % 2]->insert(&trx, doc, insertedDocsView.back(), opt); EXPECT_TRUE(res.ok()); ++i; } } // insert into collection_3 std::deque<arangodb::ManagedDocumentResult> insertedDocsCollection; { irs::utf8_path resource; resource /= irs::string_ref(arangodb::tests::testResourceDir); resource /= irs::string_ref("simple_sequential_order.json"); auto builder = arangodb::basics::VelocyPackHelper::velocyPackFromFile(resource.utf8()); auto root = builder.slice(); ASSERT_TRUE(root.isArray()); for (auto doc : arangodb::velocypack::ArrayIterator(root)) { insertedDocsCollection.emplace_back(); auto const res = logicalCollection3->insert(&trx, doc, insertedDocsCollection.back(), opt); EXPECT_TRUE(res.ok()); } } EXPECT_TRUE(trx.commit().ok()); EXPECT_TRUE( (arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH 1 ==1 OPTIONS " "{ waitForSync: true } RETURN d") .result.ok())); // commit } // deterministic filter condition in a loop // (should not recreate view iterator each loop iteration, `reset` instead) // // LET c=5 // FOR x IN 1..7 // FOR d IN testView // SEARCH c == x.seq // RETURN d; { std::string const query = "LET c=5 FOR x IN 1..7 FOR d IN testView SEARCH c == d.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // non deterministic filter condition in a loop // (must recreate view iterator each loop iteration) // // FOR x IN 1..7 // FOR d IN testView // SEARCH _FORWARD_(5) == x.seq // RETURN d; { std::string const query = "FOR x IN 1..7 FOR d IN testView SEARCH _FORWARD_(5) == d.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // non deterministic filter condition with self-reference in a loop // (must recreate view iterator each loop iteration) // // FOR x IN 1..7 // FOR d IN testView // SEARCH _NONDETERM_(5) == x.seq // RETURN d; { std::string const query = "FOR x IN 1..7 FOR d IN testView SEARCH _NONDETERM_(5) == d.seq RETURN " "d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.is(TRI_ERROR_NOT_IMPLEMENTED)); // can't handle self-referenced variable now // auto result = queryResult.data->slice(); // EXPECT_TRUE(result.isArray()); // // arangodb::velocypack::ArrayIterator resultIt(result); // ASSERT_EQ(expectedDocs.size(), resultIt.size()); // // // Check documents // auto expectedDoc = expectedDocs.begin(); // for (;resultIt.valid(); resultIt.next(), ++expectedDoc) { // auto const actualDoc = resultIt.value(); // auto const resolved = actualDoc.resolveExternals(); // // EXPECT_EQ(0, arangodb::basics::VelocyPackHelper::compare(arangodb::velocypack::Slice(*expectedDoc), resolved, true)); // } // EXPECT_EQ(expectedDoc, expectedDocs.end()); } // nondeterministic filter condition in a loop // (must recreate view iterator each loop iteration) // // LET c=_NONDETERM_(4) // FOR x IN 1..7 // FOR d IN testView // SEARCH c == x.seq // RETURN d; { std::string const query = "LET c=_NONDETERM_(4) FOR x IN 1..7 FOR d IN testView SEARCH c == " "d.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // nondeterministic range // (must recreate view iterator each loop iteration) // // LET range=_NONDETERM_(0).._NONDETERM_(7) // FOR x IN range // FOR d IN testView // SEARCH d.seq == x.seq // RETURN d; { std::string const query = " FOR x IN _NONDETERM_(0).._NONDETERM_(7) FOR d IN testView SEARCH x " "== d.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[0].vpack()), arangodb::velocypack::Slice(insertedDocsView[1].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), arangodb::velocypack::Slice(insertedDocsView[3].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[7].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // FOR x IN collection_3 // FOR d IN testView // SEARCH d.seq == x.seq // RETURN d; { std::string const query = "FOR x IN collection_3 SORT x._key FOR d IN testView SEARCH x.seq == " "d.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[0].vpack()), arangodb::velocypack::Slice(insertedDocsView[1].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), arangodb::velocypack::Slice(insertedDocsView[3].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[7].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE(arangodb::basics::VelocyPackHelper::equal(arangodb::velocypack::Slice(*expectedDoc), resolved, true)) << arangodb::velocypack::Slice(*expectedDoc).toJson() << " vs. " << resolved.toJson(); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // FOR x IN collection_3 // FOR d IN testView // SEARCH d.seq == x.seq // SORT d.seq DESC // RETURN d; { std::string const query = "FOR x IN collection_3 FOR d IN testView SEARCH x.seq == d.seq SORT " "d.seq DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[7].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[3].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), arangodb::velocypack::Slice(insertedDocsView[1].vpack()), arangodb::velocypack::Slice(insertedDocsView[0].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // FOR x IN collection_3 // FOR d IN testView // SEARCH d.seq == x.seq // SORT d.seq DESC // LIMIT 3 // RETURN d; { std::string const query = "FOR x IN collection_3 FOR d IN testView SEARCH x.seq == d.seq SORT " "d.seq DESC LIMIT 3 RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[7].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // FOR x IN collection_3 // FOR d IN testView // SEARCH d.seq == x.seq && (d.value > 5 && d.value <= 100) // RETURN d; { std::string const query = "FOR x IN collection_3 FOR d IN testView SEARCH x.seq == d.seq && " "(d.value > 5 && d.value <= 100) SORT d.seq DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[3].vpack()), arangodb::velocypack::Slice(insertedDocsView[0].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // FOR x IN collection_3 // FOR d IN testView // SEARCH d.seq == x.seq // SORT BM25(d) ASC, d.seq DESC // RETURN d; { std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[7].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[3].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), arangodb::velocypack::Slice(insertedDocsView[1].vpack()), arangodb::velocypack::Slice(insertedDocsView[0].vpack())}; auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR x IN collection_3 FOR d IN testView SEARCH x.seq == d.seq SORT " "BM25(d) ASC, d.seq DESC RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // Note: unable to push condition to the `View` now // FOR d IN testView // FOR x IN collection_3 // SEARCH d.seq == x.seq // RETURN d; { std::string const query = "FOR d IN testView FOR x IN collection_3 FILTER d.seq == x.seq SORT " "d.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, {})); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[0].vpack()), arangodb::velocypack::Slice(insertedDocsView[1].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), arangodb::velocypack::Slice(insertedDocsView[3].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[7].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // Note: unable to push condition to the `View` now // FOR d IN testView // FOR x IN collection_3 // SEARCH d.seq == x.seq && d.name == 'B' // RETURN d; { std::string const query = "FOR d IN testView FOR x IN collection_3 FILTER d.seq == x.seq && " "d.name == 'B' RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, {})); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[1].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // Note: unable to push condition to the `View` now // FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 RETURN c) // FOR x IN collection_3 // SEARCH d.seq == x.seq // RETURN d; { std::string const query = "FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 RETURN " "c) FOR x IN collection_3 FILTER d.seq == x.seq SORT d.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[7].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // Note: unable to push condition to the `View` now // FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 SORT TFIDF(c) ASC, c.seq DESC RETURN c) // FOR x IN collection_3 // SEARCH d.seq == x.seq // RETURN d; { std::string const query = "FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 SORT " "TFIDF(c) ASC, c.seq DESC RETURN c) FOR x IN collection_3 FILTER d.seq " "== x.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[7].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // Note: unable to push condition to the `View` now // FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 SORT TFIDF(c) ASC, c.seq DESC RETURN c) // FOR x IN collection_3 // SEARCH d.seq == x.seq // LIMIT 2 // RETURN d; { std::string const query = "FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 SORT " "TFIDF(c) ASC, c.seq DESC RETURN c) FOR x IN collection_3 FILTER d.seq " "== x.seq LIMIT 2 RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[7].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // Note: unable to push condition to the `View` now // FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 SORT TFIDF(c) ASC, c.seq DESC LIMIT 3 RETURN c) // FOR x IN collection_3 // SEARCH d.seq == x.seq // RETURN d; { std::string const query = "FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 SORT " "TFIDF(c) ASC, c.seq DESC LIMIT 5 RETURN c) FOR x IN collection_3 " "FILTER d.seq == x.seq RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules( vocbase, query, {arangodb::aql::OptimizerRule::handleArangoSearchViewsRule})); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[7].vpack()), arangodb::velocypack::Slice(insertedDocsView[6].vpack()), arangodb::velocypack::Slice(insertedDocsView[5].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // Invalid bound collection name { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 SORT " "TFIDF(c) ASC, c.seq DESC LIMIT 5 RETURN c) FOR x IN @@collection " "SEARCH d.seq == x.seq RETURN d", VPackParser::fromJson( "{ \"@collection\": \"invlaidCollectionName\" }")); ASSERT_TRUE(queryResult.result.is(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND)); } // dependent sort condition in inner loop + custom scorer // (must recreate view iterator each loop iteration) // // FOR x IN 0..5 // FOR d IN testView // SEARCH d.seq == x // SORT customscorer(d,x) // RETURN d; { std::string const query = "FOR x IN 0..5 FOR d IN testView SEARCH d.seq == x SORT " "customscorer(d, x) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[5].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[3].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), arangodb::velocypack::Slice(insertedDocsView[1].vpack()), arangodb::velocypack::Slice(insertedDocsView[0].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // invalid reference in scorer { std::string const query = "FOR d IN testView FOR i IN 0..5 SORT tfidf(i) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, {})); auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.is(TRI_ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH)); } // FOR i IN 1..5 // FOR x IN collection_0 // FOR d IN SEARCH d.seq == i && d.name == x.name // SORT customscorer(d, x.seq) { std::string const query = "FOR i IN 1..5 FOR x IN collection_1 FOR d IN testView SEARCH d.seq == " "i AND d.name == x.name SORT customscorer(d, x.seq) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack())}; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // FOR i IN 1..5 // FOR x IN collection_0 SEARCH x.seq == i // FOR d IN SEARCH d.seq == x.seq && d.name == x.name // SORT customscorer(d, x.seq) { std::string const query = "FOR i IN 1..5 FOR x IN collection_1 FILTER x.seq == i FOR d IN " "testView SEARCH d.seq == x.seq AND d.name == x.name SORT " "customscorer(d, x.seq) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } { std::string const query = "LET attr = _NONDETERM_('seq') " "FOR i IN 1..5 " " FOR x IN collection_1 FILTER x.seq == i " " FOR d IN testView SEARCH d.seq == x.seq AND d.name == x.name " " SORT customscorer(d, x[attr]) DESC " "RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // FOR i IN 1..5 // FOR x IN collection_0 SEARCH x.seq == i // FOR d IN SEARCH d.seq == x.seq && d.name == x.name // SORT customscorer(d, x.seq) { std::string const query = "FOR i IN 1..5 FOR x IN collection_1 FILTER x.seq == i FOR d IN " "testView SEARCH d.seq == x.seq AND d.name == x.name SORT " "customscorer(d, x['seq']) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // unable to retrieve `d.seq` from self-referenced variable // FOR i IN 1..5 // FOR d IN SEARCH d.seq == i SORT customscorer(d, d.seq) // FOR x IN collection_0 SEARCH x.seq == d.seq && x.name == d.name // SORT customscorer(d, d.seq) DESC { std::string const query = "FOR i IN 1..5 FOR d IN testView SEARCH d.seq == i FOR x IN " "collection_1 FILTER x.seq == d.seq && x.name == d.name SORT " "customscorer(d, d.seq) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.is(TRI_ERROR_BAD_PARAMETER)); } // unable to retrieve `x.seq` from inner loop // FOR i IN 1..5 // FOR d IN SEARCH d.seq == i SORT customscorer(d, d.seq) // FOR x IN collection_0 SEARCH x.seq == d.seq && x.name == d.name // SORT customscorer(d, x.seq) DESC { std::string const query = "FOR i IN 1..5 FOR d IN testView SEARCH d.seq == i FOR x IN " "collection_1 FILTER x.seq == d.seq && x.name == d.name SORT " "customscorer(d, x.seq) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.is(TRI_ERROR_BAD_PARAMETER)); } // FOR i IN 1..5 // FOR d IN SEARCH d.seq == i SORT customscorer(d, i) ASC // FOR x IN collection_0 SEARCH x.seq == d.seq && x.name == d.name // SORT customscorer(d, i) DESC { std::string const query = "FOR i IN 1..5 " " FOR d IN testView SEARCH d.seq == i SORT customscorer(d, i) ASC " " FOR x IN collection_1 FILTER x.seq == d.seq && x.name == d.name " "SORT customscorer(d, i) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // dedicated to https://github.com/arangodb/planning/issues/3065$ // Optimizer rule "inline sub-queries" which doesn't handle views correctly$ { std::string const query = "LET fullAccounts = (FOR acc1 IN [1] RETURN { 'key': 'A' }) for a IN " "fullAccounts for d IN testView SEARCH d.name == a.key return d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, {arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, arangodb::aql::OptimizerRule::inlineSubqueriesRule})); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[0].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // FOR i IN 1..5 // FOR d IN testView SEARCH d.seq == i // FOR x IN collection_1 FILTER x.seq == d.seq && x.seq == TFIDF(d) { std::string const query = "FOR i IN 1..5 " " FOR d IN testView SEARCH d.seq == i " " FOR x IN collection_1 FILTER x.seq == d.seq && x.seq == " "customscorer(d, i)" "RETURN x"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[2].vpack()), arangodb::velocypack::Slice(insertedDocsView[4].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } { std::string const query = "FOR i IN 1..5 " " FOR d IN testView SEARCH d.seq == i " " FOR x IN collection_1 FILTER x.seq == d.seq " "SORT 1 + customscorer(d, i) DESC " "RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // multiple sorts { std::string const query = "FOR i IN 1..5 " " FOR d IN testView SEARCH d.seq == i SORT tfidf(d, i > 0) ASC " " FOR x IN collection_1 FILTER x.seq == d.seq && x.name == d.name " "SORT customscorer(d, i) DESC RETURN d"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocsView[4].vpack()), arangodb::velocypack::Slice(insertedDocsView[2].vpack()), }; auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true))); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } // x.seq is used before being assigned { std::string const query = "FOR d IN testView SEARCH d.name >= 'E' && d.seq < 10 " " SORT customscorer(d) DESC " " LIMIT 3 " " FOR x IN collection_1 FILTER x.seq == d.seq " " SORT customscorer(d, x.seq) " "RETURN x"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.is(TRI_ERROR_BAD_PARAMETER)); } // x.seq is used before being assigned { std::string const query = "FOR d IN (FOR c IN testView SEARCH c.name >= 'E' && c.seq < 10 SORT " "customscorer(c) DESC LIMIT 3 RETURN c) " " FOR x IN collection_1 FILTER x.seq == d.seq " " SORT customscorer(d, x.seq) " "RETURN x"; EXPECT_TRUE(arangodb::tests::assertRules(vocbase, query, { arangodb::aql::OptimizerRule::handleArangoSearchViewsRule, })); auto queryResult = arangodb::tests::executeQuery(vocbase, query); ASSERT_TRUE(queryResult.result.is(TRI_ERROR_BAD_PARAMETER)); } }
#include "deco-layout.hpp" #include "deco-theme.hpp" #include <wayfire/core.hpp> #include <wayfire/nonstd/reverse.hpp> #include <wayfire/nonstd/wlroots-full.hpp> #define BUTTON_ASPECT_RATIO (25.0 / 16.0) #define BUTTON_HEIGHT_PC 0.8 namespace wf { namespace decor { /** * Represents an area of the decoration which reacts to input events. */ decoration_area_t::decoration_area_t(decoration_area_type_t type, wf::geometry_t g) { this->type = type; this->geometry = g; assert(type != DECORATION_AREA_BUTTON); } /** * Initialize a new decoration area holding a button */ decoration_area_t::decoration_area_t(wf::geometry_t g, std::function<void(wlr_box)> damage_callback, const decoration_theme_t& theme) { this->type = DECORATION_AREA_BUTTON; this->geometry = g; this->button = std::make_unique<button_t>(theme, std::bind(damage_callback, g)); } wf::geometry_t decoration_area_t::get_geometry() const { return geometry; } button_t& decoration_area_t::as_button() { assert(button); return *button; } decoration_area_type_t decoration_area_t::get_type() const { return type; } decoration_layout_t::decoration_layout_t(const decoration_theme_t& th, std::function<void(wlr_box)> callback) : titlebar_size(th.get_title_height()), border_size(th.get_border_size()), button_width(titlebar_size * BUTTON_HEIGHT_PC * BUTTON_ASPECT_RATIO), button_height(titlebar_size * BUTTON_HEIGHT_PC), button_padding((titlebar_size - button_height) / 2), theme(th), damage_callback(callback) {} wf::geometry_t decoration_layout_t::create_buttons(int width, int) { std::stringstream stream((std::string)button_order); std::vector<button_type_t> buttons; std::string button_name; while (stream >> button_name) { if (button_name == "minimize") { buttons.push_back(BUTTON_MINIMIZE); } if (button_name == "maximize") { buttons.push_back(BUTTON_TOGGLE_MAXIMIZE); } if (button_name == "close") { buttons.push_back(BUTTON_CLOSE); } } int per_button = 2 * button_padding + button_width; wf::geometry_t button_geometry = { width - border_size + button_padding, /* 1 more padding initially */ button_padding + border_size, button_width, button_height, }; for (auto type : wf::reverse(buttons)) { button_geometry.x -= per_button; this->layout_areas.push_back(std::make_unique<decoration_area_t>( button_geometry, damage_callback, theme)); this->layout_areas.back()->as_button().set_button_type(type); } int total_width = -button_padding + buttons.size() * per_button; return { button_geometry.x, border_size, total_width, titlebar_size }; } /** Regenerate layout using the new size */ void decoration_layout_t::resize(int width, int height) { this->layout_areas.clear(); if (this->titlebar_size > 0) { auto button_geometry_expanded = create_buttons(width, height); /* Padding around the button, allows move */ this->layout_areas.push_back(std::make_unique<decoration_area_t>( DECORATION_AREA_MOVE, button_geometry_expanded)); /* Titlebar dragging area (for move) */ wf::geometry_t title_geometry = { border_size, border_size, /* Up to the button, but subtract the padding to the left of the * title and the padding between title and button */ button_geometry_expanded.x - border_size, titlebar_size, }; this->layout_areas.push_back(std::make_unique<decoration_area_t>( DECORATION_AREA_TITLE, title_geometry)); } /* Resizing edges - left */ wf::geometry_t border_geometry = {0, 0, border_size, height}; this->layout_areas.push_back(std::make_unique<decoration_area_t>( DECORATION_AREA_RESIZE_LEFT, border_geometry)); /* Resizing edges - right */ border_geometry = {width - border_size, 0, border_size, height}; this->layout_areas.push_back(std::make_unique<decoration_area_t>( DECORATION_AREA_RESIZE_RIGHT, border_geometry)); /* Resizing edges - top */ border_geometry = {0, 0, width, border_size}; this->layout_areas.push_back(std::make_unique<decoration_area_t>( DECORATION_AREA_RESIZE_TOP, border_geometry)); /* Resizing edges - bottom */ border_geometry = {0, height - border_size, width, border_size}; this->layout_areas.push_back(std::make_unique<decoration_area_t>( DECORATION_AREA_RESIZE_BOTTOM, border_geometry)); } /** * @return The decoration areas which need to be rendered, in top to bottom * order. */ std::vector<nonstd::observer_ptr<decoration_area_t>> decoration_layout_t:: get_renderable_areas() { std::vector<nonstd::observer_ptr<decoration_area_t>> renderable; for (auto& area : layout_areas) { if (area->get_type() & DECORATION_AREA_RENDERABLE_BIT) { renderable.push_back({area}); } } return renderable; } wf::region_t decoration_layout_t::calculate_region() const { wf::region_t r{}; for (auto& area : layout_areas) { r |= area->get_geometry(); } return r; } void decoration_layout_t::unset_hover(wf::point_t position) { auto area = find_area_at(position); if (area && (area->get_type() == DECORATION_AREA_BUTTON)) { area->as_button().set_hover(false); } } /** Handle motion event to (x, y) relative to the decoration */ void decoration_layout_t::handle_motion(int x, int y) { auto previous_area = find_area_at(current_input); auto current_area = find_area_at({x, y}); if (previous_area != current_area) { unset_hover(current_input); if (current_area && (current_area->get_type() == DECORATION_AREA_BUTTON)) { current_area->as_button().set_hover(true); } } this->current_input = {x, y}; update_cursor(); } /** * Handle press or release event. * @param pressed Whether the event is a press(true) or release(false) * event. * @return The action which needs to be carried out in response to this * event. * */ decoration_layout_t::action_response_t decoration_layout_t::handle_press_event( bool pressed) { if (pressed) { auto area = find_area_at(current_input); if (area && (area->get_type() & DECORATION_AREA_MOVE_BIT)) { return {DECORATION_ACTION_MOVE, 0}; } if (area && (area->get_type() & DECORATION_AREA_RESIZE_BIT)) { return {DECORATION_ACTION_RESIZE, calculate_resize_edges()}; } if (area && (area->get_type() == DECORATION_AREA_BUTTON)) { area->as_button().set_pressed(true); } is_grabbed = true; grab_origin = current_input; } if (!pressed && is_grabbed) { auto begin_area = find_area_at(grab_origin); auto end_area = find_area_at(current_input); if (begin_area && (begin_area->get_type() == DECORATION_AREA_BUTTON)) { begin_area->as_button().set_pressed(false); if (end_area && (begin_area == end_area)) { switch (begin_area->as_button().get_button_type()) { case BUTTON_CLOSE: return {DECORATION_ACTION_CLOSE, 0}; case BUTTON_TOGGLE_MAXIMIZE: return {DECORATION_ACTION_TOGGLE_MAXIMIZE, 0}; case BUTTON_MINIMIZE: return {DECORATION_ACTION_MINIMIZE, 0}; default: break; } } } } return {DECORATION_ACTION_NONE, 0}; } /** * Find the layout area at the given coordinates, if any * @return The layout area or null on failure */ nonstd::observer_ptr<decoration_area_t> decoration_layout_t::find_area_at( wf::point_t point) { for (auto& area : this->layout_areas) { if (area->get_geometry() & point) { return {area}; } } return nullptr; } /** Calculate resize edges based on @current_input */ uint32_t decoration_layout_t::calculate_resize_edges() const { uint32_t edges = 0; for (auto& area : layout_areas) { if (area->get_geometry() & this->current_input) { if (area->get_type() & DECORATION_AREA_RESIZE_BIT) { edges |= (area->get_type() & ~DECORATION_AREA_RESIZE_BIT); } } } return edges; } /** Update the cursor based on @current_input */ void decoration_layout_t::update_cursor() const { uint32_t edges = calculate_resize_edges(); auto cursor_name = edges > 0 ? wlr_xcursor_get_resize_name((wlr_edges)edges) : "default"; wf::get_core().set_cursor(cursor_name); } void decoration_layout_t::handle_focus_lost() { if (is_grabbed) { this->is_grabbed = false; auto area = find_area_at(grab_origin); if (area && (area->get_type() == DECORATION_AREA_BUTTON)) { area->as_button().set_pressed(false); } } this->unset_hover(current_input); } } }
#include <eosio/chain/webassembly/interface.hpp> #include <eosio/chain/apply_context.hpp> namespace eosio { namespace chain { namespace webassembly { void interface::require_auth( account_name account ) const { context.require_authorization( account ); } bool interface::has_auth( account_name account ) const { return context.has_authorization( account ); } void interface::require_auth2( account_name account, permission_name permission ) const { context.require_authorization( account, permission ); } void interface::require_recipient( account_name recipient ) { context.require_recipient( recipient ); } bool interface::is_account( account_name account ) const { return context.is_account( account ); } }}} // ns eosio::chain::webassembly
/* ///////////////////////////////////////////////////////////////////////// * File: test/scratch/test.scratch.util.onbailout/implicit_link.cpp * * Purpose: Implicit link file for the test.scratch.util.onbailout project. * * Created: 1st March 2008 * Updated: 21st September 2015 * * Status: Wizard-generated * * License: (Licensed under the Synesis Software Open License) * * Copyright (c) 2008-2015, Synesis Software Pty Ltd. * All rights reserved. * * www: http://www.synesis.com.au/software * * ////////////////////////////////////////////////////////////////////// */ /* Pantheios header files */ #include <platformstl/platformstl.h> #include <pantheios/implicit_link/core.h> #include <pantheios/implicit_link/fe.all.h> #include <pantheios/implicit_link/be.null.h> /* UNIXem header files */ #if defined(PLATFORMSTL_OS_IS_UNIX) && \ defined(_WIN32) # include <unixem/implicit_link.h> #endif /* Win32 || Win64 */ /* ///////////////////////////// end of file //////////////////////////// */
// dear imgui, v1.71 WIP // (drawing and font code) /* Index of this file: // [SECTION] STB libraries implementation // [SECTION] Style functions // [SECTION] ImDrawList // [SECTION] ImDrawListSplitter // [SECTION] ImDrawData // [SECTION] Helpers ShadeVertsXXX functions // [SECTION] ImFontConfig // [SECTION] ImFontAtlas // [SECTION] ImFontAtlas glyph ranges helpers // [SECTION] ImFontGlyphRangesBuilder // [SECTION] ImFont // [SECTION] Internal Render Helpers // [SECTION] Decompression code // [SECTION] Default font data (ProggyClean.ttf) */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #ifndef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS #endif #include "imgui_internal.h" #include <stdio.h> // vsnprintf, sscanf, printf #if !defined(alloca) #if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__) || defined(__SWITCH__) #include <alloca.h> // alloca (glibc uses <alloca.h>. Note that Cygwin may have _WIN32 defined, so the order matters here) #elif defined(_WIN32) #include <malloc.h> // alloca #if !defined(alloca) #define alloca _alloca // for clang with MS Codegen #endif #else #include <stdlib.h> // alloca #endif #endif // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" // warning : possible misuse of comma operator here // #endif #if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // #endif #if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. #endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #pragma GCC diagnostic ignored "-Wstack-protector" // warning: stack protector not protecting local variables: variable length buffer #if __GNUC__ >= 8 #pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif #endif //------------------------------------------------------------------------- // [SECTION] STB libraries implementation //------------------------------------------------------------------------- // Compile time options: //#define IMGUI_STB_NAMESPACE ImStb //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION #ifdef IMGUI_STB_NAMESPACE namespace IMGUI_STB_NAMESPACE { #endif #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration #endif #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wmissing-prototypes" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #pragma clang diagnostic ignored "-Wcast-qual" // warning : cast from 'const xxxx *' to 'xxx *' drops const qualifier // #endif #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers #endif #ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) #ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION #define STBRP_STATIC #define STBRP_ASSERT(x) IM_ASSERT(x) #define STBRP_SORT ImQsort #define STB_RECT_PACK_IMPLEMENTATION #endif #ifdef IMGUI_STB_RECT_PACK_FILENAME #include IMGUI_STB_RECT_PACK_FILENAME #else #include "imstb_rectpack.h" #endif #endif #ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) #ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION #define STBTT_malloc(x,u) ((void)(u), IM_ALLOC(x)) #define STBTT_free(x,u) ((void)(u), IM_FREE(x)) #define STBTT_assert(x) IM_ASSERT(x) #define STBTT_fmod(x,y) ImFmod(x,y) #define STBTT_sqrt(x) ImSqrt(x) #define STBTT_pow(x,y) ImPow(x,y) #define STBTT_fabs(x) ImFabs(x) #define STBTT_ifloor(x) ((int)ImFloorStd(x)) #define STBTT_iceil(x) ((int)ImCeil(x)) #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION #else #define STBTT_DEF extern #endif #ifdef IMGUI_STB_TRUETYPE_FILENAME #include IMGUI_STB_TRUETYPE_FILENAME #else #include "imstb_truetype.h" #endif #endif #if defined(__GNUC__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma clang diagnostic pop #endif #if defined(_MSC_VER) #pragma warning (pop) #endif #ifdef IMGUI_STB_NAMESPACE } // namespace ImStb using namespace IMGUI_STB_NAMESPACE; #endif //----------------------------------------------------------------------------- // [SECTION] Style functions //----------------------------------------------------------------------------- void ImGui::StyleColorsDark(ImGuiStyle* dst) { ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_Separator] = colors[ImGuiCol_Border]; colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); } void ImGui::StyleColorsClassic(ImGuiStyle* dst) { ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f); colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f); colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.69f, 0.40f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.42f, 0.41f, 0.64f, 0.69f); colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); colors[ImGuiCol_Button] = ImVec4(0.35f, 0.40f, 0.61f, 0.62f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.48f, 0.71f, 0.79f); colors[ImGuiCol_ButtonActive] = ImVec4(0.46f, 0.54f, 0.80f, 1.00f); colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.16f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f); colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); } // Those light colors are better suited with a thicker font than the default one + FrameBorder void ImGui::StyleColorsLight(ImGuiStyle* dst) { ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f); colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f); colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f); colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f); colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f); colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f); colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); } //----------------------------------------------------------------------------- // ImDrawList //----------------------------------------------------------------------------- ImDrawListSharedData::ImDrawListSharedData() { Font = NULL; FontSize = 0.0f; CurveTessellationTol = 0.0f; ClipRectFullscreen = ImVec4(-8192.0f, -8192.0f, +8192.0f, +8192.0f); InitialFlags = ImDrawListFlags_None; // Const data for (int i = 0; i < IM_ARRAYSIZE(CircleVtx12); i++) { const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(CircleVtx12); CircleVtx12[i] = ImVec2(ImCos(a), ImSin(a)); } } void ImDrawList::Clear() { CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); Flags = _Data->InitialFlags; _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.resize(0); _TextureIdStack.resize(0); _Path.resize(0); _Splitter.Clear(); } void ImDrawList::ClearFreeMemory() { CmdBuffer.clear(); IdxBuffer.clear(); VtxBuffer.clear(); _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.clear(); _TextureIdStack.clear(); _Path.clear(); _Splitter.ClearFreeMemory(); } ImDrawList* ImDrawList::CloneOutput() const { ImDrawList* dst = IM_NEW(ImDrawList(NULL)); dst->CmdBuffer = CmdBuffer; dst->IdxBuffer = IdxBuffer; dst->VtxBuffer = VtxBuffer; dst->Flags = Flags; return dst; } // Using macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug builds #define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : _Data->ClipRectFullscreen) #define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : (ImTextureID)NULL) void ImDrawList::AddDrawCmd() { ImDrawCmd draw_cmd; draw_cmd.ClipRect = GetCurrentClipRect(); draw_cmd.TextureId = GetCurrentTextureId(); draw_cmd.VtxOffset = _VtxCurrentOffset; draw_cmd.IdxOffset = IdxBuffer.Size; IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); CmdBuffer.push_back(draw_cmd); } void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) { AddDrawCmd(); current_cmd = &CmdBuffer.back(); } current_cmd->UserCallback = callback; current_cmd->UserCallbackData = callback_data; AddDrawCmd(); // Force a new command after us (see comment below) } // Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. // The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. void ImDrawList::UpdateClipRect() { // If current command is used with different settings we need to add a new command const ImVec4 curr_clip_rect = GetCurrentClipRect(); ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL; if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; } // Try to merge with previous command if it matches, else use current command ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) CmdBuffer.pop_back(); else curr_cmd->ClipRect = curr_clip_rect; } void ImDrawList::UpdateTextureID() { // If current command is used with different settings we need to add a new command const ImTextureID curr_texture_id = GetCurrentTextureId(); ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; } // Try to merge with previous command if it matches, else use current command ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; if (curr_cmd->ElemCount == 0 && prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) CmdBuffer.pop_back(); else curr_cmd->TextureId = curr_texture_id; } #undef GetCurrentClipRect #undef GetCurrentTextureId // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) { ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); if (intersect_with_current_clip_rect && _ClipRectStack.Size) { ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; if (cr.x < current.x) cr.x = current.x; if (cr.y < current.y) cr.y = current.y; if (cr.z > current.z) cr.z = current.z; if (cr.w > current.w) cr.w = current.w; } cr.z = ImMax(cr.x, cr.z); cr.w = ImMax(cr.y, cr.w); _ClipRectStack.push_back(cr); UpdateClipRect(); } void ImDrawList::PushClipRectFullScreen() { PushClipRect(ImVec2(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y), ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w)); } void ImDrawList::PopClipRect() { IM_ASSERT(_ClipRectStack.Size > 0); _ClipRectStack.pop_back(); UpdateClipRect(); } void ImDrawList::PushTextureID(ImTextureID texture_id) { _TextureIdStack.push_back(texture_id); UpdateTextureID(); } void ImDrawList::PopTextureID() { IM_ASSERT(_TextureIdStack.Size > 0); _TextureIdStack.pop_back(); UpdateTextureID(); } // NB: this can be called with negative count for removing primitives (as long as the result does not underflow) void ImDrawList::PrimReserve(int idx_count, int vtx_count) { // Large mesh support (when enabled) if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) { _VtxCurrentOffset = VtxBuffer.Size; _VtxCurrentIdx = 0; AddDrawCmd(); } ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; draw_cmd.ElemCount += idx_count; int vtx_buffer_old_size = VtxBuffer.Size; VtxBuffer.resize(vtx_buffer_old_size + vtx_count); _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size; int idx_buffer_old_size = IdxBuffer.Size; IdxBuffer.resize(idx_buffer_old_size + idx_count); _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size; } // Fully unrolled with inline call to keep our debug builds decently fast. void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) { ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel); ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; _VtxCurrentIdx += 4; _IdxWritePtr += 6; } void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) { ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; _VtxCurrentIdx += 4; _IdxWritePtr += 6; } void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; _VtxCurrentIdx += 4; _IdxWritePtr += 6; } // On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superflous function calls to optimize debug/non-inlined builds. // Those macros expects l-values. #define IM_NORMALIZE2F_OVER_ZERO(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = 1.0f / ImSqrt(d2); VX *= inv_len; VY *= inv_len; } } #define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 < 0.5f) d2 = 0.5f; float inv_lensq = 1.0f / d2; VX *= inv_lensq; VY *= inv_lensq; } // TODO: Thickness anti-aliased lines cap are missing their AA fringe. // We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness) { if (points_count < 2) return; const ImVec2 uv = _Data->TexUvWhitePixel; int count = points_count; if (!closed) count = points_count-1; const bool thick_line = thickness > 1.0f; if (Flags & ImDrawListFlags_AntiAliasedLines) { // Anti-aliased stroke const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; const int idx_count = thick_line ? count*18 : count*12; const int vtx_count = thick_line ? points_count*4 : points_count*3; PrimReserve(idx_count, vtx_count); // Temporary buffer ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; float dx = points[i2].x - points[i1].x; float dy = points[i2].y - points[i1].y; IM_NORMALIZE2F_OVER_ZERO(dx, dy); temp_normals[i1].x = dy; temp_normals[i1].y = -dx; } if (!closed) temp_normals[points_count-1] = temp_normals[points_count-2]; if (!thick_line) { if (!closed) { temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; } // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. unsigned int idx1 = _VtxCurrentIdx; for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; IM_FIXNORMAL2F(dm_x, dm_y) dm_x *= AA_SIZE; dm_y *= AA_SIZE; // Add temporary vertexes ImVec2* out_vtx = &temp_points[i2*2]; out_vtx[0].x = points[i2].x + dm_x; out_vtx[0].y = points[i2].y + dm_y; out_vtx[1].x = points[i2].x - dm_x; out_vtx[1].y = points[i2].y - dm_y; // Add indexes _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); _IdxWritePtr += 12; idx1 = idx2; } // Add vertexes for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; _VtxWritePtr += 3; } } else { const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; if (!closed) { temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); } // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. unsigned int idx1 = _VtxCurrentIdx; for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; IM_FIXNORMAL2F(dm_x, dm_y); float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE); float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE); float dm_in_x = dm_x * half_inner_thickness; float dm_in_y = dm_y * half_inner_thickness; // Add temporary vertexes ImVec2* out_vtx = &temp_points[i2*4]; out_vtx[0].x = points[i2].x + dm_out_x; out_vtx[0].y = points[i2].y + dm_out_y; out_vtx[1].x = points[i2].x + dm_in_x; out_vtx[1].y = points[i2].y + dm_in_y; out_vtx[2].x = points[i2].x - dm_in_x; out_vtx[2].y = points[i2].y - dm_in_y; out_vtx[3].x = points[i2].x - dm_out_x; out_vtx[3].y = points[i2].y - dm_out_y; // Add indexes _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); _IdxWritePtr += 18; idx1 = idx2; } // Add vertexes for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; _VtxWritePtr += 4; } } _VtxCurrentIdx += (ImDrawIdx)vtx_count; } else { // Non Anti-aliased Stroke const int idx_count = count*6; const int vtx_count = count*4; // FIXME-OPT: Not sharing edges PrimReserve(idx_count, vtx_count); for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; const ImVec2& p1 = points[i1]; const ImVec2& p2 = points[i2]; float dx = p2.x - p1.x; float dy = p2.y - p1.y; IM_NORMALIZE2F_OVER_ZERO(dx, dy); dx *= (thickness * 0.5f); dy *= (thickness * 0.5f); _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); _IdxWritePtr += 6; _VtxCurrentIdx += 4; } } } // We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col) { if (points_count < 3) return; const ImVec2 uv = _Data->TexUvWhitePixel; if (Flags & ImDrawListFlags_AntiAliasedFill) { // Anti-aliased Fill const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; const int idx_count = (points_count-2)*3 + points_count*6; const int vtx_count = (points_count*2); PrimReserve(idx_count, vtx_count); // Add indexes for fill unsigned int vtx_inner_idx = _VtxCurrentIdx; unsigned int vtx_outer_idx = _VtxCurrentIdx+1; for (int i = 2; i < points_count; i++) { _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); _IdxWritePtr += 3; } // Compute normals ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); //-V630 for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { const ImVec2& p0 = points[i0]; const ImVec2& p1 = points[i1]; float dx = p1.x - p0.x; float dy = p1.y - p0.y; IM_NORMALIZE2F_OVER_ZERO(dx, dy); temp_normals[i0].x = dy; temp_normals[i0].y = -dx; } for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { // Average normals const ImVec2& n0 = temp_normals[i0]; const ImVec2& n1 = temp_normals[i1]; float dm_x = (n0.x + n1.x) * 0.5f; float dm_y = (n0.y + n1.y) * 0.5f; IM_FIXNORMAL2F(dm_x, dm_y); dm_x *= AA_SIZE * 0.5f; dm_y *= AA_SIZE * 0.5f; // Add vertices _VtxWritePtr[0].pos.x = (points[i1].x - dm_x); _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner _VtxWritePtr[1].pos.x = (points[i1].x + dm_x); _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer _VtxWritePtr += 2; // Add indexes for fringes _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr += 6; } _VtxCurrentIdx += (ImDrawIdx)vtx_count; } else { // Non Anti-aliased Fill const int idx_count = (points_count-2)*3; const int vtx_count = points_count; PrimReserve(idx_count, vtx_count); for (int i = 0; i < vtx_count; i++) { _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; _VtxWritePtr++; } for (int i = 2; i < points_count; i++) { _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); _IdxWritePtr += 3; } _VtxCurrentIdx += (ImDrawIdx)vtx_count; } } void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12) { if (radius == 0.0f || a_min_of_12 > a_max_of_12) { _Path.push_back(centre); return; } _Path.reserve(_Path.Size + (a_max_of_12 - a_min_of_12 + 1)); for (int a = a_min_of_12; a <= a_max_of_12; a++) { const ImVec2& c = _Data->CircleVtx12[a % IM_ARRAYSIZE(_Data->CircleVtx12)]; _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); } } void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments) { if (radius == 0.0f) { _Path.push_back(centre); return; } // Note that we are adding a point at both a_min and a_max. // If you are trying to draw a full closed circle you don't want the overlapping points! _Path.reserve(_Path.Size + (num_segments + 1)); for (int i = 0; i <= num_segments; i++) { const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min); _Path.push_back(ImVec2(centre.x + ImCos(a) * radius, centre.y + ImSin(a) * radius)); } } static void PathBezierToCasteljau(ImVector<ImVec2>* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) { float dx = x4 - x1; float dy = y4 - y1; float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); d2 = (d2 >= 0) ? d2 : -d2; d3 = (d3 >= 0) ? d3 : -d3; if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) { path->push_back(ImVec2(x4, y4)); } else if (level < 10) { float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); } } void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) { ImVec2 p1 = _Path.back(); if (num_segments == 0) { // Auto-tessellated PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0); } else { float t_step = 1.0f / (float)num_segments; for (int i_step = 1; i_step <= num_segments; i_step++) { float t = t_step * i_step; float u = 1.0f - t; float w1 = u*u*u; float w2 = 3*u*u*t; float w3 = 3*u*t*t; float w4 = t*t*t; _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y)); } } } void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners) { rounding = ImMin(rounding, ImFabs(b.x - a.x) * ( ((rounding_corners & ImDrawCornerFlags_Top) == ImDrawCornerFlags_Top) || ((rounding_corners & ImDrawCornerFlags_Bot) == ImDrawCornerFlags_Bot) ? 0.5f : 1.0f ) - 1.0f); rounding = ImMin(rounding, ImFabs(b.y - a.y) * ( ((rounding_corners & ImDrawCornerFlags_Left) == ImDrawCornerFlags_Left) || ((rounding_corners & ImDrawCornerFlags_Right) == ImDrawCornerFlags_Right) ? 0.5f : 1.0f ) - 1.0f); if (rounding <= 0.0f || rounding_corners == 0) { PathLineTo(a); PathLineTo(ImVec2(b.x, a.y)); PathLineTo(b); PathLineTo(ImVec2(a.x, b.y)); } else { const float rounding_tl = (rounding_corners & ImDrawCornerFlags_TopLeft) ? rounding : 0.0f; const float rounding_tr = (rounding_corners & ImDrawCornerFlags_TopRight) ? rounding : 0.0f; const float rounding_br = (rounding_corners & ImDrawCornerFlags_BotRight) ? rounding : 0.0f; const float rounding_bl = (rounding_corners & ImDrawCornerFlags_BotLeft) ? rounding : 0.0f; PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9); PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12); PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3); PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6); } } void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(a + ImVec2(0.5f,0.5f)); PathLineTo(b + ImVec2(0.5f,0.5f)); PathStroke(col, false, thickness); } // a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly. void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; if (Flags & ImDrawListFlags_AntiAliasedLines) PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.50f,0.50f), rounding, rounding_corners_flags); else PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.49f,0.49f), rounding, rounding_corners_flags); // Better looking lower-right corner and rounded non-AA shapes. PathStroke(col, true, thickness); } void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags) { if ((col & IM_COL32_A_MASK) == 0) return; if (rounding > 0.0f) { PathRect(a, b, rounding, rounding_corners_flags); PathFillConvex(col); } else { PrimReserve(6, 4); PrimRect(a, b, col); } } void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) { if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0) return; const ImVec2 uv = _Data->TexUvWhitePixel; PrimReserve(6, 4); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); PrimWriteVtx(a, uv, col_upr_left); PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right); PrimWriteVtx(c, uv, col_bot_right); PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left); } void ImDrawList::AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(a); PathLineTo(b); PathLineTo(c); PathLineTo(d); PathStroke(col, true, thickness); } void ImDrawList::AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(a); PathLineTo(b); PathLineTo(c); PathLineTo(d); PathFillConvex(col); } void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(a); PathLineTo(b); PathLineTo(c); PathStroke(col, true, thickness); } void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(a); PathLineTo(b); PathLineTo(c); PathFillConvex(col); } void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness) { if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(centre, radius-0.5f, 0.0f, a_max, num_segments - 1); PathStroke(col, true, thickness); } void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) { if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(centre, radius, 0.0f, a_max, num_segments - 1); PathFillConvex(col); } void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(pos0); PathBezierCurveTo(cp0, cp1, pos1, num_segments); PathStroke(col, false, thickness); } void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) { if ((col & IM_COL32_A_MASK) == 0) return; if (text_end == NULL) text_end = text_begin + strlen(text_begin); if (text_begin == text_end) return; // Pull default font/size from the shared ImDrawListSharedData instance if (font == NULL) font = _Data->Font; if (font_size == 0.0f) font_size = _Data->FontSize; IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. ImVec4 clip_rect = _ClipRectStack.back(); if (cpu_fine_clip_rect) { clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); } font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL); } void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) { AddText(NULL, 0.0f, pos, col, text_begin, text_end); } void ImDrawList::AddTextVertical(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, bool rotateCCW, const char* text_end , float wrap_width, const ImVec4* cpu_fine_clip_rect) { if ((col >> 24) == 0) return; if (text_end == NULL) text_end = text_begin + strlen(text_begin); if (text_begin == text_end) return; // Note: This is one of the few instance of breaking the encapsulation of ImDrawList, as we pull this from ImGui state, but it is just SO useful. // Might just move Font/FontSize to ImDrawList? if (font == NULL) font = GImGui->Font; if (font_size == 0.0f) font_size = GImGui->FontSize; //IM_ASSERT(drawList && font->ContainerAtlas->TexID == drawList->_TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); ImVec4 clip_rect = _ClipRectStack.back(); if (cpu_fine_clip_rect) { clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); } font->RenderTextVertical(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL, rotateCCW); } void ImDrawList::AddTextVertical(const ImVec2& pos, ImU32 col, const char* text_begin, bool rotateCCW,const char* text_end) { AddTextVertical(NULL, 0.0f, pos, col, text_begin, rotateCCW, text_end); } void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); if (push_texture_id) PushTextureID(user_texture_id); PrimReserve(6, 4); PrimRectUV(a, b, uv_a, uv_b, col); if (push_texture_id) PopTextureID(); } void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); if (push_texture_id) PushTextureID(user_texture_id); PrimReserve(6, 4); PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col); if (push_texture_id) PopTextureID(); } void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners) { if ((col & IM_COL32_A_MASK) == 0) return; if (rounding <= 0.0f || (rounding_corners & ImDrawCornerFlags_All) == 0) { AddImage(user_texture_id, a, b, uv_a, uv_b, col); return; } const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); if (push_texture_id) PushTextureID(user_texture_id); int vert_start_idx = VtxBuffer.Size; PathRect(a, b, rounding, rounding_corners); PathFillConvex(col); int vert_end_idx = VtxBuffer.Size; ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, a, b, uv_a, uv_b, true); if (push_texture_id) PopTextureID(); } //----------------------------------------------------------------------------- // ImDrawListSplitter //----------------------------------------------------------------------------- // FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. //----------------------------------------------------------------------------- void ImDrawListSplitter::ClearFreeMemory() { for (int i = 0; i < _Channels.Size; i++) { if (i == _Current) memset(&_Channels[i], 0, sizeof(_Channels[i])); // Current channel is a copy of CmdBuffer/IdxBuffer, don't destruct again _Channels[i].CmdBuffer.clear(); _Channels[i].IdxBuffer.clear(); } _Current = 0; _Count = 1; _Channels.clear(); } void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) { IM_ASSERT(_Current == 0 && _Count <= 1); int old_channels_count = _Channels.Size; if (old_channels_count < channels_count) _Channels.resize(channels_count); _Count = channels_count; // Channels[] (24/32 bytes each) hold storage that we'll swap with draw_list->_CmdBuffer/_IdxBuffer // The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. // When we switch to the next channel, we'll copy draw_list->_CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list->CmdBuffer/_IdxBuffer memset(&_Channels[0], 0, sizeof(ImDrawChannel)); for (int i = 1; i < channels_count; i++) { if (i >= old_channels_count) { IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); } else { _Channels[i].CmdBuffer.resize(0); _Channels[i].IdxBuffer.resize(0); } if (_Channels[i].CmdBuffer.Size == 0) { ImDrawCmd draw_cmd; draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); draw_cmd.TextureId = draw_list->_TextureIdStack.back(); _Channels[i].CmdBuffer.push_back(draw_cmd); } } } static inline bool CanMergeDrawCommands(ImDrawCmd* a, ImDrawCmd* b) { return memcmp(&a->ClipRect, &b->ClipRect, sizeof(a->ClipRect)) == 0 && a->TextureId == b->TextureId && !a->UserCallback && !b->UserCallback; } void ImDrawListSplitter::Merge(ImDrawList* draw_list) { // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. if (_Count <= 1) return; SetCurrentChannel(draw_list, 0); if (draw_list->CmdBuffer.Size != 0 && draw_list->CmdBuffer.back().ElemCount == 0) draw_list->CmdBuffer.pop_back(); // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; int new_idx_buffer_count = 0; ImDrawCmd* last_cmd = (_Count > 0 && _Channels[0].CmdBuffer.Size > 0) ? &_Channels[0].CmdBuffer.back() : NULL; int idx_offset = last_cmd ? last_cmd->IdxOffset + last_cmd->ElemCount : 0; for (int i = 1; i < _Count; i++) { ImDrawChannel& ch = _Channels[i]; if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) ch.CmdBuffer.pop_back(); else if (ch.CmdBuffer.Size > 0 && last_cmd != NULL && CanMergeDrawCommands(last_cmd, &ch.CmdBuffer[0])) { // Merge previous channel last draw command with current channel first draw command if matching. last_cmd->ElemCount += ch.CmdBuffer[0].ElemCount; ch.CmdBuffer.erase(ch.CmdBuffer.Data); } if (ch.CmdBuffer.Size > 0) last_cmd = &ch.CmdBuffer.back(); new_cmd_buffer_count += ch.CmdBuffer.Size; new_idx_buffer_count += ch.IdxBuffer.Size; for (int cmd_n = 0; cmd_n < ch.CmdBuffer.Size; cmd_n++) { ch.CmdBuffer.Data[cmd_n].IdxOffset = idx_offset; idx_offset += ch.CmdBuffer.Data[cmd_n].ElemCount; } } draw_list->CmdBuffer.resize(draw_list->CmdBuffer.Size + new_cmd_buffer_count); draw_list->IdxBuffer.resize(draw_list->IdxBuffer.Size + new_idx_buffer_count); // Write commands and indices in order (they are fairly small structures, we don't copy vertices only indices) ImDrawCmd* cmd_write = draw_list->CmdBuffer.Data + draw_list->CmdBuffer.Size - new_cmd_buffer_count; ImDrawIdx* idx_write = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size - new_idx_buffer_count; for (int i = 1; i < _Count; i++) { ImDrawChannel& ch = _Channels[i]; if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } if (int sz = ch.IdxBuffer.Size) { memcpy(idx_write, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } } draw_list->_IdxWritePtr = idx_write; draw_list->UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. _Count = 1; } void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) { IM_ASSERT(idx < _Count); if (_Current == idx) return; // Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap() memcpy(&_Channels.Data[_Current].CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer)); memcpy(&_Channels.Data[_Current].IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer)); _Current = idx; memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx].CmdBuffer, sizeof(draw_list->CmdBuffer)); memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx].IdxBuffer, sizeof(draw_list->IdxBuffer)); draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size; } //----------------------------------------------------------------------------- // [SECTION] ImDrawData //----------------------------------------------------------------------------- // For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! void ImDrawData::DeIndexAllBuffers() { ImVector<ImDrawVert> new_vtx_buffer; TotalVtxCount = TotalIdxCount = 0; for (int i = 0; i < CmdListsCount; i++) { ImDrawList* cmd_list = CmdLists[i]; if (cmd_list->IdxBuffer.empty()) continue; new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; cmd_list->VtxBuffer.swap(new_vtx_buffer); cmd_list->IdxBuffer.resize(0); TotalVtxCount += cmd_list->VtxBuffer.Size; } } // Helper to scale the ClipRect field of each ImDrawCmd. // Use if your final output buffer is at a different scale than draw_data->DisplaySize, // or if there is a difference between your window resolution and framebuffer resolution. void ImDrawData::ScaleClipRects(const ImVec2& fb_scale) { for (int i = 0; i < CmdListsCount; i++) { ImDrawList* cmd_list = CmdLists[i]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i]; cmd->ClipRect = ImVec4(cmd->ClipRect.x * fb_scale.x, cmd->ClipRect.y * fb_scale.y, cmd->ClipRect.z * fb_scale.x, cmd->ClipRect.w * fb_scale.y); } } } //----------------------------------------------------------------------------- // [SECTION] Helpers ShadeVertsXXX functions //----------------------------------------------------------------------------- // Generic linear color gradient, write to RGB fields, leave A untouched. void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1) { ImVec2 gradient_extent = gradient_p1 - gradient_p0; float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; for (ImDrawVert* vert = vert_start; vert < vert_end; vert++) { float d = ImDot(vert->pos - gradient_p0, gradient_extent); float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t); int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t); int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t); vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK); } } // Distribute UV over (a, b) rectangle void ImGui::ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp) { const ImVec2 size = b - a; const ImVec2 uv_size = uv_b - uv_a; const ImVec2 scale = ImVec2( size.x != 0.0f ? (uv_size.x / size.x) : 0.0f, size.y != 0.0f ? (uv_size.y / size.y) : 0.0f); ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; if (clamp) { const ImVec2 min = ImMin(uv_a, uv_b); const ImVec2 max = ImMax(uv_a, uv_b); for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max); } else { for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale); } } //----------------------------------------------------------------------------- // [SECTION] ImFontConfig //----------------------------------------------------------------------------- ImFontConfig::ImFontConfig() { FontData = NULL; FontDataSize = 0; FontDataOwnedByAtlas = true; FontNo = 0; SizePixels = 0.0f; OversampleH = 3; // FIXME: 2 may be a better default? OversampleV = 1; PixelSnapH = false; GlyphExtraSpacing = ImVec2(0.0f, 0.0f); GlyphOffset = ImVec2(0.0f, 0.0f); GlyphRanges = NULL; GlyphMinAdvanceX = 0.0f; GlyphMaxAdvanceX = FLT_MAX; MergeMode = false; RasterizerFlags = 0x00; RasterizerMultiply = 1.0f; memset(Name, 0, sizeof(Name)); DstFont = NULL; } //----------------------------------------------------------------------------- // [SECTION] ImFontAtlas //----------------------------------------------------------------------------- // A work of art lies ahead! (. = white layer, X = black layer, others are blank) // The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. const int FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 108; const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000; static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = { "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX " "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X " "--- -XXX.XXX- X...X - X...X -X....X - X....X- X..X " "X - X.X - X.....X - X.....X -X...X - X...X- X..X " "XX - X.X -X.......X- X.......X -X..X.X - X.X..X- X..X " "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X- X..XXX " "X..X - X.X - X.X - X.X -XX X.X - X.X XX- X..X..XXX " "X...X - X.X - X.X - XX X.X XX - X.X - X.X - X..X..X..XX " "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X - X..X..X..X.X " "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X -XXX X..X..X..X..X" "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X -X..XX........X..X" "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X -X...X...........X" "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X - X..............X" "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X - X.............X" "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X - X.............X" "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X - X............X" "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX - X...........X " "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------- X..........X " "X.X X..X - -X.......X- X.......X - XX XX - - X..........X " "XX X..X - - X.....X - X.....X - X.X X.X - - X........X " " X..X - X...X - X...X - X..X X..X - - X........X " " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - - XXXXXXXXXX " "------------ - X - X -X.....................X- ------------------" " ----------------------------------- X...XXXXXXXXXXXXX...X - " " - X..X X..X - " " - X.X X.X - " " - XX XX - " }; static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3] = { // Pos ........ Size ......... Offset ...... { ImVec2( 0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow { ImVec2(13,0), ImVec2( 7,16), ImVec2( 1, 8) }, // ImGuiMouseCursor_TextInput { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_ResizeAll { ImVec2(21,0), ImVec2( 9,23), ImVec2( 4,11) }, // ImGuiMouseCursor_ResizeNS { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 4) }, // ImGuiMouseCursor_ResizeEW { ImVec2(73,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNESW { ImVec2(55,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNWSE { ImVec2(91,0), ImVec2(17,22), ImVec2( 5, 0) }, // ImGuiMouseCursor_Hand }; ImFontAtlas::ImFontAtlas() { Locked = false; Flags = ImFontAtlasFlags_None; TexID = (ImTextureID)NULL; TexDesiredWidth = 0; TexGlyphPadding = 1; TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; TexWidth = TexHeight = 0; TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) CustomRectIds[n] = -1; } ImFontAtlas::~ImFontAtlas() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); Clear(); } void ImFontAtlas::ClearInputData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); for (int i = 0; i < ConfigData.Size; i++) if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) { IM_FREE(ConfigData[i].FontData); ConfigData[i].FontData = NULL; } // When clearing this we lose access to the font name and other information used to build the font. for (int i = 0; i < Fonts.Size; i++) if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) { Fonts[i]->ConfigData = NULL; Fonts[i]->ConfigDataCount = 0; } ConfigData.clear(); CustomRects.clear(); for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) CustomRectIds[n] = -1; } void ImFontAtlas::ClearTexData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); if (TexPixelsAlpha8) IM_FREE(TexPixelsAlpha8); if (TexPixelsRGBA32) IM_FREE(TexPixelsRGBA32); TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; } void ImFontAtlas::ClearFonts() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); for (int i = 0; i < Fonts.Size; i++) IM_DELETE(Fonts[i]); Fonts.clear(); } void ImFontAtlas::Clear() { ClearInputData(); ClearTexData(); ClearFonts(); } void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) { // Build atlas on demand if (TexPixelsAlpha8 == NULL) { if (ConfigData.empty()) AddFontDefault(); Build(); } *out_pixels = TexPixelsAlpha8; if (out_width) *out_width = TexWidth; if (out_height) *out_height = TexHeight; if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; } void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) { // Convert to RGBA32 format on demand // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp if (!TexPixelsRGBA32) { unsigned char* pixels = NULL; GetTexDataAsAlpha8(&pixels, NULL, NULL); if (pixels) { TexPixelsRGBA32 = (unsigned int*)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4); const unsigned char* src = pixels; unsigned int* dst = TexPixelsRGBA32; for (int n = TexWidth * TexHeight; n > 0; n--) *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++)); } } *out_pixels = (unsigned char*)TexPixelsRGBA32; if (out_width) *out_width = TexWidth; if (out_height) *out_height = TexHeight; if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; } ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); IM_ASSERT(font_cfg->SizePixels > 0.0f); // Create new font if (!font_cfg->MergeMode) Fonts.push_back(IM_NEW(ImFont)); else IM_ASSERT(!Fonts.empty() && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. ConfigData.push_back(*font_cfg); ImFontConfig& new_font_cfg = ConfigData.back(); if (new_font_cfg.DstFont == NULL) new_font_cfg.DstFont = Fonts.back(); if (!new_font_cfg.FontDataOwnedByAtlas) { new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize); new_font_cfg.FontDataOwnedByAtlas = true; memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); } // Invalidate texture ClearTexData(); return new_font_cfg.DstFont; } // Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder) static unsigned int stb_decompress_length(const unsigned char *input); static unsigned int stb_decompress(unsigned char *output, const unsigned char *input, unsigned int length); static const char* GetDefaultCompressedFontDataTTFBase85(); static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } static void Decode85(const unsigned char* src, unsigned char* dst) { while (*src) { unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. src += 5; dst += 4; } } // Load embedded ProggyClean.ttf at size 13, disable oversampling ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) { ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); if (!font_cfg_template) { font_cfg.OversampleH = font_cfg.OversampleV = 1; font_cfg.PixelSnapH = true; } if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f * 1.0f; if (font_cfg.Name[0] == '\0') ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels); const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault(); ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges); font->DisplayOffset.y = 1.0f; return font; } ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); size_t data_size = 0; void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0); if (!data) { IM_ASSERT(0); // Could not load file. return NULL; } ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); if (font_cfg.Name[0] == '\0') { // Store a short copy of filename into into the font name for convenience const char* p; for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels); } return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); } // NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); IM_ASSERT(font_cfg.FontData == NULL); font_cfg.FontData = ttf_data; font_cfg.FontDataSize = ttf_size; font_cfg.SizePixels = size_pixels; if (glyph_ranges) font_cfg.GlyphRanges = glyph_ranges; return AddFont(&font_cfg); } ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data); unsigned char* buf_decompressed_data = (unsigned char *)IM_ALLOC(buf_decompressed_size); stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); IM_ASSERT(font_cfg.FontData == NULL); font_cfg.FontDataOwnedByAtlas = true; return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); } ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) { int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size); Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); IM_FREE(compressed_ttf); return font; } int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) { IM_ASSERT(id >= 0x10000); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); CustomRect r; r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; CustomRects.push_back(r); return CustomRects.Size - 1; // Return index } int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset) { IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); CustomRect r; r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; r.GlyphAdvanceX = advance_x; r.GlyphOffset = offset; r.Font = font; CustomRects.push_back(r); return CustomRects.Size - 1; // Return index } void ImFontAtlas::CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) { IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y); *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y); } bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) { if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT) return false; if (Flags & ImFontAtlasFlags_NoMouseCursors) return false; IM_ASSERT(CustomRectIds[0] != -1); ImFontAtlas::CustomRect& r = CustomRects[CustomRectIds[0]]; IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y); ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; *out_size = size; *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; out_uv_border[0] = (pos) * TexUvScale; out_uv_border[1] = (pos + size) * TexUvScale; pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; out_uv_fill[0] = (pos) * TexUvScale; out_uv_fill[1] = (pos + size) * TexUvScale; return true; } bool ImFontAtlas::Build() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); return ImFontAtlasBuildWithStbTruetype(this); } void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor) { for (unsigned int i = 0; i < 256; i++) { unsigned int value = (unsigned int)(i * in_brighten_factor); out_table[i] = value > 255 ? 255 : (value & 0xFF); } } void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride) { unsigned char* data = pixels + x + y * stride; for (int j = h; j > 0; j--, data += stride) for (int i = 0; i < w; i++) data[i] = table[data[i]]; } // Temporary data for one source font (multiple source fonts can be merged into one destination ImFont) // (C++03 doesn't allow instancing ImVector<> with function-local types so we declare the type here.) struct ImFontBuildSrcData { stbtt_fontinfo FontInfo; stbtt_pack_range PackRange; // Hold the list of codepoints to pack (essentially points to Codepoints.Data) stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position. stbtt_packedchar* PackedChars; // Output glyphs const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF) int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[] int GlyphsHighest; // Highest requested codepoint int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font) ImBoolVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB) ImVector<int> GlyphsList; // Glyph codepoints list (flattened version of GlyphsMap) }; // Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont) struct ImFontBuildDstData { int SrcCount; // Number of source fonts targeting this destination font. int GlyphsHighest; int GlyphsCount; ImBoolVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font. }; static void UnpackBoolVectorToFlatIndexList(const ImBoolVector* in, ImVector<int>* out) { IM_ASSERT(sizeof(in->Storage.Data[0]) == sizeof(int)); const int* it_begin = in->Storage.begin(); const int* it_end = in->Storage.end(); for (const int* it = it_begin; it < it_end; it++) if (int entries_32 = *it) for (int bit_n = 0; bit_n < 32; bit_n++) if (entries_32 & (1u << bit_n)) out->push_back((int)((it - it_begin) << 5) + bit_n); } bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) { IM_ASSERT(atlas->ConfigData.Size > 0); ImFontAtlasBuildRegisterDefaultCustomRects(atlas); // Clear atlas atlas->TexID = (ImTextureID)NULL; atlas->TexWidth = atlas->TexHeight = 0; atlas->TexUvScale = ImVec2(0.0f, 0.0f); atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); atlas->ClearTexData(); // Temporary storage for building ImVector<ImFontBuildSrcData> src_tmp_array; ImVector<ImFontBuildDstData> dst_tmp_array; src_tmp_array.resize(atlas->ConfigData.Size); dst_tmp_array.resize(atlas->Fonts.Size); memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); memset(dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes()); // 1. Initialize font loading structure, check font data validity for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++) { ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; ImFontConfig& cfg = atlas->ConfigData[src_i]; IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas)); // Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) src_tmp.DstIndex = -1; for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++) if (cfg.DstFont == atlas->Fonts[output_i]) src_tmp.DstIndex = output_i; IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array? if (src_tmp.DstIndex == -1) return false; // Initialize helper structure for font loading and verify that the TTF/OTF data is correct const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) return false; // Measure highest codepoints ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault(); for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]); dst_tmp.SrcCount++; dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest); } // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs. int total_glyphs_count = 0; for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) { ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; src_tmp.GlyphsSet.Resize(src_tmp.GlyphsHighest + 1); if (dst_tmp.GlyphsSet.Storage.empty()) dst_tmp.GlyphsSet.Resize(dst_tmp.GlyphsHighest + 1); for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) for (int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++) { if (dst_tmp.GlyphsSet.GetBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true) continue; if (!stbtt_FindGlyphIndex(&src_tmp.FontInfo, codepoint)) // It is actually in the font? continue; // Add to avail set/counters src_tmp.GlyphsCount++; dst_tmp.GlyphsCount++; src_tmp.GlyphsSet.SetBit(codepoint, true); dst_tmp.GlyphsSet.SetBit(codepoint, true); total_glyphs_count++; } } // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another) for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) { ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount); UnpackBoolVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList); src_tmp.GlyphsSet.Clear(); IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount); } for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++) dst_tmp_array[dst_i].GlyphsSet.Clear(); dst_tmp_array.clear(); // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity) ImVector<stbrp_rect> buf_rects; ImVector<stbtt_packedchar> buf_packedchars; buf_rects.resize(total_glyphs_count); buf_packedchars.resize(total_glyphs_count); memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes()); memset(buf_packedchars.Data, 0, (size_t)buf_packedchars.size_in_bytes()); // 4. Gather glyphs sizes so we can pack them in our virtual canvas. int total_surface = 0; int buf_rects_out_n = 0; int buf_packedchars_out_n = 0; for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) { ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; if (src_tmp.GlyphsCount == 0) continue; src_tmp.Rects = &buf_rects[buf_rects_out_n]; src_tmp.PackedChars = &buf_packedchars[buf_packedchars_out_n]; buf_rects_out_n += src_tmp.GlyphsCount; buf_packedchars_out_n += src_tmp.GlyphsCount; // Convert our ranges in the format stb_truetype wants ImFontConfig& cfg = atlas->ConfigData[src_i]; src_tmp.PackRange.font_size = cfg.SizePixels; src_tmp.PackRange.first_unicode_codepoint_in_range = 0; src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data; src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size; src_tmp.PackRange.chardata_for_range = src_tmp.PackedChars; src_tmp.PackRange.h_oversample = (unsigned char)cfg.OversampleH; src_tmp.PackRange.v_oversample = (unsigned char)cfg.OversampleV; // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects) const float scale = (cfg.SizePixels > 0) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels); const int padding = atlas->TexGlyphPadding; for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) { int x0, y0, x1, y1; const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]); IM_ASSERT(glyph_index_in_font != 0); stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * cfg.OversampleH, scale * cfg.OversampleV, 0, 0, &x0, &y0, &x1, &y1); src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + padding + cfg.OversampleH - 1); src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + padding + cfg.OversampleV - 1); total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h; } } // We need a width for the skyline algorithm, any width! // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height. // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface. const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1; atlas->TexHeight = 0; if (atlas->TexDesiredWidth > 0) atlas->TexWidth = atlas->TexDesiredWidth; else atlas->TexWidth = (surface_sqrt >= 4096*0.7f) ? 4096 : (surface_sqrt >= 2048*0.7f) ? 2048 : (surface_sqrt >= 1024*0.7f) ? 1024 : 512; // 5. Start packing // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). const int TEX_HEIGHT_MAX = 1024 * 32; stbtt_pack_context spc = {}; stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, atlas->TexGlyphPadding, NULL); ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info); // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) { ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; if (src_tmp.GlyphsCount == 0) continue; stbrp_pack_rects((stbrp_context*)spc.pack_info, src_tmp.Rects, src_tmp.GlyphsCount); // Extend texture height and mark missing glyphs as non-packed so we won't render them. // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?) for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) if (src_tmp.Rects[glyph_i].was_packed) atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h); } // 7. Allocate texture atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight); memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); spc.pixels = atlas->TexPixelsAlpha8; spc.height = atlas->TexHeight; // 8. Render/rasterize font characters into the texture for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) { ImFontConfig& cfg = atlas->ConfigData[src_i]; ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; if (src_tmp.GlyphsCount == 0) continue; stbtt_PackFontRangesRenderIntoRects(&spc, &src_tmp.FontInfo, &src_tmp.PackRange, 1, src_tmp.Rects); // Apply multiply operator if (cfg.RasterizerMultiply != 1.0f) { unsigned char multiply_table[256]; ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply); stbrp_rect* r = &src_tmp.Rects[0]; for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++, r++) if (r->was_packed) ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, atlas->TexPixelsAlpha8, r->x, r->y, r->w, r->h, atlas->TexWidth * 1); } src_tmp.Rects = NULL; } // End packing stbtt_PackEnd(&spc); buf_rects.clear(); // 9. Setup ImFont and glyphs for runtime for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) { ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; if (src_tmp.GlyphsCount == 0) continue; ImFontConfig& cfg = atlas->ConfigData[src_i]; ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels); int unscaled_ascent, unscaled_descent, unscaled_line_gap; stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); const float ascent = ImFloor(unscaled_ascent * font_scale + ((unscaled_ascent > 0.0f) ? +1 : -1)); const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1)); ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent); const float font_off_x = cfg.GlyphOffset.x; const float font_off_y = cfg.GlyphOffset.y + (float)(int)(dst_font->Ascent + 0.5f); for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) { const int codepoint = src_tmp.GlyphsList[glyph_i]; const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i]; const float char_advance_x_org = pc.xadvance; const float char_advance_x_mod = ImClamp(char_advance_x_org, cfg.GlyphMinAdvanceX, cfg.GlyphMaxAdvanceX); float char_off_x = font_off_x; if (char_advance_x_org != char_advance_x_mod) char_off_x += cfg.PixelSnapH ? (float)(int)((char_advance_x_mod - char_advance_x_org) * 0.5f) : (char_advance_x_mod - char_advance_x_org) * 0.5f; // Register glyph stbtt_aligned_quad q; float dummy_x = 0.0f, dummy_y = 0.0f; stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &dummy_x, &dummy_y, &q, 0); dst_font->AddGlyph((ImWchar)codepoint, q.x0 + char_off_x, q.y0 + font_off_y, q.x1 + char_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, char_advance_x_mod); } } // Cleanup temporary (ImVector doesn't honor destructor) for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) src_tmp_array[src_i].~ImFontBuildSrcData(); ImFontAtlasBuildFinish(atlas); return true; } void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas) { if (atlas->CustomRectIds[0] >= 0) return; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); else atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, 2, 2); } void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) { if (!font_config->MergeMode) { font->ClearOutputData(); font->FontSize = font_config->SizePixels; font->ConfigData = font_config; font->ContainerAtlas = atlas; font->Ascent = ascent; font->Descent = descent; } font->ConfigDataCount++; } void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque) { stbrp_context* pack_context = (stbrp_context*)stbrp_context_opaque; IM_ASSERT(pack_context != NULL); ImVector<ImFontAtlas::CustomRect>& user_rects = atlas->CustomRects; IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong. ImVector<stbrp_rect> pack_rects; pack_rects.resize(user_rects.Size); memset(pack_rects.Data, 0, (size_t)pack_rects.size_in_bytes()); for (int i = 0; i < user_rects.Size; i++) { pack_rects[i].w = user_rects[i].Width; pack_rects[i].h = user_rects[i].Height; } stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size); for (int i = 0; i < pack_rects.Size; i++) if (pack_rects[i].was_packed) { user_rects[i].X = pack_rects[i].x; user_rects[i].Y = pack_rects[i].y; IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height); atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h); } } static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) { IM_ASSERT(atlas->CustomRectIds[0] >= 0); IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); IM_ASSERT(r.IsPacked()); const int w = atlas->TexWidth; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) { // Render/copy pixels IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++) for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++) { const int offset0 = (int)(r.X + x) + (int)(r.Y + y) * w; const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00; atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00; } } else { IM_ASSERT(r.Width == 2 && r.Height == 2); const int offset = (int)(r.X) + (int)(r.Y) * w; atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF; } atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * atlas->TexUvScale.x, (r.Y + 0.5f) * atlas->TexUvScale.y); } void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { // Render into our custom data block ImFontAtlasBuildRenderDefaultTexData(atlas); // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) { const ImFontAtlas::CustomRect& r = atlas->CustomRects[i]; if (r.Font == NULL || r.ID > 0x10000) continue; IM_ASSERT(r.Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; atlas->CalcCustomRectUV(&r, &uv0, &uv1); r.Font->AddGlyph((ImWchar)r.ID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width, r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX); } // Build all fonts lookup tables for (int i = 0; i < atlas->Fonts.Size; i++) if (atlas->Fonts[i]->DirtyLookupTables) atlas->Fonts[i]->BuildLookupTable(); } // Retrieve list of range (2 int per range, values are inclusive) const ImWchar* ImFontAtlas::GetGlyphRangesDefault() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesKorean() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3131, 0x3163, // Korean alphabets 0xAC00, 0xD79D, // Korean characters 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesChineseFull() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x2000, 0x206F, // General Punctuation 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana 0x31F0, 0x31FF, // Katakana Phonetic Extensions 0xFF00, 0xFFEF, // Half-width characters 0x4e00, 0x9FAF, // CJK Ideograms 0, }; return &ranges[0]; } static void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short* accumulative_offsets, int accumulative_offsets_count, ImWchar* out_ranges) { for (int n = 0; n < accumulative_offsets_count; n++, out_ranges += 2) { out_ranges[0] = out_ranges[1] = (ImWchar)(base_codepoint + accumulative_offsets[n]); base_codepoint += accumulative_offsets[n]; } out_ranges[0] = 0; } //------------------------------------------------------------------------- // [SECTION] ImFontAtlas glyph ranges helpers //------------------------------------------------------------------------- const ImWchar* ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon() { // Store 2500 regularly used characters for Simplified Chinese. // Sourced from https://zh.wiktionary.org/wiki/%E9%99%84%E5%BD%95:%E7%8E%B0%E4%BB%A3%E6%B1%89%E8%AF%AD%E5%B8%B8%E7%94%A8%E5%AD%97%E8%A1%A8 // This table covers 97.97% of all characters used during the month in July, 1987. // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) static const short accumulative_offsets_from_0x4E00[] = { 0,1,2,4,1,1,1,1,2,1,3,2,1,2,2,1,1,1,1,1,5,2,1,2,3,3,3,2,2,4,1,1,1,2,1,5,2,3,1,2,1,2,1,1,2,1,1,2,2,1,4,1,1,1,1,5,10,1,2,19,2,1,2,1,2,1,2,1,2, 1,5,1,6,3,2,1,2,2,1,1,1,4,8,5,1,1,4,1,1,3,1,2,1,5,1,2,1,1,1,10,1,1,5,2,4,6,1,4,2,2,2,12,2,1,1,6,1,1,1,4,1,1,4,6,5,1,4,2,2,4,10,7,1,1,4,2,4, 2,1,4,3,6,10,12,5,7,2,14,2,9,1,1,6,7,10,4,7,13,1,5,4,8,4,1,1,2,28,5,6,1,1,5,2,5,20,2,2,9,8,11,2,9,17,1,8,6,8,27,4,6,9,20,11,27,6,68,2,2,1,1, 1,2,1,2,2,7,6,11,3,3,1,1,3,1,2,1,1,1,1,1,3,1,1,8,3,4,1,5,7,2,1,4,4,8,4,2,1,2,1,1,4,5,6,3,6,2,12,3,1,3,9,2,4,3,4,1,5,3,3,1,3,7,1,5,1,1,1,1,2, 3,4,5,2,3,2,6,1,1,2,1,7,1,7,3,4,5,15,2,2,1,5,3,22,19,2,1,1,1,1,2,5,1,1,1,6,1,1,12,8,2,9,18,22,4,1,1,5,1,16,1,2,7,10,15,1,1,6,2,4,1,2,4,1,6, 1,1,3,2,4,1,6,4,5,1,2,1,1,2,1,10,3,1,3,2,1,9,3,2,5,7,2,19,4,3,6,1,1,1,1,1,4,3,2,1,1,1,2,5,3,1,1,1,2,2,1,1,2,1,1,2,1,3,1,1,1,3,7,1,4,1,1,2,1, 1,2,1,2,4,4,3,8,1,1,1,2,1,3,5,1,3,1,3,4,6,2,2,14,4,6,6,11,9,1,15,3,1,28,5,2,5,5,3,1,3,4,5,4,6,14,3,2,3,5,21,2,7,20,10,1,2,19,2,4,28,28,2,3, 2,1,14,4,1,26,28,42,12,40,3,52,79,5,14,17,3,2,2,11,3,4,6,3,1,8,2,23,4,5,8,10,4,2,7,3,5,1,1,6,3,1,2,2,2,5,28,1,1,7,7,20,5,3,29,3,17,26,1,8,4, 27,3,6,11,23,5,3,4,6,13,24,16,6,5,10,25,35,7,3,2,3,3,14,3,6,2,6,1,4,2,3,8,2,1,1,3,3,3,4,1,1,13,2,2,4,5,2,1,14,14,1,2,2,1,4,5,2,3,1,14,3,12, 3,17,2,16,5,1,2,1,8,9,3,19,4,2,2,4,17,25,21,20,28,75,1,10,29,103,4,1,2,1,1,4,2,4,1,2,3,24,2,2,2,1,1,2,1,3,8,1,1,1,2,1,1,3,1,1,1,6,1,5,3,1,1, 1,3,4,1,1,5,2,1,5,6,13,9,16,1,1,1,1,3,2,3,2,4,5,2,5,2,2,3,7,13,7,2,2,1,1,1,1,2,3,3,2,1,6,4,9,2,1,14,2,14,2,1,18,3,4,14,4,11,41,15,23,15,23, 176,1,3,4,1,1,1,1,5,3,1,2,3,7,3,1,1,2,1,2,4,4,6,2,4,1,9,7,1,10,5,8,16,29,1,1,2,2,3,1,3,5,2,4,5,4,1,1,2,2,3,3,7,1,6,10,1,17,1,44,4,6,2,1,1,6, 5,4,2,10,1,6,9,2,8,1,24,1,2,13,7,8,8,2,1,4,1,3,1,3,3,5,2,5,10,9,4,9,12,2,1,6,1,10,1,1,7,7,4,10,8,3,1,13,4,3,1,6,1,3,5,2,1,2,17,16,5,2,16,6, 1,4,2,1,3,3,6,8,5,11,11,1,3,3,2,4,6,10,9,5,7,4,7,4,7,1,1,4,2,1,3,6,8,7,1,6,11,5,5,3,24,9,4,2,7,13,5,1,8,82,16,61,1,1,1,4,2,2,16,10,3,8,1,1, 6,4,2,1,3,1,1,1,4,3,8,4,2,2,1,1,1,1,1,6,3,5,1,1,4,6,9,2,1,1,1,2,1,7,2,1,6,1,5,4,4,3,1,8,1,3,3,1,3,2,2,2,2,3,1,6,1,2,1,2,1,3,7,1,8,2,1,2,1,5, 2,5,3,5,10,1,2,1,1,3,2,5,11,3,9,3,5,1,1,5,9,1,2,1,5,7,9,9,8,1,3,3,3,6,8,2,3,2,1,1,32,6,1,2,15,9,3,7,13,1,3,10,13,2,14,1,13,10,2,1,3,10,4,15, 2,15,15,10,1,3,9,6,9,32,25,26,47,7,3,2,3,1,6,3,4,3,2,8,5,4,1,9,4,2,2,19,10,6,2,3,8,1,2,2,4,2,1,9,4,4,4,6,4,8,9,2,3,1,1,1,1,3,5,5,1,3,8,4,6, 2,1,4,12,1,5,3,7,13,2,5,8,1,6,1,2,5,14,6,1,5,2,4,8,15,5,1,23,6,62,2,10,1,1,8,1,2,2,10,4,2,2,9,2,1,1,3,2,3,1,5,3,3,2,1,3,8,1,1,1,11,3,1,1,4, 3,7,1,14,1,2,3,12,5,2,5,1,6,7,5,7,14,11,1,3,1,8,9,12,2,1,11,8,4,4,2,6,10,9,13,1,1,3,1,5,1,3,2,4,4,1,18,2,3,14,11,4,29,4,2,7,1,3,13,9,2,2,5, 3,5,20,7,16,8,5,72,34,6,4,22,12,12,28,45,36,9,7,39,9,191,1,1,1,4,11,8,4,9,2,3,22,1,1,1,1,4,17,1,7,7,1,11,31,10,2,4,8,2,3,2,1,4,2,16,4,32,2, 3,19,13,4,9,1,5,2,14,8,1,1,3,6,19,6,5,1,16,6,2,10,8,5,1,2,3,1,5,5,1,11,6,6,1,3,3,2,6,3,8,1,1,4,10,7,5,7,7,5,8,9,2,1,3,4,1,1,3,1,3,3,2,6,16, 1,4,6,3,1,10,6,1,3,15,2,9,2,10,25,13,9,16,6,2,2,10,11,4,3,9,1,2,6,6,5,4,30,40,1,10,7,12,14,33,6,3,6,7,3,1,3,1,11,14,4,9,5,12,11,49,18,51,31, 140,31,2,2,1,5,1,8,1,10,1,4,4,3,24,1,10,1,3,6,6,16,3,4,5,2,1,4,2,57,10,6,22,2,22,3,7,22,6,10,11,36,18,16,33,36,2,5,5,1,1,1,4,10,1,4,13,2,7, 5,2,9,3,4,1,7,43,3,7,3,9,14,7,9,1,11,1,1,3,7,4,18,13,1,14,1,3,6,10,73,2,2,30,6,1,11,18,19,13,22,3,46,42,37,89,7,3,16,34,2,2,3,9,1,7,1,1,1,2, 2,4,10,7,3,10,3,9,5,28,9,2,6,13,7,3,1,3,10,2,7,2,11,3,6,21,54,85,2,1,4,2,2,1,39,3,21,2,2,5,1,1,1,4,1,1,3,4,15,1,3,2,4,4,2,3,8,2,20,1,8,7,13, 4,1,26,6,2,9,34,4,21,52,10,4,4,1,5,12,2,11,1,7,2,30,12,44,2,30,1,1,3,6,16,9,17,39,82,2,2,24,7,1,7,3,16,9,14,44,2,1,2,1,2,3,5,2,4,1,6,7,5,3, 2,6,1,11,5,11,2,1,18,19,8,1,3,24,29,2,1,3,5,2,2,1,13,6,5,1,46,11,3,5,1,1,5,8,2,10,6,12,6,3,7,11,2,4,16,13,2,5,1,1,2,2,5,2,28,5,2,23,10,8,4, 4,22,39,95,38,8,14,9,5,1,13,5,4,3,13,12,11,1,9,1,27,37,2,5,4,4,63,211,95,2,2,2,1,3,5,2,1,1,2,2,1,1,1,3,2,4,1,2,1,1,5,2,2,1,1,2,3,1,3,1,1,1, 3,1,4,2,1,3,6,1,1,3,7,15,5,3,2,5,3,9,11,4,2,22,1,6,3,8,7,1,4,28,4,16,3,3,25,4,4,27,27,1,4,1,2,2,7,1,3,5,2,28,8,2,14,1,8,6,16,25,3,3,3,14,3, 3,1,1,2,1,4,6,3,8,4,1,1,1,2,3,6,10,6,2,3,18,3,2,5,5,4,3,1,5,2,5,4,23,7,6,12,6,4,17,11,9,5,1,1,10,5,12,1,1,11,26,33,7,3,6,1,17,7,1,5,12,1,11, 2,4,1,8,14,17,23,1,2,1,7,8,16,11,9,6,5,2,6,4,16,2,8,14,1,11,8,9,1,1,1,9,25,4,11,19,7,2,15,2,12,8,52,7,5,19,2,16,4,36,8,1,16,8,24,26,4,6,2,9, 5,4,36,3,28,12,25,15,37,27,17,12,59,38,5,32,127,1,2,9,17,14,4,1,2,1,1,8,11,50,4,14,2,19,16,4,17,5,4,5,26,12,45,2,23,45,104,30,12,8,3,10,2,2, 3,3,1,4,20,7,2,9,6,15,2,20,1,3,16,4,11,15,6,134,2,5,59,1,2,2,2,1,9,17,3,26,137,10,211,59,1,2,4,1,4,1,1,1,2,6,2,3,1,1,2,3,2,3,1,3,4,4,2,3,3, 1,4,3,1,7,2,2,3,1,2,1,3,3,3,2,2,3,2,1,3,14,6,1,3,2,9,6,15,27,9,34,145,1,1,2,1,1,1,1,2,1,1,1,1,2,2,2,3,1,2,1,1,1,2,3,5,8,3,5,2,4,1,3,2,2,2,12, 4,1,1,1,10,4,5,1,20,4,16,1,15,9,5,12,2,9,2,5,4,2,26,19,7,1,26,4,30,12,15,42,1,6,8,172,1,1,4,2,1,1,11,2,2,4,2,1,2,1,10,8,1,2,1,4,5,1,2,5,1,8, 4,1,3,4,2,1,6,2,1,3,4,1,2,1,1,1,1,12,5,7,2,4,3,1,1,1,3,3,6,1,2,2,3,3,3,2,1,2,12,14,11,6,6,4,12,2,8,1,7,10,1,35,7,4,13,15,4,3,23,21,28,52,5, 26,5,6,1,7,10,2,7,53,3,2,1,1,1,2,163,532,1,10,11,1,3,3,4,8,2,8,6,2,2,23,22,4,2,2,4,2,1,3,1,3,3,5,9,8,2,1,2,8,1,10,2,12,21,20,15,105,2,3,1,1, 3,2,3,1,1,2,5,1,4,15,11,19,1,1,1,1,5,4,5,1,1,2,5,3,5,12,1,2,5,1,11,1,1,15,9,1,4,5,3,26,8,2,1,3,1,1,15,19,2,12,1,2,5,2,7,2,19,2,20,6,26,7,5, 2,2,7,34,21,13,70,2,128,1,1,2,1,1,2,1,1,3,2,2,2,15,1,4,1,3,4,42,10,6,1,49,85,8,1,2,1,1,4,4,2,3,6,1,5,7,4,3,211,4,1,2,1,2,5,1,2,4,2,2,6,5,6, 10,3,4,48,100,6,2,16,296,5,27,387,2,2,3,7,16,8,5,38,15,39,21,9,10,3,7,59,13,27,21,47,5,21,6 }; static ImWchar base_ranges[] = // not zero-terminated { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x2000, 0x206F, // General Punctuation 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana 0x31F0, 0x31FF, // Katakana Phonetic Extensions 0xFF00, 0xFFEF // Half-width characters }; static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = { 0 }; if (!full_ranges[0]) { memcpy(full_ranges, base_ranges, sizeof(base_ranges)); UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges)); } return &full_ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() { // 1946 common ideograms code points for Japanese // Sourced from http://theinstructionlimit.com/common-kanji-character-ranges-for-xna-spritefont-rendering // FIXME: Source a list of the revised 2136 Joyo Kanji list from 2010 and rebuild this. // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) static const short accumulative_offsets_from_0x4E00[] = { 0,1,2,4,1,1,1,1,2,1,6,2,2,1,8,5,7,11,1,2,10,10,8,2,4,20,2,11,8,2,1,2,1,6,2,1,7,5,3,7,1,1,13,7,9,1,4,6,1,2,1,10,1,1,9,2,2,4,5,6,14,1,1,9,3,18, 5,4,2,2,10,7,1,1,1,3,2,4,3,23,2,10,12,2,14,2,4,13,1,6,10,3,1,7,13,6,4,13,5,2,3,17,2,2,5,7,6,4,1,7,14,16,6,13,9,15,1,1,7,16,4,7,1,19,9,2,7,15, 2,6,5,13,25,4,14,13,11,25,1,1,1,2,1,2,2,3,10,11,3,3,1,1,4,4,2,1,4,9,1,4,3,5,5,2,7,12,11,15,7,16,4,5,16,2,1,1,6,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1, 2,1,12,3,3,9,5,8,1,11,1,2,3,18,20,4,1,3,6,1,7,3,5,5,7,2,2,12,3,1,4,2,3,2,3,11,8,7,4,17,1,9,25,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,6,16,1,2,1,1,3,12, 20,2,5,20,8,7,6,2,1,1,1,1,6,2,1,2,10,1,1,6,1,3,1,2,1,4,1,12,4,1,3,1,1,1,1,1,10,4,7,5,13,1,15,1,1,30,11,9,1,15,38,14,1,32,17,20,1,9,31,2,21,9, 4,49,22,2,1,13,1,11,45,35,43,55,12,19,83,1,3,2,3,13,2,1,7,3,18,3,13,8,1,8,18,5,3,7,25,24,9,24,40,3,17,24,2,1,6,2,3,16,15,6,7,3,12,1,9,7,3,3, 3,15,21,5,16,4,5,12,11,11,3,6,3,2,31,3,2,1,1,23,6,6,1,4,2,6,5,2,1,1,3,3,22,2,6,2,3,17,3,2,4,5,1,9,5,1,1,6,15,12,3,17,2,14,2,8,1,23,16,4,2,23, 8,15,23,20,12,25,19,47,11,21,65,46,4,3,1,5,6,1,2,5,26,2,1,1,3,11,1,1,1,2,1,2,3,1,1,10,2,3,1,1,1,3,6,3,2,2,6,6,9,2,2,2,6,2,5,10,2,4,1,2,1,2,2, 3,1,1,3,1,2,9,23,9,2,1,1,1,1,5,3,2,1,10,9,6,1,10,2,31,25,3,7,5,40,1,15,6,17,7,27,180,1,3,2,2,1,1,1,6,3,10,7,1,3,6,17,8,6,2,2,1,3,5,5,8,16,14, 15,1,1,4,1,2,1,1,1,3,2,7,5,6,2,5,10,1,4,2,9,1,1,11,6,1,44,1,3,7,9,5,1,3,1,1,10,7,1,10,4,2,7,21,15,7,2,5,1,8,3,4,1,3,1,6,1,4,2,1,4,10,8,1,4,5, 1,5,10,2,7,1,10,1,1,3,4,11,10,29,4,7,3,5,2,3,33,5,2,19,3,1,4,2,6,31,11,1,3,3,3,1,8,10,9,12,11,12,8,3,14,8,6,11,1,4,41,3,1,2,7,13,1,5,6,2,6,12, 12,22,5,9,4,8,9,9,34,6,24,1,1,20,9,9,3,4,1,7,2,2,2,6,2,28,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,8,8,3,2,1,5,1,2,2,3,1,11,11,7,3,6,10,8,6,16,16, 22,7,12,6,21,5,4,6,6,3,6,1,3,2,1,2,8,29,1,10,1,6,13,6,6,19,31,1,13,4,4,22,17,26,33,10,4,15,12,25,6,67,10,2,3,1,6,10,2,6,2,9,1,9,4,4,1,2,16,2, 5,9,2,3,8,1,8,3,9,4,8,6,4,8,11,3,2,1,1,3,26,1,7,5,1,11,1,5,3,5,2,13,6,39,5,1,5,2,11,6,10,5,1,15,5,3,6,19,21,22,2,4,1,6,1,8,1,4,8,2,4,2,2,9,2, 1,1,1,4,3,6,3,12,7,1,14,2,4,10,2,13,1,17,7,3,2,1,3,2,13,7,14,12,3,1,29,2,8,9,15,14,9,14,1,3,1,6,5,9,11,3,38,43,20,7,7,8,5,15,12,19,15,81,8,7, 1,5,73,13,37,28,8,8,1,15,18,20,165,28,1,6,11,8,4,14,7,15,1,3,3,6,4,1,7,14,1,1,11,30,1,5,1,4,14,1,4,2,7,52,2,6,29,3,1,9,1,21,3,5,1,26,3,11,14, 11,1,17,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,7,7,5,17,3,3,3,1,23,10,4,4,6,3,1,16,17,22,3,10,21,16,16,6,4,10,2,1,1,2,8,8,6,5,3,3,3,39,25, 15,1,1,16,6,7,25,15,6,6,12,1,22,13,1,4,9,5,12,2,9,1,12,28,8,3,5,10,22,60,1,2,40,4,61,63,4,1,13,12,1,4,31,12,1,14,89,5,16,6,29,14,2,5,49,18,18, 5,29,33,47,1,17,1,19,12,2,9,7,39,12,3,7,12,39,3,1,46,4,12,3,8,9,5,31,15,18,3,2,2,66,19,13,17,5,3,46,124,13,57,34,2,5,4,5,8,1,1,1,4,3,1,17,5, 3,5,3,1,8,5,6,3,27,3,26,7,12,7,2,17,3,7,18,78,16,4,36,1,2,1,6,2,1,39,17,7,4,13,4,4,4,1,10,4,2,4,6,3,10,1,19,1,26,2,4,33,2,73,47,7,3,8,2,4,15, 18,1,29,2,41,14,1,21,16,41,7,39,25,13,44,2,2,10,1,13,7,1,7,3,5,20,4,8,2,49,1,10,6,1,6,7,10,7,11,16,3,12,20,4,10,3,1,2,11,2,28,9,2,4,7,2,15,1, 27,1,28,17,4,5,10,7,3,24,10,11,6,26,3,2,7,2,2,49,16,10,16,15,4,5,27,61,30,14,38,22,2,7,5,1,3,12,23,24,17,17,3,3,2,4,1,6,2,7,5,1,1,5,1,1,9,4, 1,3,6,1,8,2,8,4,14,3,5,11,4,1,3,32,1,19,4,1,13,11,5,2,1,8,6,8,1,6,5,13,3,23,11,5,3,16,3,9,10,1,24,3,198,52,4,2,2,5,14,5,4,22,5,20,4,11,6,41, 1,5,2,2,11,5,2,28,35,8,22,3,18,3,10,7,5,3,4,1,5,3,8,9,3,6,2,16,22,4,5,5,3,3,18,23,2,6,23,5,27,8,1,33,2,12,43,16,5,2,3,6,1,20,4,2,9,7,1,11,2, 10,3,14,31,9,3,25,18,20,2,5,5,26,14,1,11,17,12,40,19,9,6,31,83,2,7,9,19,78,12,14,21,76,12,113,79,34,4,1,1,61,18,85,10,2,2,13,31,11,50,6,33,159, 179,6,6,7,4,4,2,4,2,5,8,7,20,32,22,1,3,10,6,7,28,5,10,9,2,77,19,13,2,5,1,4,4,7,4,13,3,9,31,17,3,26,2,6,6,5,4,1,7,11,3,4,2,1,6,2,20,4,1,9,2,6, 3,7,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,5,13,8,4,11,23,1,10,6,2,1,3,21,2,2,4,24,31,4,10,10,2,5,192,15,4,16,7,9,51,1,2,1,1,5,1,1,2,1,3,5,3,1,3,4,1, 3,1,3,3,9,8,1,2,2,2,4,4,18,12,92,2,10,4,3,14,5,25,16,42,4,14,4,2,21,5,126,30,31,2,1,5,13,3,22,5,6,6,20,12,1,14,12,87,3,19,1,8,2,9,9,3,3,23,2, 3,7,6,3,1,2,3,9,1,3,1,6,3,2,1,3,11,3,1,6,10,3,2,3,1,2,1,5,1,1,11,3,6,4,1,7,2,1,2,5,5,34,4,14,18,4,19,7,5,8,2,6,79,1,5,2,14,8,2,9,2,1,36,28,16, 4,1,1,1,2,12,6,42,39,16,23,7,15,15,3,2,12,7,21,64,6,9,28,8,12,3,3,41,59,24,51,55,57,294,9,9,2,6,2,15,1,2,13,38,90,9,9,9,3,11,7,1,1,1,5,6,3,2, 1,2,2,3,8,1,4,4,1,5,7,1,4,3,20,4,9,1,1,1,5,5,17,1,5,2,6,2,4,1,4,5,7,3,18,11,11,32,7,5,4,7,11,127,8,4,3,3,1,10,1,1,6,21,14,1,16,1,7,1,3,6,9,65, 51,4,3,13,3,10,1,1,12,9,21,110,3,19,24,1,1,10,62,4,1,29,42,78,28,20,18,82,6,3,15,6,84,58,253,15,155,264,15,21,9,14,7,58,40,39, }; static ImWchar base_ranges[] = // not zero-terminated { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana 0x31F0, 0x31FF, // Katakana Phonetic Extensions 0xFF00, 0xFFEF // Half-width characters }; static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00)*2 + 1] = { 0 }; if (!full_ranges[0]) { memcpy(full_ranges, base_ranges, sizeof(base_ranges)); UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges)); } return &full_ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement 0x2DE0, 0x2DFF, // Cyrillic Extended-A 0xA640, 0xA69F, // Cyrillic Extended-B 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesThai() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin 0x2010, 0x205E, // Punctuations 0x0E00, 0x0E7F, // Thai 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin 0x0102, 0x0103, 0x0110, 0x0111, 0x0128, 0x0129, 0x0168, 0x0169, 0x01A0, 0x01A1, 0x01AF, 0x01B0, 0x1EA0, 0x1EF9, 0, }; return &ranges[0]; } //----------------------------------------------------------------------------- // [SECTION] ImFontGlyphRangesBuilder //----------------------------------------------------------------------------- void ImFontGlyphRangesBuilder::AddText(const char* text, const char* text_end) { while (text_end ? (text < text_end) : *text) { unsigned int c = 0; int c_len = ImTextCharFromUtf8(&c, text, text_end); text += c_len; if (c_len == 0) break; if (c < 0x10000) AddChar((ImWchar)c); } } void ImFontGlyphRangesBuilder::AddRanges(const ImWchar* ranges) { for (; ranges[0]; ranges += 2) for (ImWchar c = ranges[0]; c <= ranges[1]; c++) AddChar(c); } void ImFontGlyphRangesBuilder::BuildRanges(ImVector<ImWchar>* out_ranges) { int max_codepoint = 0x10000; for (int n = 0; n < max_codepoint; n++) if (GetBit(n)) { out_ranges->push_back((ImWchar)n); while (n < max_codepoint - 1 && GetBit(n + 1)) n++; out_ranges->push_back((ImWchar)n); } out_ranges->push_back(0); } //----------------------------------------------------------------------------- // [SECTION] ImFont //----------------------------------------------------------------------------- ImFont::ImFont() { FontSize = 0.0f; FallbackAdvanceX = 0.0f; FallbackChar = (ImWchar)'?'; DisplayOffset = ImVec2(0.0f, 0.0f); FallbackGlyph = NULL; ContainerAtlas = NULL; ConfigData = NULL; ConfigDataCount = 0; DirtyLookupTables = false; Scale = 1.0f; Ascent = Descent = 0.0f; MetricsTotalSurface = 0; } ImFont::~ImFont() { ClearOutputData(); } void ImFont::ClearOutputData() { FontSize = 0.0f; FallbackAdvanceX = 0.0f; Glyphs.clear(); IndexAdvanceX.clear(); IndexLookup.clear(); FallbackGlyph = NULL; ContainerAtlas = NULL; DirtyLookupTables = true; Ascent = Descent = 0.0f; MetricsTotalSurface = 0; } void ImFont::BuildLookupTable() { int max_codepoint = 0; for (int i = 0; i != Glyphs.Size; i++) max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved IndexAdvanceX.clear(); IndexLookup.clear(); DirtyLookupTables = false; GrowIndex(max_codepoint + 1); for (int i = 0; i < Glyphs.Size; i++) { int codepoint = (int)Glyphs[i].Codepoint; IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX; IndexLookup[codepoint] = (ImWchar)i; } // Create a glyph to handle TAB // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) if (FindGlyph((ImWchar)' ')) { if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times Glyphs.resize(Glyphs.Size + 1); ImFontGlyph& tab_glyph = Glyphs.back(); tab_glyph = *FindGlyph((ImWchar)' '); tab_glyph.Codepoint = '\t'; tab_glyph.AdvanceX *= IM_TABSIZE; IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size-1); } FallbackGlyph = FindGlyphNoFallback(FallbackChar); FallbackAdvanceX = FallbackGlyph ? FallbackGlyph->AdvanceX : 0.0f; for (int i = 0; i < max_codepoint + 1; i++) if (IndexAdvanceX[i] < 0.0f) IndexAdvanceX[i] = FallbackAdvanceX; } void ImFont::SetFallbackChar(ImWchar c) { FallbackChar = c; BuildLookupTable(); } void ImFont::GrowIndex(int new_size) { IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); if (new_size <= IndexLookup.Size) return; IndexAdvanceX.resize(new_size, -1.0f); IndexLookup.resize(new_size, (ImWchar)-1); } // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. // Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) { Glyphs.resize(Glyphs.Size + 1); ImFontGlyph& glyph = Glyphs.back(); glyph.Codepoint = (ImWchar)codepoint; glyph.X0 = x0; glyph.Y0 = y0; glyph.X1 = x1; glyph.Y1 = y1; glyph.U0 = u0; glyph.V0 = v0; glyph.U1 = u1; glyph.V1 = v1; glyph.AdvanceX = advance_x + ConfigData->GlyphExtraSpacing.x; // Bake spacing into AdvanceX if (ConfigData->PixelSnapH) glyph.AdvanceX = (float)(int)(glyph.AdvanceX + 0.5f); // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round) DirtyLookupTables = true; MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f); } void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) { IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. int index_size = IndexLookup.Size; if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists return; if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op return; GrowIndex(dst + 1); IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImWchar)-1; IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f; } const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const { if (c >= IndexLookup.Size) return FallbackGlyph; const ImWchar i = IndexLookup.Data[c]; if (i == (ImWchar)-1) return FallbackGlyph; return &Glyphs.Data[i]; } const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const { if (c >= IndexLookup.Size) return NULL; const ImWchar i = IndexLookup.Data[c]; if (i == (ImWchar)-1) return NULL; return &Glyphs.Data[i]; } const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const { // Simple word-wrapping for English, not full-featured. Please submit failing cases! // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" // ^ ^ ^ ^ ^__ ^ ^ // List of hardcoded separators: .,;!?'" // Skip extra blanks after a line returns (that includes not counting them in width computation) // e.g. "Hello world" --> "Hello" "World" // Cut words that cannot possibly fit within one line. // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" float line_width = 0.0f; float word_width = 0.0f; float blank_width = 0.0f; wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters const char* word_end = text; const char* prev_word_end = NULL; bool inside_word = true; const char* s = text; while (s < text_end) { unsigned int c = (unsigned int)*s; const char* next_s; if (c < 0x80) next_s = s + 1; else next_s = s + ImTextCharFromUtf8(&c, s, text_end); if (c == 0) break; if (c < 32) { if (c == '\n') { line_width = word_width = blank_width = 0.0f; inside_word = true; s = next_s; continue; } if (c == '\r') { s = next_s; continue; } } const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX); if (ImCharIsBlankW(c)) { if (inside_word) { line_width += blank_width; blank_width = 0.0f; word_end = s; } blank_width += char_width; inside_word = false; } else { word_width += char_width; if (inside_word) { word_end = next_s; } else { prev_word_end = word_end; line_width += word_width + blank_width; word_width = blank_width = 0.0f; } // Allow wrapping after punctuation. inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); } // We ignore blank width at the end of the line (they can be skipped) if (line_width + word_width >= wrap_width) { // Words that cannot possibly fit within an entire line will be cut anywhere. if (word_width < wrap_width) s = prev_word_end ? prev_word_end : word_end; break; } s = next_s; } return s; } ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const { if (!text_end) text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. const float line_height = size; const float scale = size / FontSize; ImVec2 text_size = ImVec2(0,0); float line_width = 0.0f; const bool word_wrap_enabled = (wrap_width > 0.0f); const char* word_wrap_eol = NULL; const char* s = text_begin; while (s < text_end) { if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) { word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below } if (s >= word_wrap_eol) { if (text_size.x < line_width) text_size.x = line_width; text_size.y += line_height; line_width = 0.0f; word_wrap_eol = NULL; // Wrapping skips upcoming blanks while (s < text_end) { const char c = *s; if (ImCharIsBlankA(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } } continue; } } // Decode and advance source const char* prev_s = s; unsigned int c = (unsigned int)*s; if (c < 0x80) { s += 1; } else { s += ImTextCharFromUtf8(&c, s, text_end); if (c == 0) // Malformed UTF-8? break; } if (c < 32) { if (c == '\n') { text_size.x = ImMax(text_size.x, line_width); text_size.y += line_height; line_width = 0.0f; continue; } if (c == '\r') continue; } const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX) * scale; if (line_width + char_width >= max_width) { s = prev_s; break; } line_width += char_width; } if (text_size.x < line_width) text_size.x = line_width; if (line_width > 0 || text_size.y == 0.0f) text_size.y += line_height; if (remaining) *remaining = s; return text_size; } void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const { if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded. return; if (const ImFontGlyph* glyph = FindGlyph(c)) { float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; pos.x = (float)(int)pos.x + DisplayOffset.x; pos.y = (float)(int)pos.y + DisplayOffset.y; draw_list->PrimReserve(6, 4); draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); } } void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const { if (!text_end) text_end = text_begin + strlen(text_begin); // ImGui functions generally already provides a valid text_end, so this is merely to handle direct calls. // Align to be pixel perfect pos.x = (float)(int)pos.x + DisplayOffset.x; pos.y = (float)(int)pos.y + DisplayOffset.y; float x = pos.x; float y = pos.y; if (y > clip_rect.w) return; const float scale = size / FontSize; const float line_height = FontSize * scale; const bool word_wrap_enabled = (wrap_width > 0.0f); const char* word_wrap_eol = NULL; // Fast-forward to first visible line const char* s = text_begin; if (y + line_height < clip_rect.y && !word_wrap_enabled) while (y + line_height < clip_rect.y && s < text_end) { s = (const char*)memchr(s, '\n', text_end - s); s = s ? s + 1 : text_end; y += line_height; } // For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve() // Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm) if (text_end - s > 10000 && !word_wrap_enabled) { const char* s_end = s; float y_end = y; while (y_end < clip_rect.w && s_end < text_end) { s_end = (const char*)memchr(s_end, '\n', text_end - s_end); s_end = s_end ? s_end + 1 : text_end; y_end += line_height; } text_end = s_end; } if (s == text_end) return; // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) const int vtx_count_max = (int)(text_end - s) * 4; const int idx_count_max = (int)(text_end - s) * 6; const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; draw_list->PrimReserve(idx_count_max, vtx_count_max); ImDrawVert* vtx_write = draw_list->_VtxWritePtr; ImDrawIdx* idx_write = draw_list->_IdxWritePtr; unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; while (s < text_end) { if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) { word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below } if (s >= word_wrap_eol) { x = pos.x; y += line_height; word_wrap_eol = NULL; // Wrapping skips upcoming blanks while (s < text_end) { const char c = *s; if (ImCharIsBlankA(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } } continue; } } // Decode and advance source unsigned int c = (unsigned int)*s; if (c < 0x80) { s += 1; } else { s += ImTextCharFromUtf8(&c, s, text_end); if (c == 0) // Malformed UTF-8? break; } if (c < 32) { if (c == '\n') { x = pos.x; y += line_height; if (y > clip_rect.w) break; // break out of main loop continue; } if (c == '\r') continue; } float char_width = 0.0f; if (const ImFontGlyph* glyph = FindGlyph((ImWchar)c)) { char_width = glyph->AdvanceX * scale; // Arbitrarily assume that both space and tabs are empty glyphs as an optimization if (c != ' ' && c != '\t') { // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w float x1 = x + glyph->X0 * scale; float x2 = x + glyph->X1 * scale; float y1 = y + glyph->Y0 * scale; float y2 = y + glyph->Y1 * scale; if (x1 <= clip_rect.z && x2 >= clip_rect.x) { // Render a character float u1 = glyph->U0; float v1 = glyph->V0; float u2 = glyph->U1; float v2 = glyph->V1; // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. if (cpu_fine_clip) { if (x1 < clip_rect.x) { u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); x1 = clip_rect.x; } if (y1 < clip_rect.y) { v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); y1 = clip_rect.y; } if (x2 > clip_rect.z) { u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); x2 = clip_rect.z; } if (y2 > clip_rect.w) { v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); y2 = clip_rect.w; } if (y1 >= y2) { x += char_width; continue; } } // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: { idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2); idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3); vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2; vtx_write += 4; vtx_current_idx += 4; idx_write += 6; } } } } x += char_width; } // Give back unused vertices draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data)); draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data)); draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); draw_list->_VtxWritePtr = vtx_write; draw_list->_IdxWritePtr = idx_write; draw_list->_VtxCurrentIdx = vtx_current_idx; } void ImFont::RenderTextVertical(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip, bool rotateCCW) const { if (!text_end) text_end = text_begin + strlen(text_begin); const float scale = size / FontSize; // Align to be pixel perfect pos.x = (float)(int)pos.x;// + (rotateCCW ? (font->FontSize-font->DisplayOffset.y) : 0); // Not sure it's correct pos.y = (float)(int)pos.y + DisplayOffset.x; float x = pos.x; float y = pos.y; if (x > clip_rect.z) return; const float line_height = FontSize * scale; const bool word_wrap_enabled = (wrap_width > 0.0f); const char* word_wrap_eol = NULL; const float y_dir = rotateCCW ? -1.f : 1.f; // Skip non-visible lines const char* s = text_begin; if (!word_wrap_enabled && y + line_height < clip_rect.y) while (s < text_end && *s != '\n') // Fast-forward to next line s++; // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) const int vtx_count_max = (int)(text_end - s) * 4; const int idx_count_max = (int)(text_end - s) * 6; const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; draw_list->PrimReserve(idx_count_max, vtx_count_max); ImDrawVert* vtx_write = draw_list->_VtxWritePtr; ImDrawIdx* idx_write = draw_list->_IdxWritePtr; unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; float x1 = 0.f, x2 = 0.f, y1 = 0.f, y2 = 0.f; while (s < text_end) { if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) { word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (y - pos.y)); if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below } if (s >= word_wrap_eol) { y = pos.y; x += line_height; word_wrap_eol = NULL; // Wrapping skips upcoming blanks while (s < text_end) { const char c = *s; if (ImCharIsBlankA(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } } continue; } } // Decode and advance source unsigned int c = (unsigned int)*s; if (c < 0x80) { s += 1; } else { s += ImTextCharFromUtf8(&c, s, text_end); if (c == 0) break; } if (c < 32) { if (c == '\n') { y = pos.y; x += line_height; if (x > clip_rect.z) break; if (!word_wrap_enabled && x + line_height < clip_rect.x) while (s < text_end && *s != '\n') // Fast-forward to next line s++; continue; } if (c == '\r') continue; } float char_width = 0.0f; if (const ImFont::Glyph* glyph = FindGlyph((unsigned short)c)) { char_width = glyph->AdvanceX * scale; // Arbitrarily assume that both space and tabs are empty glyphs as an optimization if (c != ' ' && c != '\t') { // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w if (!rotateCCW) { x1 = x + (FontSize - glyph->Y1) * scale; x2 = x + (FontSize - glyph->Y0) * scale; y1 = y + glyph->X0 * scale; y2 = y + glyph->X1 * scale; } else { x1 = x + glyph->Y0 * scale; x2 = x + glyph->Y1 * scale; y1 = y + glyph->X0 * scale; y2 = y + glyph->X1 * scale; } if (y1 <= clip_rect.w && y2 >= clip_rect.y) { // Render a character float u1 = glyph->U0; float v1 = glyph->V0; float u2 = glyph->U1; float v2 = glyph->V1; // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. if (cpu_fine_clip) { if (x1 < clip_rect.x) { u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); x1 = clip_rect.x; } if (y1 < clip_rect.y) { v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); y1 = clip_rect.y; } if (x2 > clip_rect.z) { u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); x2 = clip_rect.z; } if (y2 > clip_rect.w) { v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); y2 = clip_rect.w; } if (x1 >= x2) { y += char_width * y_dir; continue; } } // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug build. // Inlined here: { idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx + 1); idx_write[2] = (ImDrawIdx)(vtx_current_idx + 2); idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx + 2); idx_write[5] = (ImDrawIdx)(vtx_current_idx + 3); vtx_write[0].col = vtx_write[1].col = vtx_write[2].col = vtx_write[3].col = col; vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; if (rotateCCW) { vtx_write[0].uv.x = u2; vtx_write[0].uv.y = v1; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v2; vtx_write[2].uv.x = u1; vtx_write[2].uv.y = v2; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v1; } else { vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v2; vtx_write[1].uv.x = u1; vtx_write[1].uv.y = v1; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v1; vtx_write[3].uv.x = u2; vtx_write[3].uv.y = v2; } vtx_write += 4; vtx_current_idx += 4; idx_write += 6; } } } } y += char_width * y_dir; } // Give back unused vertices draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data)); draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data)); draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); draw_list->_VtxWritePtr = vtx_write; draw_list->_IdxWritePtr = idx_write; draw_list->_VtxCurrentIdx = (unsigned int)draw_list->VtxBuffer.Size; } //----------------------------------------------------------------------------- // [SECTION] Internal Render Helpers // (progressively moved from imgui.cpp to here when they are redesigned to stop accessing ImGui global state) //----------------------------------------------------------------------------- // - RenderMouseCursor() // - RenderArrowPointingAt() // - RenderRectFilledRangeH() // - RenderPixelEllipsis() //----------------------------------------------------------------------------- void ImGui::RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor) { if (mouse_cursor == ImGuiMouseCursor_None) return; IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT); const ImU32 col_shadow = IM_COL32(0, 0, 0, 48); const ImU32 col_border = IM_COL32(0, 0, 0, 255); // Black const ImU32 col_fill = IM_COL32(255, 255, 255, 255); // White ImFontAtlas* font_atlas = draw_list->_Data->Font->ContainerAtlas; ImVec2 offset, size, uv[4]; if (font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2])) { pos -= offset; const ImTextureID tex_id = font_atlas->TexID; draw_list->PushTextureID(tex_id); draw_list->AddImage(tex_id, pos + ImVec2(1,0)*scale, pos + ImVec2(1,0)*scale + size*scale, uv[2], uv[3], col_shadow); draw_list->AddImage(tex_id, pos + ImVec2(2,0)*scale, pos + ImVec2(2,0)*scale + size*scale, uv[2], uv[3], col_shadow); draw_list->AddImage(tex_id, pos, pos + size*scale, uv[2], uv[3], col_border); draw_list->AddImage(tex_id, pos, pos + size*scale, uv[0], uv[1], col_fill); draw_list->PopTextureID(); } } // Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col) { switch (direction) { case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return; case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return; case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return; case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return; case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings } } static inline float ImAcos01(float x) { if (x <= 0.0f) return IM_PI * 0.5f; if (x >= 1.0f) return 0.0f; return ImAcos(x); //return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do. } // FIXME: Cleanup and move code to ImDrawList. void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding) { if (x_end_norm == x_start_norm) return; if (x_start_norm > x_end_norm) ImSwap(x_start_norm, x_end_norm); ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y); ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y); if (rounding == 0.0f) { draw_list->AddRectFilled(p0, p1, col, 0.0f); return; } rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f, rounding); const float inv_rounding = 1.0f / rounding; const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding); const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding); const float half_pi = IM_PI * 0.5f; // We will == compare to this because we know this is the exact value ImAcos01 can return. const float x0 = ImMax(p0.x, rect.Min.x + rounding); if (arc0_b == arc0_e) { draw_list->PathLineTo(ImVec2(x0, p1.y)); draw_list->PathLineTo(ImVec2(x0, p0.y)); } else if (arc0_b == 0.0f && arc0_e == half_pi) { draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR } else { draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR } if (p1.x > rect.Min.x + rounding) { const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding); const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding); const float x1 = ImMin(p1.x, rect.Max.x - rounding); if (arc1_b == arc1_e) { draw_list->PathLineTo(ImVec2(x1, p0.y)); draw_list->PathLineTo(ImVec2(x1, p1.y)); } else if (arc1_b == 0.0f && arc1_e == half_pi) { draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3); // BR } else { draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR } } draw_list->PathFillConvex(col); } // FIXME: Rendering an ellipsis "..." is a surprisingly tricky problem for us... we cannot rely on font glyph having it, // and regular dot are typically too wide. If we render a dot/shape ourselves it comes with the risk that it wouldn't match // the boldness or positioning of what the font uses... void ImGui::RenderPixelEllipsis(ImDrawList* draw_list, ImVec2 pos, int count, ImU32 col) { ImFont* font = draw_list->_Data->Font; const float font_scale = draw_list->_Data->FontSize / font->FontSize; pos.y += (float)(int)(font->DisplayOffset.y + font->Ascent * font_scale + 0.5f - 1.0f); for (int dot_n = 0; dot_n < count; dot_n++) draw_list->AddRectFilled(ImVec2(pos.x + dot_n * 2.0f, pos.y), ImVec2(pos.x + dot_n * 2.0f + 1.0f, pos.y + 1.0f), col); } //----------------------------------------------------------------------------- // [SECTION] Decompression code //----------------------------------------------------------------------------- // Compressed with stb_compress() then converted to a C array and encoded as base85. // Use the program in misc/fonts/binary_to_compressed_c.cpp to create the array from a TTF file. // The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. // Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h //----------------------------------------------------------------------------- static unsigned int stb_decompress_length(const unsigned char *input) { return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; } static unsigned char *stb__barrier_out_e, *stb__barrier_out_b; static const unsigned char *stb__barrier_in_b; static unsigned char *stb__dout; static void stb__match(const unsigned char *data, unsigned int length) { // INVERSE of memmove... write each byte before copying the next... IM_ASSERT(stb__dout + length <= stb__barrier_out_e); if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; } if (data < stb__barrier_out_b) { stb__dout = stb__barrier_out_e+1; return; } while (length--) *stb__dout++ = *data++; } static void stb__lit(const unsigned char *data, unsigned int length) { IM_ASSERT(stb__dout + length <= stb__barrier_out_e); if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; } if (data < stb__barrier_in_b) { stb__dout = stb__barrier_out_e+1; return; } memcpy(stb__dout, data, length); stb__dout += length; } #define stb__in2(x) ((i[x] << 8) + i[(x)+1]) #define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) #define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) static const unsigned char *stb_decompress_token(const unsigned char *i) { if (*i >= 0x20) { // use fewer if's for cases that expand small if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); } else { // more ifs for cases that expand large, since overhead is amortized if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; } return i; } static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) { const unsigned long ADLER_MOD = 65521; unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; unsigned long blocklen, i; blocklen = buflen % 5552; while (buflen) { for (i=0; i + 7 < blocklen; i += 8) { s1 += buffer[0], s2 += s1; s1 += buffer[1], s2 += s1; s1 += buffer[2], s2 += s1; s1 += buffer[3], s2 += s1; s1 += buffer[4], s2 += s1; s1 += buffer[5], s2 += s1; s1 += buffer[6], s2 += s1; s1 += buffer[7], s2 += s1; buffer += 8; } for (; i < blocklen; ++i) s1 += *buffer++, s2 += s1; s1 %= ADLER_MOD, s2 %= ADLER_MOD; buflen -= blocklen; blocklen = 5552; } return (unsigned int)(s2 << 16) + (unsigned int)s1; } static unsigned int stb_decompress(unsigned char *output, const unsigned char *i, unsigned int /*length*/) { unsigned int olen; if (stb__in4(0) != 0x57bC0000) return 0; if (stb__in4(4) != 0) return 0; // error! stream is > 4GB olen = stb_decompress_length(i); stb__barrier_in_b = i; stb__barrier_out_e = output + olen; stb__barrier_out_b = output; i += 16; stb__dout = output; for (;;) { const unsigned char *old_i = i; i = stb_decompress_token(i); if (i == old_i) { if (*i == 0x05 && i[1] == 0xfa) { IM_ASSERT(stb__dout == output + olen); if (stb__dout != output + olen) return 0; if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) return 0; return olen; } else { IM_ASSERT(0); /* NOTREACHED */ return 0; } } IM_ASSERT(stb__dout <= output + olen); if (stb__dout > output + olen) return 0; } } //----------------------------------------------------------------------------- // [SECTION] Default font data (ProggyClean.ttf) //----------------------------------------------------------------------------- // ProggyClean.ttf // Copyright (c) 2004, 2005 Tristan Grimmer // MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) // Download and more information at http://upperbounds.net //----------------------------------------------------------------------------- // File: 'ProggyClean.ttf' (41208 bytes) // Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding). // The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. //----------------------------------------------------------------------------- static const char proggy_clean_ttf_compressed_data_base85[11980+1] = "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" "2*>]b(MC;$jPfY.;h^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#" "`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#0X@U.a<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL" "i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-VsM.M0rJfLH2eTM`*oJMHRC`N" "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`&#0j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N" "*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cX&#2m#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)" "tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX" "ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." "x]Ip.PH^'/aqUO/$1WxLoW0[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G" "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[7MI2k).'2($5FNP&EQ(,)" "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[K<L" "%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#" "OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)(" "h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h" "o;#2:;%d&#x9v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J<j$UpK<Q4a1]MupW^-" "sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-" "eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO" "M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VB<HFF*qL(" "$/V,;(kXZejWO`<[5?\?ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<iaQjO@.kLg;x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<" "nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?" "7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;" ")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" "D?@f&1'BW-)Ju<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" "bIu)'Z,*[>br5fX^:FPAWr-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTG&#1T5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aeg<Z'<$#4H)6,>e0jT6'N#(q%.O=?2S]u*(m<-" "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" "sZ88+dKQ)W6>J%CL<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P&#9r+$%CE=68>K8r0=dSC%%(@p7" ".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'b)Tq7VT9q^*^$$.:&N@@" "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" "@-W$U%VEQ/,,>>#)D<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#" "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#" "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0" "d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoF&#4DoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" "6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjL<Lni;''X.`$#8+1GD" ":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+" "tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*" "$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7" ":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A" "7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7" "u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT" "LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M" ":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>" "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%" "9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$U4O]GKx'm9)b@p7YsvK3w^YR-" "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY" "8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-" "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`" "0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/" "+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V" "?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK" "Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa" ">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>" "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#" "Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$" "MlvAF_jCK*.O-^(63adMT->W%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'IAO" "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>" "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#" "d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4&#3^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" "/QHC#3^ZC#7jmC#;v)D#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#" "m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#" "TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; static const char* GetDefaultCompressedFontDataTTFBase85() { return proggy_clean_ttf_compressed_data_base85; }
#include "stdafx.h" #include "g72x.h" static short qtab_721[7] = { -124, 80, 178, 246, 300, 349, 400}; /* * Maps G.721 code word to reconstructed scale factor normalized log * magnitude values. */ static short _dqlntab[16] = { -2048, 4, 135, 213, 273, 323, 373, 425, 425, 373, 323, 273, 213, 135, 4, -2048}; /* Maps G.721 code word to log of scale factor multiplier. */ static short _witab[16] = { -12, 18, 41, 64, 112, 198, 355, 1122, 1122, 355, 198, 112, 64, 41, 18, -12}; /* * Maps G.721 code words to a set of values whose long and short * term averages are computed and then compared to give an indication * how stationary (steady state) the signal is. */ static short _fitab[16] = {0, 0, 0, 0x200, 0x200, 0x200, 0x600, 0xE00, 0xE00, 0x600, 0x200, 0x200, 0x200, 0, 0, 0}; /* * g721_encoder() * * Encodes the input vale of linear PCM, A-law or u-law data sl and returns * the resulting code. -1 is returned for unknown input coding value. */ int g721_encoder(int sl, int in_coding, struct g72x_state *state_ptr) { short sezi, se, sez; /* ACCUM */ short d; /* SUBTA */ short sr; /* ADDB */ short y; /* MIX */ short dqsez; /* ADDC */ short dq, i; switch (in_coding) { /* linearize input sample to 14-bit PCM */ case AUDIO_ENCODING_LINEAR: sl >>= 2; /* 14-bit dynamic range */ break; default: return ( -1); } sezi = predictor_zero(state_ptr); sez = sezi >> 1; se = (sezi + predictor_pole(state_ptr)) >> 1; /* estimated signal */ d = sl - se; /* estimation difference */ /* quantize the prediction difference */ y = step_size(state_ptr); /* quantizer step size */ i = quantize(d, y, qtab_721, 7); /* i = ADPCM code */ dq = reconstruct(i & 8, _dqlntab[i], y); /* quantized est diff */ sr = (dq < 0) ? se - (dq & 0x3FFF) : se + dq; /* reconst. signal */ dqsez = sr + sez - se; /* pole prediction diff. */ update(4, y, _witab[i] << 5, _fitab[i], dq, sr, dqsez, state_ptr); return (i); } /* * g721_decoder() * * Description: * * Decodes a 4-bit code of G.721 encoded data of i and * returns the resulting linear PCM, A-law or u-law value. * return -1 for unknown out_coding value. */ int g721_decoder(int i, int out_coding, struct g72x_state *state_ptr) { short sezi, sei, sez, se; /* ACCUM */ short y; /* MIX */ short sr; /* ADDB */ short dq; short dqsez; i &= 0x0f; /* mask to get proper bits */ sezi = predictor_zero(state_ptr); sez = sezi >> 1; sei = sezi + predictor_pole(state_ptr); se = sei >> 1; /* se = estimated signal */ y = step_size(state_ptr); /* dynamic quantizer step size */ dq = reconstruct(i & 0x08, _dqlntab[i], y); /* quantized diff. */ sr = (dq < 0) ? (se - (dq & 0x3FFF)) : se + dq; /* reconst. signal */ dqsez = sr - se + sez; /* pole prediction diff. */ update(4, y, _witab[i] << 5, _fitab[i], dq, sr, dqsez, state_ptr); switch (out_coding) { case AUDIO_ENCODING_LINEAR: return (sr << 2); /* sr was 14-bit dynamic range */ default: return ( -1); } }
/* Copyright 2019-2021 Google LLC 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 "absl/flags/parse.h" #include "gtest/gtest.h" int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); absl::ParseCommandLine(argc, argv); return RUN_ALL_TESTS(); }
#ifndef SERWIS_SPRZETU_KOMPUTEROWEGO_LAPTOP_HPP #define SERWIS_SPRZETU_KOMPUTEROWEGO_LAPTOP_HPP #include "Device.hpp" class Laptop : public Device { bool hasACdReader; public: Laptop(double price, const std::string &brand, double weight, int memorySizeInMb, int batteryCapacityInMAh, bool hasACdReader); ~Laptop() final; bool getHasACdReader() const; std::string itemInfo() final; }; #endif //SERWIS_SPRZETU_KOMPUTEROWEGO_LAPTOP_HPP
/* * MIT License * * Copyright (c) 2018 Kalate Hexanome, 4IF, INSA Lyon * * 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 "PostIncOperator.h" #include "../../../utils/Common.h" #include "../../../ir/BasicBlock.h" #include "../../../ir/helpers/IROperatorHelper.h" #include "../../../ir/instructions/CopyInstruction.h" #include "../../../ir/instructions/EmptyInstruction.h" #include "../../../ir/instructions/AdditionInstruction.h" #include "../../statements/expressions/atomicexpression/LValue.h" using namespace caramel::utils; std::shared_ptr<caramel::ir::IR> caramel::ast::PostIncOperator::buildIR( std::shared_ptr<caramel::ir::BasicBlock> &currentBasicBlock, std::shared_ptr<caramel::ast::Expression> const &expression ) { auto lvalue = castTo<LValue::Ptr>(expression); std::string oldValue = Statement::createVarName(); currentBasicBlock->addInstruction(std::make_shared<ir::CopyInstruction>( currentBasicBlock, expression->getPrimaryType(), oldValue, lvalue->getSymbol()->getName() )); std::string tmpName = Statement::createVarName(); std::string lvalueRegister = SAFE_ADD_INSTRUCTION(expression, currentBasicBlock); currentBasicBlock->addInstruction(castTo<ir::IR::Ptr>(std::make_shared<ir::AdditionInstruction>( tmpName, currentBasicBlock, expression->getPrimaryType(), lvalueRegister, "1" ))); currentBasicBlock->addInstruction(std::make_shared<ir::CopyInstruction>( currentBasicBlock, expression->getPrimaryType(), lvalue->getSymbol()->getName(), tmpName )); return castTo<ir::IR::Ptr>(std::make_shared<ir::EmptyInstruction>( oldValue, currentBasicBlock, expression->getPrimaryType() )); } caramel::ast::StatementType caramel::ast::PostIncOperator::getExpressionType() const { return StatementType::UnaryAdditiveExpression; } std::string caramel::ast::PostIncOperator::getToken() const { return SYMBOL; }
#include <ros/ros.h> #include "CameraLidarTransformer.hpp" int main (int argc, char** argv) { ros::init (argc, argv, "camera_lidar_transformer"); CameraLidarTransformer transformer; ros::spin (); }
/* ------------------------------------------------------------------------------- This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------------- */ #include "rtImageTarget.h" #include <cstring> #include "rtCommon.h" rtImageTarget::rtImageTarget(SKuint32 w, SKuint32 h) : m_image(nullptr), m_frameBuffer() { m_image = new skImage(w, h, SK_RGBA); m_image->setFlipY(true); m_frameBuffer.width = (SKuint16)m_image->getWidth(); m_frameBuffer.height = (SKuint16)m_image->getHeight(); m_frameBuffer.maxSize = (SKuint32)m_image->getSizeInBytes(); m_frameBuffer.pitch = (SKuint16)m_image->getPitch(); m_frameBuffer.pixels = new SKubyte[m_frameBuffer.maxSize]; } rtImageTarget::~rtImageTarget() { delete[] m_frameBuffer.pixels; delete m_image; m_image = nullptr; } void rtImageTarget::save(const char* path) const { if (m_image) { for (SKuint32 y = 0; y < m_frameBuffer.height; ++y) { for (SKuint32 x = 0; x < m_frameBuffer.width; ++x) { rtPixelRGBA* rgba = (rtPixelRGBA*)&m_frameBuffer.pixels[x * 4 + y * m_frameBuffer.pitch]; m_image->setPixel(x, y, {rgba->r, rgba->g, rgba->b, 255}); } } m_image->save(path); } } SKuint32 rtImageTarget::getWidth() { if (m_image) return m_image->getWidth(); return 0; } SKuint32 rtImageTarget::getHeight() { if (m_image) return m_image->getHeight(); return 0; } SKuint32 rtImageTarget::getSizeInBytes() { if (m_image) { const SKsize sz = m_image->getSizeInBytes(); SK_ASSERT(sz < SK_NPOS32); return (SKuint32)sz; } return 0; } SKuint32 rtImageTarget::getPitch() { if (m_image) return m_image->getPitch(); return 0; }
// 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 "cc/surfaces/display.h" #include <utility> #include "base/memory/ptr_util.h" #include "base/test/null_task_runner.h" #include "cc/output/compositor_frame.h" #include "cc/output/copy_output_result.h" #include "cc/output/texture_mailbox_deleter.h" #include "cc/quads/render_pass.h" #include "cc/resources/shared_bitmap_manager.h" #include "cc/scheduler/begin_frame_source.h" #include "cc/surfaces/display_client.h" #include "cc/surfaces/display_scheduler.h" #include "cc/surfaces/frame_sink_id.h" #include "cc/surfaces/surface.h" #include "cc/surfaces/surface_factory.h" #include "cc/surfaces/surface_factory_client.h" #include "cc/surfaces/surface_id_allocator.h" #include "cc/surfaces/surface_manager.h" #include "cc/test/fake_output_surface.h" #include "cc/test/scheduler_test_common.h" #include "cc/test/test_shared_bitmap_manager.h" #include "gpu/GLES2/gl2extchromium.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::AnyNumber; namespace cc { namespace { static constexpr FrameSinkId kArbitraryFrameSinkId(3, 3); class FakeSurfaceFactoryClient : public SurfaceFactoryClient { public: FakeSurfaceFactoryClient() : begin_frame_source_(nullptr) {} void ReturnResources(const ReturnedResourceArray& resources) override {} void SetBeginFrameSource(BeginFrameSource* begin_frame_source) override { begin_frame_source_ = begin_frame_source; } BeginFrameSource* begin_frame_source() { return begin_frame_source_; } private: BeginFrameSource* begin_frame_source_; }; class TestSoftwareOutputDevice : public SoftwareOutputDevice { public: TestSoftwareOutputDevice() {} gfx::Rect damage_rect() const { return damage_rect_; } gfx::Size viewport_pixel_size() const { return viewport_pixel_size_; } }; class TestDisplayScheduler : public DisplayScheduler { public: explicit TestDisplayScheduler(base::SingleThreadTaskRunner* task_runner) : DisplayScheduler(task_runner, 1), damaged(false), display_resized_(false), has_new_root_surface(false), swapped(false) {} ~TestDisplayScheduler() override {} void DisplayResized() override { display_resized_ = true; } void SetNewRootSurface(const SurfaceId& root_surface_id) override { has_new_root_surface = true; } void SurfaceDamaged(const SurfaceId& surface_id) override { damaged = true; needs_draw_ = true; } void DidSwapBuffers() override { swapped = true; } void ResetDamageForTest() { damaged = false; display_resized_ = false; has_new_root_surface = false; } bool damaged; bool display_resized_; bool has_new_root_surface; bool swapped; }; class DisplayTest : public testing::Test { public: DisplayTest() : factory_(kArbitraryFrameSinkId, &manager_, &surface_factory_client_), task_runner_(new base::NullTaskRunner) { manager_.RegisterFrameSinkId(kArbitraryFrameSinkId); } ~DisplayTest() override { manager_.InvalidateFrameSinkId(kArbitraryFrameSinkId); factory_.EvictSurface(); } void SetUpDisplay(const RendererSettings& settings, std::unique_ptr<TestWebGraphicsContext3D> context) { begin_frame_source_.reset(new StubBeginFrameSource); std::unique_ptr<FakeOutputSurface> output_surface; if (context) { auto provider = TestContextProvider::Create(std::move(context)); provider->BindToCurrentThread(); output_surface = FakeOutputSurface::Create3d(std::move(provider)); } else { std::unique_ptr<TestSoftwareOutputDevice> device( new TestSoftwareOutputDevice); software_output_device_ = device.get(); output_surface = FakeOutputSurface::CreateSoftware(std::move(device)); } output_surface_ = output_surface.get(); std::unique_ptr<TestDisplayScheduler> scheduler( new TestDisplayScheduler(task_runner_.get())); scheduler_ = scheduler.get(); display_ = base::MakeUnique<Display>( &shared_bitmap_manager_, nullptr /* gpu_memory_buffer_manager */, settings, kArbitraryFrameSinkId, begin_frame_source_.get(), std::move(output_surface), std::move(scheduler), base::MakeUnique<TextureMailboxDeleter>(task_runner_.get())); display_->SetVisible(true); } protected: void SubmitCompositorFrame(RenderPassList* pass_list, const LocalFrameId& local_frame_id) { CompositorFrame frame; pass_list->swap(frame.render_pass_list); factory_.SubmitCompositorFrame(local_frame_id, std::move(frame), SurfaceFactory::DrawCallback()); } SurfaceManager manager_; FakeSurfaceFactoryClient surface_factory_client_; SurfaceFactory factory_; SurfaceIdAllocator id_allocator_; scoped_refptr<base::NullTaskRunner> task_runner_; TestSharedBitmapManager shared_bitmap_manager_; std::unique_ptr<BeginFrameSource> begin_frame_source_; std::unique_ptr<Display> display_; TestSoftwareOutputDevice* software_output_device_ = nullptr; FakeOutputSurface* output_surface_ = nullptr; TestDisplayScheduler* scheduler_ = nullptr; }; class StubDisplayClient : public DisplayClient { public: void DisplayOutputSurfaceLost() override {} void DisplayWillDrawAndSwap(bool will_draw_and_swap, const RenderPassList& render_passes) override {} void DisplayDidDrawAndSwap() override {} }; void CopyCallback(bool* called, std::unique_ptr<CopyOutputResult> result) { *called = true; } // Check that frame is damaged and swapped only under correct conditions. TEST_F(DisplayTest, DisplayDamaged) { RendererSettings settings; settings.partial_swap_enabled = true; settings.finish_rendering_on_resize = true; SetUpDisplay(settings, nullptr); StubDisplayClient client; display_->Initialize(&client, &manager_); LocalFrameId local_frame_id(id_allocator_.GenerateId()); EXPECT_FALSE(scheduler_->damaged); EXPECT_FALSE(scheduler_->has_new_root_surface); display_->SetLocalFrameId(local_frame_id, 1.f); EXPECT_FALSE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_TRUE(scheduler_->has_new_root_surface); scheduler_->ResetDamageForTest(); display_->Resize(gfx::Size(100, 100)); EXPECT_FALSE(scheduler_->damaged); EXPECT_TRUE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); // First draw from surface should have full damage. RenderPassList pass_list; std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 100, 100); pass->damage_rect = gfx::Rect(10, 10, 1, 1); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); SubmitCompositorFrame(&pass_list, local_frame_id); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); EXPECT_FALSE(scheduler_->swapped); EXPECT_EQ(0u, output_surface_->num_sent_frames()); display_->DrawAndSwap(); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(1u, output_surface_->num_sent_frames()); EXPECT_EQ(gfx::Size(100, 100), software_output_device_->viewport_pixel_size()); EXPECT_EQ(gfx::Rect(0, 0, 100, 100), software_output_device_->damage_rect()); { // Only damaged portion should be swapped. pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 100, 100); pass->damage_rect = gfx::Rect(10, 10, 1, 1); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); SubmitCompositorFrame(&pass_list, local_frame_id); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; display_->DrawAndSwap(); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(2u, output_surface_->num_sent_frames()); EXPECT_EQ(gfx::Size(100, 100), software_output_device_->viewport_pixel_size()); EXPECT_EQ(gfx::Rect(10, 10, 1, 1), software_output_device_->damage_rect()); } { // Pass has no damage so shouldn't be swapped. pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 100, 100); pass->damage_rect = gfx::Rect(10, 10, 0, 0); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); SubmitCompositorFrame(&pass_list, local_frame_id); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; display_->DrawAndSwap(); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(2u, output_surface_->num_sent_frames()); } { // Pass is wrong size so shouldn't be swapped. pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 99, 99); pass->damage_rect = gfx::Rect(10, 10, 10, 10); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); SubmitCompositorFrame(&pass_list, local_frame_id); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; display_->DrawAndSwap(); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(2u, output_surface_->num_sent_frames()); } { // Previous frame wasn't swapped, so next swap should have full damage. pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 100, 100); pass->damage_rect = gfx::Rect(10, 10, 0, 0); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); SubmitCompositorFrame(&pass_list, local_frame_id); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; display_->DrawAndSwap(); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(3u, output_surface_->num_sent_frames()); EXPECT_EQ(gfx::Rect(0, 0, 100, 100), software_output_device_->damage_rect()); } { // Pass has copy output request so should be swapped. pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 100, 100); pass->damage_rect = gfx::Rect(10, 10, 0, 0); bool copy_called = false; pass->copy_requests.push_back(CopyOutputRequest::CreateRequest( base::Bind(&CopyCallback, &copy_called))); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); SubmitCompositorFrame(&pass_list, local_frame_id); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; display_->DrawAndSwap(); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(4u, output_surface_->num_sent_frames()); EXPECT_TRUE(copy_called); } // Pass has no damage, so shouldn't be swapped, but latency info should be // saved for next swap. { pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 100, 100); pass->damage_rect = gfx::Rect(10, 10, 0, 0); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); CompositorFrame frame; pass_list.swap(frame.render_pass_list); frame.metadata.latency_info.push_back(ui::LatencyInfo()); factory_.SubmitCompositorFrame(local_frame_id, std::move(frame), SurfaceFactory::DrawCallback()); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; display_->DrawAndSwap(); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(4u, output_surface_->num_sent_frames()); } // Resize should cause a swap if no frame was swapped at the previous size. { scheduler_->swapped = false; display_->Resize(gfx::Size(200, 200)); EXPECT_FALSE(scheduler_->swapped); EXPECT_EQ(4u, output_surface_->num_sent_frames()); pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 200, 200); pass->damage_rect = gfx::Rect(10, 10, 10, 10); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); CompositorFrame frame; pass_list.swap(frame.render_pass_list); factory_.SubmitCompositorFrame(local_frame_id, std::move(frame), SurfaceFactory::DrawCallback()); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; display_->Resize(gfx::Size(100, 100)); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(5u, output_surface_->num_sent_frames()); // Latency info from previous frame should be sent now. EXPECT_EQ(1u, output_surface_->last_sent_frame()->latency_info.size()); } { // Surface that's damaged completely should be resized and swapped. pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 99, 99); pass->damage_rect = gfx::Rect(0, 0, 99, 99); pass->id = 1; pass_list.push_back(std::move(pass)); scheduler_->ResetDamageForTest(); SubmitCompositorFrame(&pass_list, local_frame_id); EXPECT_TRUE(scheduler_->damaged); EXPECT_FALSE(scheduler_->display_resized_); EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; display_->DrawAndSwap(); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(6u, output_surface_->num_sent_frames()); EXPECT_EQ(gfx::Size(100, 100), software_output_device_->viewport_pixel_size()); EXPECT_EQ(gfx::Rect(0, 0, 100, 100), software_output_device_->damage_rect()); EXPECT_EQ(0u, output_surface_->last_sent_frame()->latency_info.size()); } } class MockedContext : public TestWebGraphicsContext3D { public: MOCK_METHOD0(shallowFinishCHROMIUM, void()); }; TEST_F(DisplayTest, Finish) { LocalFrameId local_frame_id(id_allocator_.GenerateId()); RendererSettings settings; settings.partial_swap_enabled = true; settings.finish_rendering_on_resize = true; std::unique_ptr<MockedContext> context(new MockedContext()); MockedContext* context_ptr = context.get(); EXPECT_CALL(*context_ptr, shallowFinishCHROMIUM()).Times(0); SetUpDisplay(settings, std::move(context)); StubDisplayClient client; display_->Initialize(&client, &manager_); display_->SetLocalFrameId(local_frame_id, 1.f); display_->Resize(gfx::Size(100, 100)); { RenderPassList pass_list; std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 100, 100); pass->damage_rect = gfx::Rect(10, 10, 1, 1); pass->id = 1; pass_list.push_back(std::move(pass)); SubmitCompositorFrame(&pass_list, local_frame_id); } display_->DrawAndSwap(); // First resize and draw shouldn't finish. testing::Mock::VerifyAndClearExpectations(context_ptr); EXPECT_CALL(*context_ptr, shallowFinishCHROMIUM()); display_->Resize(gfx::Size(150, 150)); testing::Mock::VerifyAndClearExpectations(context_ptr); // Another resize without a swap doesn't need to finish. EXPECT_CALL(*context_ptr, shallowFinishCHROMIUM()).Times(0); display_->Resize(gfx::Size(200, 200)); testing::Mock::VerifyAndClearExpectations(context_ptr); EXPECT_CALL(*context_ptr, shallowFinishCHROMIUM()).Times(0); { RenderPassList pass_list; std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->output_rect = gfx::Rect(0, 0, 200, 200); pass->damage_rect = gfx::Rect(10, 10, 1, 1); pass->id = 1; pass_list.push_back(std::move(pass)); SubmitCompositorFrame(&pass_list, local_frame_id); } display_->DrawAndSwap(); testing::Mock::VerifyAndClearExpectations(context_ptr); EXPECT_CALL(*context_ptr, shallowFinishCHROMIUM()); display_->Resize(gfx::Size(250, 250)); testing::Mock::VerifyAndClearExpectations(context_ptr); } class CountLossDisplayClient : public StubDisplayClient { public: CountLossDisplayClient() = default; void DisplayOutputSurfaceLost() override { ++loss_count_; } int loss_count() const { return loss_count_; } private: int loss_count_ = 0; }; TEST_F(DisplayTest, ContextLossInformsClient) { SetUpDisplay(RendererSettings(), TestWebGraphicsContext3D::Create()); CountLossDisplayClient client; display_->Initialize(&client, &manager_); // Verify DidLoseOutputSurface callback is hooked up correctly. EXPECT_EQ(0, client.loss_count()); output_surface_->context_provider()->ContextGL()->LoseContextCHROMIUM( GL_GUILTY_CONTEXT_RESET_ARB, GL_INNOCENT_CONTEXT_RESET_ARB); output_surface_->context_provider()->ContextGL()->Flush(); EXPECT_EQ(1, client.loss_count()); } } // namespace } // namespace cc
/* Copyright 2018 The TensorFlow Authors. 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 <stdint.h> #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace builtin { namespace reverse { namespace { constexpr int kInputTensor = 0; constexpr int kAxisTensor = 1; constexpr int kOutputTensor = 0; TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const TfLiteTensor* axis; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxisTensor, &axis)); TF_LITE_ENSURE_EQ(context, NumDimensions(axis), 1); TF_LITE_ENSURE(context, NumDimensions(input) >= NumElements(axis)); if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 && input->type != kTfLiteUInt8 && input->type != kTfLiteInt8 && input->type != kTfLiteInt16 && input->type != kTfLiteInt64 && input->type != kTfLiteBool) { context->ReportError(context, "Type '%s' is not supported by reverse.", TfLiteTypeGetName(input->type)); return kTfLiteError; } if (axis->type != kTfLiteInt32) { context->ReportError(context, "Axis Type '%s' is not supported by reverse.", TfLiteTypeGetName(axis->type)); return kTfLiteError; } // TODO(renjieliu): support multi-axis case. if (NumElements(axis) > 1) { context->ReportError(context, "Current does not support more than 1 axis."); } TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims); TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type); return context->ResizeTensor(context, output, output_shape); } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const TfLiteTensor* axis_tensor; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxisTensor, &axis_tensor)); int axis = GetTensorData<int32_t>(axis_tensor)[0]; const int rank = NumDimensions(input); if (axis < 0) { axis += rank; } TF_LITE_ENSURE(context, axis >= 0 && axis < rank); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); switch (output->type) { case kTfLiteFloat32: { reference_ops::Reverse<float>( axis, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); break; } case kTfLiteUInt8: case kTfLiteInt8: { reference_ops::Reverse<uint8_t>( axis, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); break; } case kTfLiteInt16: { reference_ops::Reverse<int16_t>( axis, GetTensorShape(input), GetTensorData<int16_t>(input), GetTensorShape(output), GetTensorData<int16_t>(output)); break; } case kTfLiteInt32: { reference_ops::Reverse<int32_t>( axis, GetTensorShape(input), GetTensorData<int32_t>(input), GetTensorShape(output), GetTensorData<int32_t>(output)); break; } case kTfLiteInt64: { reference_ops::Reverse<int64_t>( axis, GetTensorShape(input), GetTensorData<int64_t>(input), GetTensorShape(output), GetTensorData<int64_t>(output)); break; } case kTfLiteBool: { reference_ops::Reverse<bool>( axis, GetTensorShape(input), GetTensorData<bool>(input), GetTensorShape(output), GetTensorData<bool>(output)); break; } default: { context->ReportError(context, "Type '%s' is not supported by reverse.", TfLiteTypeGetName(output->type)); return kTfLiteError; } } return kTfLiteOk; } } // namespace } // namespace reverse TfLiteRegistration* Register_REVERSE_V2() { static TfLiteRegistration r = {nullptr, nullptr, reverse::Prepare, reverse::Eval}; return &r; } } // namespace builtin } // namespace ops } // namespace tflite
//===--- PlaygroundTransform.cpp - Playground Transform -------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the playground transform for Swift. // //===----------------------------------------------------------------------===// #include "InstrumenterSupport.h" #include "swift/Subsystems.h" #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/DeclContext.h" #include "swift/AST/Module.h" #include "swift/AST/Pattern.h" #include <random> #include <forward_list> using namespace swift; using namespace swift::instrumenter_support; //===----------------------------------------------------------------------===// // performPlaygroundTransform //===----------------------------------------------------------------------===// namespace { class Instrumenter : InstrumenterBase { private: std::mt19937_64 &RNG; ASTContext &Context; DeclContext *TypeCheckDC; unsigned &TmpNameIndex; bool HighPerformance; struct BracePair { public: SourceRange BraceRange; enum class TargetKinds { None = 0, Break, Return, Fallthrough }; TargetKinds TargetKind = TargetKinds::None; BracePair(const SourceRange &BR) : BraceRange(BR) {} }; using BracePairStack = std::forward_list<BracePair>; BracePairStack BracePairs; class BracePairPusher { BracePairStack &BracePairs; bool Valid = false; public: BracePairPusher(BracePairStack &BPS, const SourceRange &BR) : BracePairs(BPS) { BracePairs.push_front(BracePair(BR)); Valid = true; } ~BracePairPusher() { if (isValid()) { Valid = false; BracePairs.pop_front(); } } void invalidate() { if (isValid()) { Valid = false; BracePairs.pop_front(); } } bool isValid() { return Valid; } }; class TargetKindSetter { BracePairStack &BracePairs; public: TargetKindSetter(BracePairStack &BPS, BracePair::TargetKinds Kind) : BracePairs(BPS) { assert(!BracePairs.empty()); assert(BracePairs.front().TargetKind == BracePair::TargetKinds::None); BracePairs.front().TargetKind = Kind; } ~TargetKindSetter() { BracePairs.front().TargetKind = BracePair::TargetKinds::None; } }; using ElementVector = SmallVector<swift::ASTNode, 3>; // Before a "return," "continue" or similar statement, emit pops of // all the braces up to its target. size_t escapeToTarget(BracePair::TargetKinds TargetKind, ElementVector &Elements, size_t EI) { if (HighPerformance) return EI; for (const BracePair &BP : BracePairs) { if (BP.TargetKind == TargetKind) { break; } Elements.insert(Elements.begin() + EI, *buildScopeExit(BP.BraceRange)); ++EI; } return EI; } public: Instrumenter(ASTContext &C, DeclContext *DC, std::mt19937_64 &RNG, bool HP, unsigned &TmpNameIndex) : RNG(RNG), Context(C), TypeCheckDC(DC), TmpNameIndex(TmpNameIndex), HighPerformance(HP) {} Stmt *transformStmt(Stmt *S) { switch (S->getKind()) { default: return S; case StmtKind::Brace: return transformBraceStmt(cast<BraceStmt>(S)); case StmtKind::Defer: return transformDeferStmt(cast<DeferStmt>(S)); case StmtKind::If: return transformIfStmt(cast<IfStmt>(S)); case StmtKind::Guard: return transformGuardStmt(cast<GuardStmt>(S)); case StmtKind::While: { TargetKindSetter TKS(BracePairs, BracePair::TargetKinds::Break); return transformWhileStmt(cast<WhileStmt>(S)); } case StmtKind::RepeatWhile: { TargetKindSetter TKS(BracePairs, BracePair::TargetKinds::Break); return transformRepeatWhileStmt(cast<RepeatWhileStmt>(S)); } case StmtKind::ForEach: { TargetKindSetter TKS(BracePairs, BracePair::TargetKinds::Break); return transformForEachStmt(cast<ForEachStmt>(S)); } case StmtKind::Switch: { TargetKindSetter TKS(BracePairs, BracePair::TargetKinds::Fallthrough); return transformSwitchStmt(cast<SwitchStmt>(S)); } case StmtKind::Do: return transformDoStmt(llvm::cast<DoStmt>(S)); case StmtKind::DoCatch: return transformDoCatchStmt(cast<DoCatchStmt>(S)); } } DeferStmt *transformDeferStmt(DeferStmt *DS) { if (auto *FD = DS->getTempDecl()) { // Temporarily unmark the DeferStmt's FuncDecl as implicit so it is // transformed (as typically implicit Decls are skipped by the // transformer). auto Implicit = FD->isImplicit(); FD->setImplicit(false); auto *D = transformDecl(FD); D->setImplicit(Implicit); assert(D == FD); } return DS; } // transform*() return their input if it's unmodified, // or a modified copy of their input otherwise. IfStmt *transformIfStmt(IfStmt *IS) { if (Stmt *TS = IS->getThenStmt()) { Stmt *NTS = transformStmt(TS); if (NTS != TS) { IS->setThenStmt(NTS); } } if (Stmt *ES = IS->getElseStmt()) { Stmt *NES = transformStmt(ES); if (NES != ES) { IS->setElseStmt(NES); } } return IS; } GuardStmt *transformGuardStmt(GuardStmt *GS) { if (Stmt *BS = GS->getBody()) GS->setBody(transformStmt(BS)); return GS; } WhileStmt *transformWhileStmt(WhileStmt *WS) { if (Stmt *B = WS->getBody()) { Stmt *NB = transformStmt(B); if (NB != B) { WS->setBody(NB); } } return WS; } RepeatWhileStmt *transformRepeatWhileStmt(RepeatWhileStmt *RWS) { if (Stmt *B = RWS->getBody()) { Stmt *NB = transformStmt(B); if (NB != B) { RWS->setBody(NB); } } return RWS; } ForEachStmt *transformForEachStmt(ForEachStmt *FES) { if (BraceStmt *B = FES->getBody()) { BraceStmt *NB = transformBraceStmt(B); if (NB != B) { FES->setBody(NB); } } return FES; } SwitchStmt *transformSwitchStmt(SwitchStmt *SS) { for (CaseStmt *CS : SS->getCases()) { if (Stmt *S = CS->getBody()) { if (auto *B = dyn_cast<BraceStmt>(S)) { BraceStmt *NB = transformBraceStmt(B); if (NB != B) { CS->setBody(NB); } } } } return SS; } DoStmt *transformDoStmt(DoStmt *DS) { if (auto *B = dyn_cast_or_null<BraceStmt>(DS->getBody())) { BraceStmt *NB = transformBraceStmt(B); if (NB != B) { DS->setBody(NB); } } return DS; } DoCatchStmt *transformDoCatchStmt(DoCatchStmt *DCS) { if (auto *B = dyn_cast_or_null<BraceStmt>(DCS->getBody())) { BraceStmt *NB = transformBraceStmt(B); if (NB != B) { DCS->setBody(NB); } } for (CatchStmt *C : DCS->getCatches()) { if (auto *CB = dyn_cast_or_null<BraceStmt>(C->getBody())) { BraceStmt *NCB = transformBraceStmt(CB); if (NCB != CB) { C->setBody(NCB); } } } return DCS; } Decl *transformDecl(Decl *D) { if (D->isImplicit()) return D; if (auto *FD = dyn_cast<FuncDecl>(D)) { if (BraceStmt *B = FD->getBody()) { TargetKindSetter TKS(BracePairs, BracePair::TargetKinds::Return); BraceStmt *NB = transformBraceStmt(B); if (NB != B) { FD->setBody(NB); TypeChecker(Context).checkFunctionErrorHandling(FD); } } } else if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) { for (Decl *Member : NTD->getMembers()) { transformDecl(Member); } } return D; } std::pair<Added<Expr *>, ValueDecl *> digForVariable(Expr *E) { switch (E->getKind()) { default: if (auto *ICE = dyn_cast<ImplicitConversionExpr>(E)) return digForVariable(ICE->getSubExpr()); return std::make_pair(Added<Expr *>(nullptr), nullptr); case ExprKind::DeclRef: { ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); Added<Expr *> DRE = new (Context) DeclRefExpr( ConcreteDeclRef(D), cast<DeclRefExpr>(E)->getNameLoc(), true, // implicit AccessSemantics::Ordinary, cast<DeclRefExpr>(E)->getType()); return std::make_pair(DRE, D); } case ExprKind::MemberRef: { std::pair<Added<Expr *>, ValueDecl *> BaseVariable = digForVariable(cast<MemberRefExpr>(E)->getBase()); if (!*BaseVariable.first || !BaseVariable.second) return std::make_pair(nullptr, nullptr); ValueDecl *M = cast<MemberRefExpr>(E)->getMember().getDecl(); Added<Expr *> MRE(new (Context) MemberRefExpr( *BaseVariable.first, cast<MemberRefExpr>(E)->getDotLoc(), ConcreteDeclRef(M), cast<MemberRefExpr>(E)->getNameLoc(), true, // implicit AccessSemantics::Ordinary)); return std::make_pair(MRE, M); } case ExprKind::Load: return digForVariable(cast<LoadExpr>(E)->getSubExpr()); case ExprKind::ForceValue: return digForVariable(cast<ForceValueExpr>(E)->getSubExpr()); case ExprKind::InOut: return digForVariable(cast<InOutExpr>(E)->getSubExpr()); } } std::string digForName(Expr *E) { Added<Expr *> RE = nullptr; ValueDecl *VD = nullptr; std::tie(RE, VD) = digForVariable(E); if (VD) { return VD->getBaseName().getIdentifier().str(); } else { return std::string(""); } } static DeclRefExpr *digForInoutDeclRef(Expr *E) { if (auto inout = dyn_cast<InOutExpr>(E)) { return dyn_cast<DeclRefExpr>( inout->getSubExpr()->getSemanticsProvidingExpr()); // Drill through tuple shuffles, ignoring non-default-argument inouts. } else if (auto shuffle = dyn_cast<TupleShuffleExpr>(E)) { return digForInoutDeclRef(shuffle->getSubExpr()); // Try to find a unique inout argument in a tuple. } else if (auto tuple = dyn_cast<TupleExpr>(E)) { DeclRefExpr *uniqueRef = nullptr; for (Expr *elt : tuple->getElements()) { if (auto ref = digForInoutDeclRef(elt)) { // If we already have a reference, it's not unique. if (uniqueRef) return nullptr; uniqueRef = ref; } } return uniqueRef; // Look through parens. } else { auto subExpr = E->getSemanticsProvidingExpr(); return (E == subExpr ? nullptr : digForInoutDeclRef(subExpr)); } } BraceStmt *transformBraceStmt(BraceStmt *BS, bool TopLevel = false) override { ArrayRef<ASTNode> OriginalElements = BS->getElements(); using ElementVector = SmallVector<swift::ASTNode, 3>; ElementVector Elements(OriginalElements.begin(), OriginalElements.end()); SourceRange SR = BS->getSourceRange(); BracePairPusher BPP(BracePairs, SR); for (size_t EI = 0; EI != Elements.size(); ++EI) { swift::ASTNode &Element = Elements[EI]; if (auto *E = Element.dyn_cast<Expr *>()) { E->walk(CF); if (auto *AE = dyn_cast<AssignExpr>(E)) { if (auto *MRE = dyn_cast<MemberRefExpr>(AE->getDest())) { // an assignment to a property of an object counts as a mutation of // that object Added<Expr *> Base_RE = nullptr; ValueDecl *BaseVD = nullptr; std::tie(Base_RE, BaseVD) = digForVariable(MRE->getBase()); if (*Base_RE) { Added<Stmt *> Log = logDeclOrMemberRef(Base_RE); if (*Log) { Elements.insert(Elements.begin() + (EI + 1), *Log); ++EI; } } } else { std::pair<PatternBindingDecl *, VarDecl *> PV = buildPatternAndVariable(AE->getSrc()); DeclRefExpr *DRE = new (Context) DeclRefExpr(ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, AE->getSrc()->getType()); AssignExpr *NAE = new (Context) AssignExpr(AE->getDest(), SourceLoc(), DRE, true); // implicit NAE->setType(Context.TheEmptyTupleType); AE->setImplicit(true); std::string Name = digForName(AE->getDest()); Added<Stmt *> Log(buildLoggerCall( new (Context) DeclRefExpr( ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, AE->getSrc()->getType()), AE->getSrc()->getSourceRange(), Name.c_str())); if (*Log) { Elements[EI] = PV.first; Elements.insert(Elements.begin() + (EI + 1), PV.second); Elements.insert(Elements.begin() + (EI + 2), *Log); Elements.insert(Elements.begin() + (EI + 3), NAE); EI += 3; } } } else if (auto *AE = dyn_cast<ApplyExpr>(E)) { bool Handled = false; if (auto *DRE = dyn_cast<DeclRefExpr>(AE->getFn())) { auto *FnD = dyn_cast<AbstractFunctionDecl>(DRE->getDecl()); if (FnD && FnD->getModuleContext() == Context.TheStdlibModule) { StringRef FnName = FnD->getNameStr(); if (FnName.equals("print") || FnName.equals("debugPrint")) { const bool isOldStyle = false; if (isOldStyle) { const bool isDebugPrint = FnName.equals("debugPrint"); PatternBindingDecl *ArgPattern = nullptr; VarDecl *ArgVariable = nullptr; Added<Stmt *> Log = logPrint(isDebugPrint, AE, ArgPattern, ArgVariable); if (*Log) { if (ArgPattern) { assert(ArgVariable); Elements[EI] = ArgPattern; Elements.insert(Elements.begin() + (EI + 1), ArgVariable); Elements.insert(Elements.begin() + (EI + 2), *Log); EI += 2; } else { Elements[EI] = *Log; } } } else { Added<Stmt *> Log = logPostPrint(AE->getSourceRange()); Elements.insert(Elements.begin() + (EI + 1), *Log); EI += 1; } Handled = true; } } } if (!Handled && AE->getType()->isEqual(Context.TheEmptyTupleType)) { if (auto *DSCE = dyn_cast<DotSyntaxCallExpr>(AE->getFn())) { Expr *TargetExpr = DSCE->getArg(); Added<Expr *> Target_RE; ValueDecl *TargetVD = nullptr; std::tie(Target_RE, TargetVD) = digForVariable(TargetExpr); if (TargetVD) { Added<Stmt *> Log = logDeclOrMemberRef(Target_RE); if (*Log) { Elements.insert(Elements.begin() + (EI + 1), *Log); ++EI; } Handled = true; } } if (!Handled) { if (DeclRefExpr *DRE = digForInoutDeclRef(AE->getArg())) { Added<Stmt *> Log = logDeclOrMemberRef(DRE); if (*Log) { Elements.insert(Elements.begin() + (EI + 1), *Log); ++EI; } } } Handled = true; // Never log () } if (!Handled) { // do the same as for all other expressions std::pair<PatternBindingDecl *, VarDecl *> PV = buildPatternAndVariable(E); Added<Stmt *> Log = buildLoggerCall( new (Context) DeclRefExpr(ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, E->getType()), E->getSourceRange(), ""); if (*Log) { Elements[EI] = PV.first; Elements.insert(Elements.begin() + (EI + 1), PV.second); Elements.insert(Elements.begin() + (EI + 2), *Log); EI += 2; } } } else { if (E->getType()->getCanonicalType() != Context.TheEmptyTupleType) { std::pair<PatternBindingDecl *, VarDecl *> PV = buildPatternAndVariable(E); Added<Stmt *> Log = buildLoggerCall( new (Context) DeclRefExpr(ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, E->getType()), E->getSourceRange(), ""); if (*Log) { Elements[EI] = PV.first; Elements.insert(Elements.begin() + (EI + 1), PV.second); Elements.insert(Elements.begin() + (EI + 2), *Log); EI += 2; } } } } else if (auto *S = Element.dyn_cast<Stmt *>()) { S->walk(CF); if (auto *RS = dyn_cast<ReturnStmt>(S)) { if (RS->hasResult()) { std::pair<PatternBindingDecl *, VarDecl *> PV = buildPatternAndVariable(RS->getResult()); DeclRefExpr *DRE = new (Context) DeclRefExpr( ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, RS->getResult()->getType()); ReturnStmt *NRS = new (Context) ReturnStmt(SourceLoc(), DRE, true); // implicit Added<Stmt *> Log = buildLoggerCall( new (Context) DeclRefExpr( ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, RS->getResult()->getType()), RS->getResult()->getSourceRange(), ""); if (*Log) { Elements[EI] = PV.first; Elements.insert(Elements.begin() + (EI + 1), PV.second); Elements.insert(Elements.begin() + (EI + 2), *Log); Elements.insert(Elements.begin() + (EI + 3), NRS); EI += 3; } } EI = escapeToTarget(BracePair::TargetKinds::Return, Elements, EI); } else { if (isa<BreakStmt>(S) || isa<ContinueStmt>(S)) { EI = escapeToTarget(BracePair::TargetKinds::Break, Elements, EI); } else if (isa<FallthroughStmt>(S)) { EI = escapeToTarget(BracePair::TargetKinds::Fallthrough, Elements, EI); } Stmt *NS = transformStmt(S); if (NS != S) { Elements[EI] = NS; } } } else if (auto *D = Element.dyn_cast<Decl *>()) { D->walk(CF); if (auto *PBD = dyn_cast<PatternBindingDecl>(D)) { if (VarDecl *VD = PBD->getSingleVar()) { if (VD->getParentInitializer()) { Added<Stmt *> Log = logVarDecl(VD); if (*Log) { Elements.insert(Elements.begin() + (EI + 1), *Log); ++EI; } } } } else { transformDecl(D); } } } if (!TopLevel && !HighPerformance) { Elements.insert(Elements.begin(), *buildScopeEntry(BS->getSourceRange())); Elements.insert(Elements.end(), *buildScopeExit(BS->getSourceRange())); } // Remove null elements from the list. // FIXME: This is a band-aid used to work around the fact that the // above code can introduce null elements into the vector. The // right fix is to avoid doing that above. Elements.erase(std::remove_if(Elements.begin(), Elements.end(), [](ASTNode node) { return node.isNull(); }), Elements.end()); return swift::BraceStmt::create(Context, BS->getLBraceLoc(), Context.AllocateCopy(Elements), BS->getRBraceLoc()); } // log*() functions return a newly-created log expression to be inserted // after or instead of the expression they're looking at. Only call this // if the variable has an initializer. Added<Stmt *> logVarDecl(VarDecl *VD) { if (isa<ConstructorDecl>(TypeCheckDC) && VD->getNameStr().equals("self")) { // Don't log "self" in a constructor return nullptr; } return buildLoggerCall( new (Context) DeclRefExpr(ConcreteDeclRef(VD), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, Type()), VD->getSourceRange(), VD->getName().str().str().c_str()); } Added<Stmt *> logDeclOrMemberRef(Added<Expr *> RE) { if (auto *DRE = dyn_cast<DeclRefExpr>(*RE)) { VarDecl *VD = cast<VarDecl>(DRE->getDecl()); if (isa<ConstructorDecl>(TypeCheckDC) && VD->getNameStr().equals("self")) { // Don't log "self" in a constructor return nullptr; } return buildLoggerCall( new (Context) DeclRefExpr(ConcreteDeclRef(VD), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, Type()), DRE->getSourceRange(), VD->getName().str().str().c_str()); } else if (auto *MRE = dyn_cast<MemberRefExpr>(*RE)) { Expr *B = MRE->getBase(); ConcreteDeclRef M = MRE->getMember(); if (isa<ConstructorDecl>(TypeCheckDC) && !digForName(B).compare("self")) { // Don't log attributes of "self" in a constructor return nullptr; } return buildLoggerCall( new (Context) MemberRefExpr(B, SourceLoc(), M, DeclNameLoc(), true, // implicit AccessSemantics::Ordinary), MRE->getSourceRange(), M.getDecl()->getBaseName().getIdentifier().str().str().c_str()); } else { return nullptr; } } std::pair<PatternBindingDecl *, VarDecl *> maybeFixupPrintArgument(ApplyExpr *Print) { Expr *ArgTuple = Print->getArg(); if (auto *PE = dyn_cast<ParenExpr>(ArgTuple)) { std::pair<PatternBindingDecl *, VarDecl *> PV = buildPatternAndVariable(PE->getSubExpr()); PE->setSubExpr(new (Context) DeclRefExpr( ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, PE->getSubExpr()->getType())); return PV; } else if (auto *TE = dyn_cast<TupleExpr>(ArgTuple)) { if (TE->getNumElements() == 0) { return std::make_pair(nullptr, nullptr); } else { // Are we using print() specialized to handle a single argument, // or is actually only the first argument of interest and the rest are // extra information for print()? bool useJustFirst = false; if (TE->hasElementNames()) { useJustFirst = true; } else { for (Expr *Arg : TE->getElements()) { if (Arg->isSemanticallyInOutExpr()) { useJustFirst = true; break; } } } if (useJustFirst) { std::pair<PatternBindingDecl *, VarDecl *> PV = buildPatternAndVariable(TE->getElement(0)); TE->setElement(0, new (Context) DeclRefExpr( ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, TE->getElement(0)->getType())); return PV; } else { std::pair<PatternBindingDecl *, VarDecl *> PV = buildPatternAndVariable(TE); Print->setArg(new (Context) DeclRefExpr( ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, TE->getType())); return PV; } } } else { return std::make_pair(nullptr, nullptr); } } Added<Stmt *> logPrint(bool isDebugPrint, ApplyExpr *AE, PatternBindingDecl *&ArgPattern, VarDecl *&ArgVariable) { const char *LoggerName = isDebugPrint ? "$builtin_debugPrint" : "$builtin_print"; UnresolvedDeclRefExpr *LoggerRef = new (Context) UnresolvedDeclRefExpr( Context.getIdentifier(LoggerName), DeclRefKind::Ordinary, DeclNameLoc(AE->getSourceRange().End)); std::tie(ArgPattern, ArgVariable) = maybeFixupPrintArgument(AE); AE->setFn(LoggerRef); Added<ApplyExpr *> AddedApply(AE); // safe because we've fixed up the args if (!doTypeCheck(Context, TypeCheckDC, AddedApply)) { return nullptr; } return buildLoggerCallWithApply(AddedApply, AE->getSourceRange()); } Added<Stmt *> logPostPrint(SourceRange SR) { return buildLoggerCallWithArgs("$builtin_postPrint", MutableArrayRef<Expr *>(), SR); } std::pair<PatternBindingDecl *, VarDecl *> buildPatternAndVariable(Expr *InitExpr) { // This is 14 because "tmp" is 3 chars, %u is at most 10 digits long plus a // null terminator. char NameBuf[14] = {0}; snprintf(NameBuf, sizeof(NameBuf), "tmp%u", TmpNameIndex); TmpNameIndex++; Expr *MaybeLoadInitExpr = nullptr; if (LValueType *LVT = InitExpr->getType()->getAs<LValueType>()) { MaybeLoadInitExpr = new (Context) LoadExpr(InitExpr, LVT->getObjectType()); } else { MaybeLoadInitExpr = InitExpr; } VarDecl *VD = new (Context) VarDecl(/*IsStatic*/false, VarDecl::Specifier::Let, /*IsCaptureList*/false, SourceLoc(), Context.getIdentifier(NameBuf), MaybeLoadInitExpr->getType(), TypeCheckDC); VD->setInterfaceType(VD->getType()->mapTypeOutOfContext()); VD->setImplicit(); NamedPattern *NP = new (Context) NamedPattern(VD, /*implicit*/ true); PatternBindingDecl *PBD = PatternBindingDecl::createImplicit( Context, StaticSpellingKind::None, NP, MaybeLoadInitExpr, TypeCheckDC); return std::make_pair(PBD, VD); } Added<Stmt *> buildLoggerCall(Added<Expr *> E, SourceRange SR, const char *Name) { assert(Name); std::string *NameInContext = Context.AllocateObjectCopy(std::string(Name)); Expr *NameExpr = new (Context) StringLiteralExpr(NameInContext->c_str(), SourceRange()); NameExpr->setImplicit(true); std::uniform_int_distribution<unsigned> Distribution(0, 0x7fffffffu); const unsigned id_num = Distribution(RNG); Expr *IDExpr = IntegerLiteralExpr::createFromUnsigned(Context, id_num); Expr *LoggerArgExprs[] = {*E, NameExpr, IDExpr}; return buildLoggerCallWithArgs("$builtin_log_with_id", MutableArrayRef<Expr *>(LoggerArgExprs), SR); } Added<Stmt *> buildScopeEntry(SourceRange SR) { return buildScopeCall(SR, false); } Added<Stmt *> buildScopeExit(SourceRange SR) { return buildScopeCall(SR, true); } Added<Stmt *> buildScopeCall(SourceRange SR, bool IsExit) { const char *LoggerName = IsExit ? "$builtin_log_scope_exit" : "$builtin_log_scope_entry"; return buildLoggerCallWithArgs(LoggerName, MutableArrayRef<Expr *>(), SR); } Added<Stmt *> buildLoggerCallWithArgs(const char *LoggerName, MutableArrayRef<Expr *> Args, SourceRange SR) { // If something doesn't have a valid source range it can not be playground // logged. For example, a PC Macro event. if (!SR.isValid()) { return nullptr; } std::pair<unsigned, unsigned> StartLC = Context.SourceMgr.getLineAndColumn(SR.Start); std::pair<unsigned, unsigned> EndLC = Context.SourceMgr.getLineAndColumn( Lexer::getLocForEndOfToken(Context.SourceMgr, SR.End)); Expr *StartLine = IntegerLiteralExpr::createFromUnsigned(Context, StartLC.first); Expr *EndLine = IntegerLiteralExpr::createFromUnsigned(Context, EndLC.first); Expr *StartColumn = IntegerLiteralExpr::createFromUnsigned(Context, StartLC.second); Expr *EndColumn = IntegerLiteralExpr::createFromUnsigned(Context, EndLC.second); llvm::SmallVector<Expr *, 6> ArgsWithSourceRange(Args.begin(), Args.end()); ArgsWithSourceRange.append({StartLine, EndLine, StartColumn, EndColumn}); UnresolvedDeclRefExpr *LoggerRef = new (Context) UnresolvedDeclRefExpr(Context.getIdentifier(LoggerName), DeclRefKind::Ordinary, DeclNameLoc(SR.End)); LoggerRef->setImplicit(true); SmallVector<Identifier, 4> ArgLabels(ArgsWithSourceRange.size(), Identifier()); ApplyExpr *LoggerCall = CallExpr::createImplicit( Context, LoggerRef, ArgsWithSourceRange, ArgLabels); Added<ApplyExpr *> AddedLogger(LoggerCall); if (!doTypeCheck(Context, TypeCheckDC, AddedLogger)) { return nullptr; } return buildLoggerCallWithApply(AddedLogger, SR); } // Assumes Apply has already been type-checked. Added<Stmt *> buildLoggerCallWithApply(Added<ApplyExpr *> Apply, SourceRange SR) { std::pair<PatternBindingDecl *, VarDecl *> PV = buildPatternAndVariable(*Apply); DeclRefExpr *DRE = new (Context) DeclRefExpr(ConcreteDeclRef(PV.second), DeclNameLoc(), true, // implicit AccessSemantics::Ordinary, Apply->getType()); UnresolvedDeclRefExpr *SendDataRef = new (Context) UnresolvedDeclRefExpr(Context.getIdentifier("$builtin_send_data"), DeclRefKind::Ordinary, DeclNameLoc()); SendDataRef->setImplicit(true); Expr *SendDataCall = CallExpr::createImplicit(Context, SendDataRef, {DRE}, {Identifier()}); Added<Expr *> AddedSendData(SendDataCall); if (!doTypeCheck(Context, TypeCheckDC, AddedSendData)) { return nullptr; } ASTNode Elements[] = {PV.first, PV.second, SendDataCall}; BraceStmt *BS = BraceStmt::create(Context, SourceLoc(), Elements, SourceLoc(), true); return BS; } }; } // end anonymous namespace void swift::performPlaygroundTransform(SourceFile &SF, bool HighPerformance) { class ExpressionFinder : public ASTWalker { private: std::mt19937_64 RNG; bool HighPerformance; unsigned TmpNameIndex = 0; public: ExpressionFinder(bool HP) : HighPerformance(HP) {} bool walkToDeclPre(Decl *D) override { if (auto *FD = dyn_cast<AbstractFunctionDecl>(D)) { if (!FD->isImplicit()) { if (BraceStmt *Body = FD->getBody()) { ASTContext &ctx = FD->getASTContext(); Instrumenter I(ctx, FD, RNG, HighPerformance, TmpNameIndex); BraceStmt *NewBody = I.transformBraceStmt(Body); if (NewBody != Body) { FD->setBody(NewBody); TypeChecker(ctx).checkFunctionErrorHandling(FD); } return false; } } } else if (auto *TLCD = dyn_cast<TopLevelCodeDecl>(D)) { if (!TLCD->isImplicit()) { if (BraceStmt *Body = TLCD->getBody()) { ASTContext &ctx = static_cast<Decl *>(TLCD)->getASTContext(); Instrumenter I(ctx, TLCD, RNG, HighPerformance, TmpNameIndex); BraceStmt *NewBody = I.transformBraceStmt(Body, true); if (NewBody != Body) { TLCD->setBody(NewBody); TypeChecker(ctx).checkTopLevelErrorHandling(TLCD); } return false; } } } return true; } }; ExpressionFinder EF(HighPerformance); for (Decl *D : SF.Decls) { D->walk(EF); } }
//myfirst.cpp --displays a message #include <iostream> // a PREPROCESSOR directive int main() // function header { // start of function body using namespace std; // make definitions visible cout << "Come up and C++ me some time."; // message cout << endl; // start a new line cout << "You won't regret it!" <<endl; // more output return 0; // terminate main() } // end of function body