hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
37039a0b930df44df796db907271b1b4f5b6b02f
5,771
cpp
C++
extras/vom/vom/l2_binding.cpp
amithbraj/vpp
edf1da94dc099c6e2ab1d455ce8652fada3cdb04
[ "Apache-2.0" ]
52
2016-09-20T15:08:46.000Z
2020-12-22T23:03:25.000Z
extras/vom/vom/l2_binding.cpp
fantastic2085/vpp
c599c6f001bc28e1023fb5e74a27db37b1aae847
[ "Apache-2.0" ]
63
2018-06-11T09:48:35.000Z
2021-01-05T09:11:03.000Z
extras/vom/vom/l2_binding.cpp
fantastic2085/vpp
c599c6f001bc28e1023fb5e74a27db37b1aae847
[ "Apache-2.0" ]
36
2016-07-21T11:20:33.000Z
2022-01-16T15:55:45.000Z
/* * Copyright (c) 2017 Cisco and/or its affiliates. * 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 "vom/l2_binding.hpp" #include "vom/l2_binding_cmds.hpp" #include "vom/l2_vtr_cmds.hpp" #include "vom/singular_db_funcs.hpp" namespace VOM { /** * A DB of all the L2 Configs */ singular_db<l2_binding::key_t, l2_binding> l2_binding::m_db; l2_binding::event_handler l2_binding::m_evh; const l2_binding::l2_port_type_t l2_binding::l2_port_type_t::L2_PORT_TYPE_NORMAL(0, "normal"); const l2_binding::l2_port_type_t l2_binding::l2_port_type_t::L2_PORT_TYPE_BVI( 1, "bvi"); const l2_binding::l2_port_type_t l2_binding::l2_port_type_t::L2_PORT_TYPE_UU_FWD(2, "uu-fwd"); l2_binding::l2_port_type_t::l2_port_type_t(int v, const std::string s) : enum_base<l2_binding::l2_port_type_t>(v, s) { } /** * Construct a new object matching the desried state */ l2_binding::l2_binding(const interface& itf, const bridge_domain& bd) : m_itf(itf.singular()) , m_bd(bd.singular()) , m_port_type(l2_port_type_t::L2_PORT_TYPE_NORMAL) , m_binding(0) , m_vtr_op(l2_vtr::option_t::DISABLED, rc_t::UNSET) , m_vtr_op_tag(0) { if (interface::type_t::BVI == m_itf->type()) m_port_type = l2_port_type_t::L2_PORT_TYPE_BVI; } /** * Construct a new object matching the desried state */ l2_binding::l2_binding(const interface& itf, const bridge_domain& bd, const l2_port_type_t& port_type) : m_itf(itf.singular()) , m_bd(bd.singular()) , m_port_type(port_type) , m_binding(0) , m_vtr_op(l2_vtr::option_t::DISABLED, rc_t::UNSET) , m_vtr_op_tag(0) { } l2_binding::l2_binding(const l2_binding& o) : m_itf(o.m_itf) , m_bd(o.m_bd) , m_port_type(o.m_port_type) , m_binding(0) , m_vtr_op(o.m_vtr_op) , m_vtr_op_tag(o.m_vtr_op_tag) { } const l2_binding::key_t& l2_binding::key() const { return (m_itf->key()); } bool l2_binding::operator==(const l2_binding& l) const { return ((*m_itf == *l.m_itf) && (*m_bd == *l.m_bd) && (m_port_type == l.m_port_type)); } std::shared_ptr<l2_binding> l2_binding::find(const key_t& key) { return (m_db.find(key)); } void l2_binding::sweep() { if (m_binding && handle_t::INVALID != m_itf->handle()) { HW::enqueue(new l2_binding_cmds::unbind_cmd(m_binding, m_itf->handle(), m_bd->id(), m_port_type)); } // no need to undo the VTR operation. HW::write(); } void l2_binding::replay() { if (m_binding && handle_t::INVALID != m_itf->handle()) { HW::enqueue(new l2_binding_cmds::bind_cmd(m_binding, m_itf->handle(), m_bd->id(), m_port_type)); } if (m_vtr_op && handle_t::INVALID != m_itf->handle()) { HW::enqueue( new l2_vtr_cmds::set_cmd(m_vtr_op, m_itf->handle(), m_vtr_op_tag)); } } l2_binding::~l2_binding() { sweep(); // not in the DB anymore. m_db.release(m_itf->key(), this); } std::string l2_binding::to_string() const { std::ostringstream s; s << "L2-binding:[" << m_itf->to_string() << " " << m_bd->to_string() << " " << m_port_type.to_string() << " " << m_binding.to_string() << "]"; return (s.str()); } void l2_binding::set(const l2_vtr::option_t& op, uint16_t tag) { assert(rc_t::UNSET == m_vtr_op.rc()); m_vtr_op.set(rc_t::NOOP); m_vtr_op.update(op); m_vtr_op_tag = tag; } void l2_binding::update(const l2_binding& desired) { /* * the desired state is always that the interface should be created */ if (rc_t::OK != m_binding.rc()) { HW::enqueue(new l2_binding_cmds::bind_cmd(m_binding, m_itf->handle(), m_bd->id(), m_port_type)); } else if (!(*m_bd == *desired.m_bd)) { /* * re-binding to a different BD. do unbind, bind. */ HW::enqueue(new l2_binding_cmds::unbind_cmd(m_binding, m_itf->handle(), m_bd->id(), m_port_type)); m_bd = desired.m_bd; HW::enqueue(new l2_binding_cmds::bind_cmd(m_binding, m_itf->handle(), m_bd->id(), m_port_type)); } /* * set the VTR operation if request */ if (m_vtr_op.update(desired.m_vtr_op)) { HW::enqueue( new l2_vtr_cmds::set_cmd(m_vtr_op, m_itf->handle(), m_vtr_op_tag)); } } std::shared_ptr<l2_binding> l2_binding::find_or_add(const l2_binding& temp) { return (m_db.find_or_add(temp.m_itf->key(), temp)); } std::shared_ptr<l2_binding> l2_binding::singular() const { return find_or_add(*this); } void l2_binding::dump(std::ostream& os) { db_dump(m_db, os); } l2_binding::event_handler::event_handler() { OM::register_listener(this); inspect::register_handler({ "l2" }, "L2 bindings", this); } void l2_binding::event_handler::handle_replay() { m_db.replay(); } void l2_binding::event_handler::handle_populate(const client_db::key_t& key) { /** * This is done while populating the bridge-domain */ } dependency_t l2_binding::event_handler::order() const { return (dependency_t::BINDING); } void l2_binding::event_handler::show(std::ostream& os) { db_dump(m_db, os); } } /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "mozilla") * End: */
23.946058
78
0.655346
[ "object" ]
3704be7ac17dbe7708df0d815f96f164ed7eb9e3
12,845
cpp
C++
examples/graph_shufflenet.cpp
tklebanoff/ComputeLibrary
d6c1eade8c36154ebfd2b61141f045fbc5112ea2
[ "MIT" ]
18
2019-09-05T01:25:16.000Z
2021-10-12T06:37:57.000Z
examples/graph_shufflenet.cpp
tklebanoff/ComputeLibrary
d6c1eade8c36154ebfd2b61141f045fbc5112ea2
[ "MIT" ]
10
2019-11-25T11:09:08.000Z
2021-12-20T12:56:32.000Z
examples/graph_shufflenet.cpp
tklebanoff/ComputeLibrary
d6c1eade8c36154ebfd2b61141f045fbc5112ea2
[ "MIT" ]
9
2019-09-05T04:46:59.000Z
2021-10-12T06:33:08.000Z
/* * Copyright (c) 2018-2019 ARM Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "arm_compute/graph.h" #include "support/ToolchainSupport.h" #include "utils/CommonGraphOptions.h" #include "utils/GraphUtils.h" #include "utils/Utils.h" using namespace arm_compute::utils; using namespace arm_compute::graph::frontend; using namespace arm_compute::graph_utils; /** Example demonstrating how to implement ShuffleNet network using the Compute Library's graph API */ class ShuffleNetExample : public Example { public: ShuffleNetExample() : cmd_parser(), common_opts(cmd_parser), common_params(), graph(0, "ShuffleNet") { } bool do_setup(int argc, char **argv) override { // Parse arguments cmd_parser.parse(argc, argv); // Consume common parameters common_params = consume_common_graph_parameters(common_opts); // Return when help menu is requested if(common_params.help) { cmd_parser.print_help(argv[0]); return false; } // Set default layout if needed (Single kernel grouped convolution not yet supported int NHWC) if(!common_opts.data_layout->is_set()) { common_params.data_layout = DataLayout::NHWC; } // Checks ARM_COMPUTE_EXIT_ON_MSG(arm_compute::is_data_type_quantized_asymmetric(common_params.data_type), "QASYMM8 not supported for this graph"); // Print parameter values std::cout << common_params << std::endl; std::cout << "Model: Shufflenet_1_g4" << std::endl; // Create model path std::string model_path = "/cnn_data/shufflenet_model/"; // Get trainable parameters data path std::string data_path = common_params.data_path; // Add model path to data path if(!data_path.empty()) { data_path += model_path; } // Create input descriptor const TensorShape tensor_shape = permute_shape(TensorShape(224U, 224U, 3U, 1U), DataLayout::NCHW, common_params.data_layout); TensorDescriptor input_descriptor = TensorDescriptor(tensor_shape, common_params.data_type).set_layout(common_params.data_layout); // Set weights trained layout const DataLayout weights_layout = DataLayout::NCHW; // Create preprocessor std::unique_ptr<IPreprocessor> preprocessor = arm_compute::support::cpp14::make_unique<TFPreproccessor>(0); graph << common_params.target << common_params.fast_math_hint << InputLayer(input_descriptor, get_input_accessor(common_params, std::move(preprocessor), false /* Do not convert to BGR */)) << ConvolutionLayer( 3U, 3U, 24U, get_weights_accessor(data_path, "conv3_0_w_0.npy", weights_layout), get_weights_accessor(data_path, "conv3_0_b_0.npy", weights_layout), PadStrideInfo(2, 2, 1, 1)) .set_name("Conv1/convolution") << BatchNormalizationLayer( get_weights_accessor(data_path, "conv3_0_bn_rm_0.npy"), get_weights_accessor(data_path, "conv3_0_bn_riv_0.npy"), get_weights_accessor(data_path, "conv3_0_bn_s_0.npy"), get_weights_accessor(data_path, "conv3_0_bn_b_0.npy"), 1e-5f) .set_name("Conv1/BatchNorm") << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name("Conv1/Relu") << PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 3, PadStrideInfo(2, 2, 1, 1))).set_name("pool1/MaxPool"); // Stage 2 add_residual_block(data_path, DataLayout::NCHW, 0U /* unit */, 112U /* depth */, 2U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 1U /* unit */, 136U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 2U /* unit */, 136U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 3U /* unit */, 136U /* depth */, 1U /* stride */); // Stage 3 add_residual_block(data_path, DataLayout::NCHW, 4U /* unit */, 136U /* depth */, 2U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 5U /* unit */, 272U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 6U /* unit */, 272U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 7U /* unit */, 272U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 8U /* unit */, 272U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 9U /* unit */, 272U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 10U /* unit */, 272U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 11U /* unit */, 272U /* depth */, 1U /* stride */); // Stage 4 add_residual_block(data_path, DataLayout::NCHW, 12U /* unit */, 272U /* depth */, 2U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 13U /* unit */, 544U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 14U /* unit */, 544U /* depth */, 1U /* stride */); add_residual_block(data_path, DataLayout::NCHW, 15U /* unit */, 544U /* depth */, 1U /* stride */); graph << PoolingLayer(PoolingLayerInfo(PoolingType::AVG)).set_name("predictions/AvgPool") << FlattenLayer().set_name("predictions/Reshape") << FullyConnectedLayer( 1000U, get_weights_accessor(data_path, "pred_w_0.npy", weights_layout), get_weights_accessor(data_path, "pred_b_0.npy")) .set_name("predictions/FC") << SoftmaxLayer().set_name("predictions/Softmax") << OutputLayer(get_output_accessor(common_params, 5)); // Finalize graph GraphConfig config; config.num_threads = common_params.threads; config.use_tuner = common_params.enable_tuner; config.tuner_mode = common_params.tuner_mode; config.tuner_file = common_params.tuner_file; graph.finalize(common_params.target, config); return true; } void do_run() override { // Run graph graph.run(); } private: CommandLineParser cmd_parser; CommonGraphOptions common_opts; CommonGraphParams common_params; Stream graph; void add_residual_block(const std::string &data_path, DataLayout weights_layout, unsigned int unit, unsigned int depth, unsigned int stride) { PadStrideInfo dwc_info = PadStrideInfo(1, 1, 1, 1); const unsigned int gconv_id = unit * 2; const unsigned int num_groups = 4; const std::string unit_id_name = arm_compute::support::cpp11::to_string(unit); const std::string gconv_id_name = arm_compute::support::cpp11::to_string(gconv_id); const std::string gconv_id_1_name = arm_compute::support::cpp11::to_string(gconv_id + 1); const std::string unit_name = "unit" + unit_id_name; SubStream left_ss(graph); SubStream right_ss(graph); if(stride == 2) { right_ss << PoolingLayer(PoolingLayerInfo(PoolingType::AVG, 3, PadStrideInfo(2, 2, 1, 1))).set_name(unit_name + "/pool_1/AveragePool"); dwc_info = PadStrideInfo(2, 2, 1, 1); } left_ss << ConvolutionLayer( 1U, 1U, depth, get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_w_0.npy", weights_layout), std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr), PadStrideInfo(1, 1, 0, 0), num_groups) .set_name(unit_name + "/gconv1_" + gconv_id_name + "/convolution") << BatchNormalizationLayer( get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_bn_rm_0.npy"), get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_bn_riv_0.npy"), get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_bn_s_0.npy"), get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_bn_b_0.npy"), 1e-5f) .set_name(unit_name + "/gconv1_" + gconv_id_name + "/BatchNorm") << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "/gconv1_" + gconv_id_name + "/Relu") << ChannelShuffleLayer(num_groups).set_name(unit_name + "/shuffle_0/ChannelShufle") << DepthwiseConvolutionLayer( 3U, 3U, get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_w_0.npy", weights_layout), std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr), dwc_info) .set_name(unit_name + "/gconv3_" + unit_id_name + "/depthwise") << BatchNormalizationLayer( get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_bn_rm_0.npy"), get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_bn_riv_0.npy"), get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_bn_s_0.npy"), get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_bn_b_0.npy"), 1e-5f) .set_name(unit_name + "/gconv3_" + unit_id_name + "/BatchNorm") << ConvolutionLayer( 1U, 1U, depth, get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_w_0.npy", weights_layout), std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr), PadStrideInfo(1, 1, 0, 0), num_groups) .set_name(unit_name + "/gconv1_" + gconv_id_1_name + "/convolution") << BatchNormalizationLayer( get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_bn_rm_0.npy"), get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_bn_riv_0.npy"), get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_bn_s_0.npy"), get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_bn_b_0.npy"), 1e-5f) .set_name(unit_name + "/gconv1_" + gconv_id_1_name + "/BatchNorm"); if(stride == 2) { graph << ConcatLayer(std::move(left_ss), std::move(right_ss)).set_name(unit_name + "/Concat"); } else { graph << EltwiseLayer(std::move(left_ss), std::move(right_ss), EltwiseOperation::Add).set_name(unit_name + "/Add"); } graph << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "/Relu"); } }; /** Main program for ShuffleNet * * Model is based on: * https://arxiv.org/abs/1707.01083 * "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices" * Xiangyu Zhang, Xinyu Zhou, Mengxiao Lin, Jian Sun * * Provenance: https://s3.amazonaws.com/download.onnx/models/opset_9/shufflenet.tar.gz * * @note To list all the possible arguments execute the binary appended with the --help option * * @param[in] argc Number of arguments * @param[in] argv Arguments */ int main(int argc, char **argv) { return arm_compute::utils::run_example<ShuffleNetExample>(argc, argv); }
49.594595
161
0.630284
[ "model" ]
3708fd01b0d8174615383d27007280fab27b2b98
3,567
cpp
C++
reefbot/src/reefbot_cascade_detector.cpp
MRSD2018/reefbot-1
a595ca718d0cda277726894a3105815cef000475
[ "MIT" ]
null
null
null
reefbot/src/reefbot_cascade_detector.cpp
MRSD2018/reefbot-1
a595ca718d0cda277726894a3105815cef000475
[ "MIT" ]
null
null
null
reefbot/src/reefbot_cascade_detector.cpp
MRSD2018/reefbot-1
a595ca718d0cda277726894a3105815cef000475
[ "MIT" ]
null
null
null
// ROS Node that wraps the OpenCV Haar Cascade Detector for object // detection for Reefbot usages // // Provides a service with reefbot_msgs::FindSpecies // // ROS Input Type: reefbot_msgs::ImageCaptured // ROS Output Type: reefbot_msgs::SpeciesIDResponse // // Author: Mark Desnoyer markd@cmu.edu // Date: May 2011 #include <vector> #include "ros/ros.h" #include "cascade_detector/cascade_detector.h" #include "reefbot_msgs/FindSpecies.h" #include "cascade_detector/DetectObject.h" #include "reefbot_msgs/SingleSpeciesId.h" #include "reefbot_msgs/SpeciesScore.h" using namespace std; using namespace ros; using namespace cascade_detector; using namespace reefbot_msgs; class HandleServiceRequest { public: HandleServiceRequest(CascadeDetector* client, int species_id) : client_(client), species_id_(species_id) {} bool operator()(reefbot_msgs::FindSpecies::Request& request, reefbot_msgs::FindSpecies::Response& response) { ROS_DEBUG("Processing request"); response.response.image_id = request.image.image_id; DetectObject detectObject; detectObject.request.image = request.image.image; if (client_->HandleServiceRequest(detectObject.request, detectObject.response)) { for (vector<cascade_detector::Detection>::const_iterator resultI = detectObject.response.detections.detections.begin(); resultI != detectObject.response.detections.detections.end(); resultI++) { SpeciesScore curScore; curScore.species_id = species_id_; curScore.score = resultI->score; curScore.meta_data = resultI->label; SingleSpeciesId curAnswer; curAnswer.bounding_box = resultI->mask.roi; curAnswer.best_species.push_back(curScore); response.response.answers.push_back(curAnswer); } } else { return false; } response.response.header.stamp = ros::Time::now(); return true; }; private: CascadeDetector* client_; int species_id_; }; int main(int argc, char** argv) { ros::init(argc, argv, "ReefbotCascadeDetector"); NodeHandle handle; // Get the node parameters string filename; string objectName; string imageTopic; string responseTopic; string serviceName; int species_id; NodeHandle local("~"); local.getParam("detector_filename", filename); local.param<string>("object_name", objectName, "face"); local.param<string>("request_topic", imageTopic, "detect_object_request"); local.param<string>("response_topic", responseTopic, "object_detection"); local.param<string>("service_name", serviceName, "detect_object"); local.param<int>("species_id", species_id, -1); string internalCVService = local.getNamespace()+'/'+serviceName; string internalCVRequest = local.getNamespace()+"/detect_object_request"; string internalCVResponse = local.getNamespace()+"/object_detection"; // Create the component that will do the open cv call cascade_detector::CascadeDetector node(filename, objectName); node.Init(internalCVRequest, internalCVResponse, internalCVService); // Now create a service handler that will provde the wrapper for Reefbot ROS_INFO_STREAM("Advertising service: " << serviceName); ServiceServer service = handle.advertiseService< reefbot_msgs::FindSpecies::Request, reefbot_msgs::FindSpecies::Response>( serviceName, HandleServiceRequest(&node, species_id)); ros::spin(); }
32.427273
76
0.704514
[ "object", "vector" ]
3709e807d3ee40dad4b2976582066dda61e6f796
89,294
cc
C++
media/engine/webrtcvoiceengine.cc
UWNetworksLab/webrtc-mod
5b910438baf4f7c7883996a2323d8ed809fd10e1
[ "DOC", "BSD-3-Clause" ]
1
2017-02-20T04:24:44.000Z
2017-02-20T04:24:44.000Z
media/engine/webrtcvoiceengine.cc
UWNetworksLab/webrtc-mod
5b910438baf4f7c7883996a2323d8ed809fd10e1
[ "DOC", "BSD-3-Clause" ]
null
null
null
media/engine/webrtcvoiceengine.cc
UWNetworksLab/webrtc-mod
5b910438baf4f7c7883996a2323d8ed809fd10e1
[ "DOC", "BSD-3-Clause" ]
1
2016-10-17T18:34:08.000Z
2016-10-17T18:34:08.000Z
/* * Copyright (c) 2004 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef HAVE_WEBRTC_VOICE #include "webrtc/media/engine/webrtcvoiceengine.h" #include <algorithm> #include <cstdio> #include <string> #include <vector> #include "webrtc/audio/audio_sink.h" #include "webrtc/base/arraysize.h" #include "webrtc/base/base64.h" #include "webrtc/base/byteorder.h" #include "webrtc/base/common.h" #include "webrtc/base/helpers.h" #include "webrtc/base/logging.h" #include "webrtc/base/stringencode.h" #include "webrtc/base/stringutils.h" #include "webrtc/call/rtc_event_log.h" #include "webrtc/common.h" #include "webrtc/media/base/audioframe.h" #include "webrtc/media/base/audiorenderer.h" #include "webrtc/media/base/constants.h" #include "webrtc/media/base/streamparams.h" #include "webrtc/media/engine/webrtcmediaengine.h" #include "webrtc/media/engine/webrtcvoe.h" #include "webrtc/modules/audio_coding/acm2/rent_a_codec.h" #include "webrtc/modules/audio_processing/include/audio_processing.h" #include "webrtc/system_wrappers/include/field_trial.h" #include "webrtc/system_wrappers/include/trace.h" namespace cricket { namespace { const int kDefaultTraceFilter = webrtc::kTraceNone | webrtc::kTraceTerseInfo | webrtc::kTraceWarning | webrtc::kTraceError | webrtc::kTraceCritical; const int kElevatedTraceFilter = kDefaultTraceFilter | webrtc::kTraceStateInfo | webrtc::kTraceInfo; // On Windows Vista and newer, Microsoft introduced the concept of "Default // Communications Device". This means that there are two types of default // devices (old Wave Audio style default and Default Communications Device). // // On Windows systems which only support Wave Audio style default, uses either // -1 or 0 to select the default device. #ifdef WIN32 const int kDefaultAudioDeviceId = -1; #else const int kDefaultAudioDeviceId = 0; #endif // Parameter used for NACK. // This value is equivalent to 5 seconds of audio data at 20 ms per packet. const int kNackMaxPackets = 250; // Codec parameters for Opus. // draft-spittka-payload-rtp-opus-03 // Recommended bitrates: // 8-12 kb/s for NB speech, // 16-20 kb/s for WB speech, // 28-40 kb/s for FB speech, // 48-64 kb/s for FB mono music, and // 64-128 kb/s for FB stereo music. // The current implementation applies the following values to mono signals, // and multiplies them by 2 for stereo. const int kOpusBitrateNb = 12000; const int kOpusBitrateWb = 20000; const int kOpusBitrateFb = 32000; // Opus bitrate should be in the range between 6000 and 510000. const int kOpusMinBitrate = 6000; const int kOpusMaxBitrate = 510000; // Default audio dscp value. // See http://tools.ietf.org/html/rfc2474 for details. // See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00 const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF; // Constants from voice_engine_defines.h. const int kMinTelephoneEventCode = 0; // RFC4733 (Section 2.3.1) const int kMaxTelephoneEventCode = 255; const int kMinTelephoneEventDuration = 100; const int kMaxTelephoneEventDuration = 60000; // Actual limit is 2^16 class ProxySink : public webrtc::AudioSinkInterface { public: ProxySink(AudioSinkInterface* sink) : sink_(sink) { RTC_DCHECK(sink); } void OnData(const Data& audio) override { sink_->OnData(audio); } private: webrtc::AudioSinkInterface* sink_; }; bool ValidateStreamParams(const StreamParams& sp) { if (sp.ssrcs.empty()) { LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString(); return false; } if (sp.ssrcs.size() > 1) { LOG(LS_ERROR) << "Multiple SSRCs in stream parameters: " << sp.ToString(); return false; } return true; } // Dumps an AudioCodec in RFC 2327-ish format. std::string ToString(const AudioCodec& codec) { std::stringstream ss; ss << codec.name << "/" << codec.clockrate << "/" << codec.channels << " (" << codec.id << ")"; return ss.str(); } std::string ToString(const webrtc::CodecInst& codec) { std::stringstream ss; ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels << " (" << codec.pltype << ")"; return ss.str(); } bool IsCodec(const AudioCodec& codec, const char* ref_name) { return (_stricmp(codec.name.c_str(), ref_name) == 0); } bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) { return (_stricmp(codec.plname, ref_name) == 0); } bool FindCodec(const std::vector<AudioCodec>& codecs, const AudioCodec& codec, AudioCodec* found_codec) { for (const AudioCodec& c : codecs) { if (c.Matches(codec)) { if (found_codec != NULL) { *found_codec = c; } return true; } } return false; } bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) { if (codecs.empty()) { return true; } std::vector<int> payload_types; for (const AudioCodec& codec : codecs) { payload_types.push_back(codec.id); } std::sort(payload_types.begin(), payload_types.end()); auto it = std::unique(payload_types.begin(), payload_types.end()); return it == payload_types.end(); } // Return true if codec.params[feature] == "1", false otherwise. bool IsCodecFeatureEnabled(const AudioCodec& codec, const char* feature) { int value; return codec.GetParam(feature, &value) && value == 1; } // Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate // otherwise. If the value (either from params or codec.bitrate) <=0, use the // default configuration. If the value is beyond feasible bit rate of Opus, // clamp it. Returns the Opus bit rate for operation. int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) { int bitrate = 0; bool use_param = true; if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) { bitrate = codec.bitrate; use_param = false; } if (bitrate <= 0) { if (max_playback_rate <= 8000) { bitrate = kOpusBitrateNb; } else if (max_playback_rate <= 16000) { bitrate = kOpusBitrateWb; } else { bitrate = kOpusBitrateFb; } if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) { bitrate *= 2; } } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) { bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate; std::string rate_source = use_param ? "Codec parameter \"maxaveragebitrate\"" : "Supplied Opus bitrate"; LOG(LS_WARNING) << rate_source << " is invalid and is replaced by: " << bitrate; } return bitrate; } // Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not // defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise. int GetOpusMaxPlaybackRate(const AudioCodec& codec) { int value; if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) { return value; } return kOpusDefaultMaxPlaybackRate; } void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec, bool* enable_codec_fec, int* max_playback_rate, bool* enable_codec_dtx) { *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec); *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx); *max_playback_rate = GetOpusMaxPlaybackRate(codec); // If OPUS, change what we send according to the "stereo" codec // parameter, and not the "channels" parameter. We set // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If // the bitrate is not specified, i.e. is <= zero, we set it to the // appropriate default value for mono or stereo Opus. voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1; voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate); } webrtc::AudioState::Config MakeAudioStateConfig(VoEWrapper* voe_wrapper) { webrtc::AudioState::Config config; config.voice_engine = voe_wrapper->engine(); return config; } class WebRtcVoiceCodecs final { public: // TODO(solenberg): Do this filtering once off-line, add a simple AudioCodec // list and add a test which verifies VoE supports the listed codecs. static std::vector<AudioCodec> SupportedCodecs() { LOG(LS_INFO) << "WebRtc VoiceEngine codecs:"; std::vector<AudioCodec> result; for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) { // Change the sample rate of G722 to 8000 to match SDP. MaybeFixupG722(&voe_codec, 8000); // Skip uncompressed formats. if (IsCodec(voe_codec, kL16CodecName)) { continue; } const CodecPref* pref = NULL; for (size_t j = 0; j < arraysize(kCodecPrefs); ++j) { if (IsCodec(voe_codec, kCodecPrefs[j].name) && kCodecPrefs[j].clockrate == voe_codec.plfreq && kCodecPrefs[j].channels == voe_codec.channels) { pref = &kCodecPrefs[j]; break; } } if (pref) { // Use the payload type that we've configured in our pref table; // use the offset in our pref table to determine the sort order. AudioCodec codec( pref->payload_type, voe_codec.plname, voe_codec.plfreq, voe_codec.rate, voe_codec.channels, static_cast<int>(arraysize(kCodecPrefs)) - (pref - kCodecPrefs)); LOG(LS_INFO) << ToString(codec); if (IsCodec(codec, kIsacCodecName)) { // Indicate auto-bitrate in signaling. codec.bitrate = 0; } if (IsCodec(codec, kOpusCodecName)) { // Only add fmtp parameters that differ from the spec. if (kPreferredMinPTime != kOpusDefaultMinPTime) { codec.params[kCodecParamMinPTime] = rtc::ToString(kPreferredMinPTime); } if (kPreferredMaxPTime != kOpusDefaultMaxPTime) { codec.params[kCodecParamMaxPTime] = rtc::ToString(kPreferredMaxPTime); } codec.SetParam(kCodecParamUseInbandFec, 1); codec.AddFeedbackParam( FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty)); // TODO(hellner): Add ptime, sprop-stereo, and stereo // when they can be set to values other than the default. } result.push_back(codec); } else { LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec); } } // Make sure they are in local preference order. std::sort(result.begin(), result.end(), &AudioCodec::Preferable); return result; } static bool ToCodecInst(const AudioCodec& in, webrtc::CodecInst* out) { for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) { // Change the sample rate of G722 to 8000 to match SDP. MaybeFixupG722(&voe_codec, 8000); AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq, voe_codec.rate, voe_codec.channels, 0); bool multi_rate = IsCodecMultiRate(voe_codec); // Allow arbitrary rates for ISAC to be specified. if (multi_rate) { // Set codec.bitrate to 0 so the check for codec.Matches() passes. codec.bitrate = 0; } if (codec.Matches(in)) { if (out) { // Fixup the payload type. voe_codec.pltype = in.id; // Set bitrate if specified. if (multi_rate && in.bitrate != 0) { voe_codec.rate = in.bitrate; } // Reset G722 sample rate to 16000 to match WebRTC. MaybeFixupG722(&voe_codec, 16000); // Apply codec-specific settings. if (IsCodec(codec, kIsacCodecName)) { // If ISAC and an explicit bitrate is not specified, // enable auto bitrate adjustment. voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1; } *out = voe_codec; } return true; } } return false; } static bool IsCodecMultiRate(const webrtc::CodecInst& codec) { for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) { if (IsCodec(codec, kCodecPrefs[i].name) && kCodecPrefs[i].clockrate == codec.plfreq) { return kCodecPrefs[i].is_multi_rate; } } return false; } // If the AudioCodec param kCodecParamPTime is set, then we will set it to // codec pacsize if it's valid, or we will pick the next smallest value we // support. // TODO(Brave): Query supported packet sizes from ACM when the API is ready. static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) { for (const CodecPref& codec_pref : kCodecPrefs) { if ((IsCodec(*codec, codec_pref.name) && codec_pref.clockrate == codec->plfreq) || IsCodec(*codec, kG722CodecName)) { int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms); if (packet_size_ms) { // Convert unit from milli-seconds to samples. codec->pacsize = (codec->plfreq / 1000) * packet_size_ms; return true; } } } return false; } static const AudioCodec* GetPreferredCodec( const std::vector<AudioCodec>& codecs, webrtc::CodecInst* voe_codec, int* red_payload_type) { RTC_DCHECK(voe_codec); RTC_DCHECK(red_payload_type); // Select the preferred send codec (the first non-telephone-event/CN codec). for (const AudioCodec& codec : codecs) { *red_payload_type = -1; if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) { // Skip telephone-event/CN codec, which will be handled later. continue; } // We'll use the first codec in the list to actually send audio data. // Be sure to use the payload type requested by the remote side. // "red", for RED audio, is a special case where the actual codec to be // used is specified in params. const AudioCodec* found_codec = &codec; if (IsCodec(*found_codec, kRedCodecName)) { // Parse out the RED parameters. If we fail, just ignore RED; // we don't support all possible params/usage scenarios. *red_payload_type = codec.id; found_codec = GetRedSendCodec(*found_codec, codecs); if (!found_codec) { continue; } } // Ignore codecs we don't know about. The negotiation step should prevent // this, but double-check to be sure. if (!ToCodecInst(*found_codec, voe_codec)) { LOG(LS_WARNING) << "Unknown codec " << ToString(*found_codec); continue; } return found_codec; } return nullptr; } private: static const int kMaxNumPacketSize = 6; struct CodecPref { const char* name; int clockrate; size_t channels; int payload_type; bool is_multi_rate; int packet_sizes_ms[kMaxNumPacketSize]; }; // Note: keep the supported packet sizes in ascending order. static const CodecPref kCodecPrefs[12]; static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) { int selected_packet_size_ms = codec_pref.packet_sizes_ms[0]; for (int packet_size_ms : codec_pref.packet_sizes_ms) { if (packet_size_ms && packet_size_ms <= ptime_ms) { selected_packet_size_ms = packet_size_ms; } } return selected_packet_size_ms; } // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC // which says that G722 should be advertised as 8 kHz although it is a 16 kHz // codec. static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) { if (IsCodec(*voe_codec, kG722CodecName)) { // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine // has changed, and this special case is no longer needed. RTC_DCHECK(voe_codec->plfreq != new_plfreq); voe_codec->plfreq = new_plfreq; } } static const AudioCodec* GetRedSendCodec( const AudioCodec& red_codec, const std::vector<AudioCodec>& all_codecs) { // Get the RED encodings from the parameter with no name. This may // change based on what is discussed on the Jingle list. // The encoding parameter is of the form "a/b"; we only support where // a == b. Verify this and parse out the value into red_pt. // If the parameter value is absent (as it will be until we wire up the // signaling of this message), use the second codec specified (i.e. the // one after "red") as the encoding parameter. int red_pt = -1; std::string red_params; CodecParameterMap::const_iterator it = red_codec.params.find(""); if (it != red_codec.params.end()) { red_params = it->second; std::vector<std::string> red_pts; if (rtc::split(red_params, '/', &red_pts) != 2 || red_pts[0] != red_pts[1] || !rtc::FromString(red_pts[0], &red_pt)) { LOG(LS_WARNING) << "RED params " << red_params << " not supported."; return nullptr; } } else if (red_codec.params.empty()) { LOG(LS_WARNING) << "RED params not present, using defaults"; if (all_codecs.size() > 1) { red_pt = all_codecs[1].id; } } // Try to find red_pt in |codecs|. for (const AudioCodec& codec : all_codecs) { if (codec.id == red_pt) { return &codec; } } LOG(LS_WARNING) << "RED params " << red_params << " are invalid."; return nullptr; } }; const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = { { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } }, { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } }, { kIsacCodecName, 32000, 1, 104, true, { 30 } }, // G722 should be advertised as 8000 Hz because of the RFC "bug". { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } }, { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } }, { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } }, { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } }, { kCnCodecName, 32000, 1, 106, false, { } }, { kCnCodecName, 16000, 1, 105, false, { } }, { kCnCodecName, 8000, 1, 13, false, { } }, { kRedCodecName, 8000, 1, 127, false, { } }, { kDtmfCodecName, 8000, 1, 126, false, { } }, }; } // namespace { bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in, webrtc::CodecInst* out) { return WebRtcVoiceCodecs::ToCodecInst(in, out); } WebRtcVoiceEngine::WebRtcVoiceEngine() : voe_wrapper_(new VoEWrapper()), audio_state_(webrtc::AudioState::Create(MakeAudioStateConfig(voe()))) { Construct(); } WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper) : voe_wrapper_(voe_wrapper) { Construct(); } void WebRtcVoiceEngine::Construct() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine"; signal_thread_checker_.DetachFromThread(); std::memset(&default_agc_config_, 0, sizeof(default_agc_config_)); voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true)); webrtc::Trace::set_level_filter(kDefaultTraceFilter); webrtc::Trace::SetTraceCallback(this); // Load our audio codec list. codecs_ = WebRtcVoiceCodecs::SupportedCodecs(); } WebRtcVoiceEngine::~WebRtcVoiceEngine() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine"; if (adm_) { voe_wrapper_.reset(); adm_->Release(); adm_ = NULL; } webrtc::Trace::SetTraceCallback(nullptr); } bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(worker_thread == rtc::Thread::Current()); LOG(LS_INFO) << "WebRtcVoiceEngine::Init"; bool res = InitInternal(); if (res) { LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!"; } else { LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed"; Terminate(); } return res; } bool WebRtcVoiceEngine::InitInternal() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Temporarily turn logging level up for the Init call webrtc::Trace::set_level_filter(kElevatedTraceFilter); LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString(); if (voe_wrapper_->base()->Init(adm_) == -1) { LOG_RTCERR0_EX(Init, voe_wrapper_->error()); return false; } webrtc::Trace::set_level_filter(kDefaultTraceFilter); // Save the default AGC configuration settings. This must happen before // calling ApplyOptions or the default will be overwritten. if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) { LOG_RTCERR0(GetAgcConfig); return false; } // Set default engine options. { AudioOptions options; options.echo_cancellation = rtc::Optional<bool>(true); options.auto_gain_control = rtc::Optional<bool>(true); options.noise_suppression = rtc::Optional<bool>(true); options.highpass_filter = rtc::Optional<bool>(true); options.stereo_swapping = rtc::Optional<bool>(false); options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50); options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false); options.typing_detection = rtc::Optional<bool>(true); options.adjust_agc_delta = rtc::Optional<int>(0); options.experimental_agc = rtc::Optional<bool>(false); options.extended_filter_aec = rtc::Optional<bool>(false); options.delay_agnostic_aec = rtc::Optional<bool>(false); options.experimental_ns = rtc::Optional<bool>(false); if (!ApplyOptions(options)) { return false; } } // Print our codec list again for the call diagnostic log LOG(LS_INFO) << "WebRtc VoiceEngine codecs:"; for (const AudioCodec& codec : codecs_) { LOG(LS_INFO) << ToString(codec); } SetDefaultDevices(); initialized_ = true; return true; } void WebRtcVoiceEngine::Terminate() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate"; initialized_ = false; StopAecDump(); voe_wrapper_->base()->Terminate(); } rtc::scoped_refptr<webrtc::AudioState> WebRtcVoiceEngine::GetAudioState() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return audio_state_; } VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel( webrtc::Call* call, const MediaConfig& config, const AudioOptions& options) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return new WebRtcVoiceMediaChannel(this, config, options, call); } bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "ApplyOptions: " << options_in.ToString(); AudioOptions options = options_in; // The options are modified below. // kEcConference is AEC with high suppression. webrtc::EcModes ec_mode = webrtc::kEcConference; webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone; webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog; webrtc::NsModes ns_mode = webrtc::kNsHighSuppression; if (options.aecm_generate_comfort_noise) { LOG(LS_VERBOSE) << "Comfort noise explicitly set to " << *options.aecm_generate_comfort_noise << " (default is false)."; } #if defined(WEBRTC_IOS) // On iOS, VPIO provides built-in EC and AGC. options.echo_cancellation = rtc::Optional<bool>(false); options.auto_gain_control = rtc::Optional<bool>(false); LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead."; #elif defined(ANDROID) ec_mode = webrtc::kEcAecm; #endif #if defined(WEBRTC_IOS) || defined(ANDROID) // Set the AGC mode for iOS as well despite disabling it above, to avoid // unsupported configuration errors from webrtc. agc_mode = webrtc::kAgcFixedDigital; options.typing_detection = rtc::Optional<bool>(false); options.experimental_agc = rtc::Optional<bool>(false); options.extended_filter_aec = rtc::Optional<bool>(false); options.experimental_ns = rtc::Optional<bool>(false); #endif // Delay Agnostic AEC automatically turns on EC if not set except on iOS // where the feature is not supported. bool use_delay_agnostic_aec = false; #if !defined(WEBRTC_IOS) if (options.delay_agnostic_aec) { use_delay_agnostic_aec = *options.delay_agnostic_aec; if (use_delay_agnostic_aec) { options.echo_cancellation = rtc::Optional<bool>(true); options.extended_filter_aec = rtc::Optional<bool>(true); ec_mode = webrtc::kEcConference; } } #endif webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing(); if (options.echo_cancellation) { // Check if platform supports built-in EC. Currently only supported on // Android and in combination with Java based audio layer. // TODO(henrika): investigate possibility to support built-in EC also // in combination with Open SL ES audio. const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable(); if (built_in_aec) { // Built-in EC exists on this device and use_delay_agnostic_aec is not // overriding it. Enable/Disable it according to the echo_cancellation // audio option. const bool enable_built_in_aec = *options.echo_cancellation && !use_delay_agnostic_aec; if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 && enable_built_in_aec) { // Disable internal software EC if built-in EC is enabled, // i.e., replace the software EC with the built-in EC. options.echo_cancellation = rtc::Optional<bool>(false); LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead"; } } if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) { LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode); return false; } else { LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation << " with mode " << ec_mode; } #if !defined(ANDROID) // TODO(ajm): Remove the error return on Android from webrtc. if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) { LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation); return false; } #endif if (ec_mode == webrtc::kEcAecm) { bool cn = options.aecm_generate_comfort_noise.value_or(false); if (voep->SetAecmMode(aecm_mode, cn) != 0) { LOG_RTCERR2(SetAecmMode, aecm_mode, cn); return false; } } } if (options.auto_gain_control) { const bool built_in_agc = voe_wrapper_->hw()->BuiltInAGCIsAvailable(); if (built_in_agc) { if (voe_wrapper_->hw()->EnableBuiltInAGC(*options.auto_gain_control) == 0 && *options.auto_gain_control) { // Disable internal software AGC if built-in AGC is enabled, // i.e., replace the software AGC with the built-in AGC. options.auto_gain_control = rtc::Optional<bool>(false); LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead"; } } if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) { LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode); return false; } else { LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control << " with mode " << agc_mode; } } if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain || options.tx_agc_limiter) { // Override default_agc_config_. Generally, an unset option means "leave // the VoE bits alone" in this function, so we want whatever is set to be // stored as the new "default". If we didn't, then setting e.g. // tx_agc_target_dbov would reset digital compression gain and limiter // settings. // Also, if we don't update default_agc_config_, then adjust_agc_delta // would be an offset from the original values, and not whatever was set // explicitly. default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or( default_agc_config_.targetLeveldBOv); default_agc_config_.digitalCompressionGaindB = options.tx_agc_digital_compression_gain.value_or( default_agc_config_.digitalCompressionGaindB); default_agc_config_.limiterEnable = options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable); if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) { LOG_RTCERR3(SetAgcConfig, default_agc_config_.targetLeveldBOv, default_agc_config_.digitalCompressionGaindB, default_agc_config_.limiterEnable); return false; } } if (options.noise_suppression) { const bool built_in_ns = voe_wrapper_->hw()->BuiltInNSIsAvailable(); if (built_in_ns) { if (voe_wrapper_->hw()->EnableBuiltInNS(*options.noise_suppression) == 0 && *options.noise_suppression) { // Disable internal software NS if built-in NS is enabled, // i.e., replace the software NS with the built-in NS. options.noise_suppression = rtc::Optional<bool>(false); LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead"; } } if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) { LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode); return false; } else { LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression << " with mode " << ns_mode; } } if (options.highpass_filter) { LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter; if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) { LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter); return false; } } if (options.stereo_swapping) { LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping; voep->EnableStereoChannelSwapping(*options.stereo_swapping); if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) { LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping); return false; } } if (options.audio_jitter_buffer_max_packets) { LOG(LS_INFO) << "NetEq capacity is " << *options.audio_jitter_buffer_max_packets; voe_config_.Set<webrtc::NetEqCapacityConfig>( new webrtc::NetEqCapacityConfig( *options.audio_jitter_buffer_max_packets)); } if (options.audio_jitter_buffer_fast_accelerate) { LOG(LS_INFO) << "NetEq fast mode? " << *options.audio_jitter_buffer_fast_accelerate; voe_config_.Set<webrtc::NetEqFastAccelerate>( new webrtc::NetEqFastAccelerate( *options.audio_jitter_buffer_fast_accelerate)); } if (options.typing_detection) { LOG(LS_INFO) << "Typing detection is enabled? " << *options.typing_detection; if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) { // In case of error, log the info and continue LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection); } } if (options.adjust_agc_delta) { LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta; if (!AdjustAgcLevel(*options.adjust_agc_delta)) { return false; } } webrtc::Config config; if (options.delay_agnostic_aec) delay_agnostic_aec_ = options.delay_agnostic_aec; if (delay_agnostic_aec_) { LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_; config.Set<webrtc::DelayAgnostic>( new webrtc::DelayAgnostic(*delay_agnostic_aec_)); } if (options.extended_filter_aec) { extended_filter_aec_ = options.extended_filter_aec; } if (extended_filter_aec_) { LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_; config.Set<webrtc::ExtendedFilter>( new webrtc::ExtendedFilter(*extended_filter_aec_)); } if (options.experimental_ns) { experimental_ns_ = options.experimental_ns; } if (experimental_ns_) { LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_; config.Set<webrtc::ExperimentalNs>( new webrtc::ExperimentalNs(*experimental_ns_)); } // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine // returns NULL on audio_processing(). webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing(); if (audioproc) { audioproc->SetExtraOptions(config); } if (options.recording_sample_rate) { LOG(LS_INFO) << "Recording sample rate is " << *options.recording_sample_rate; if (voe_wrapper_->hw()->SetRecordingSampleRate( *options.recording_sample_rate)) { LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate); } } if (options.playout_sample_rate) { LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate; if (voe_wrapper_->hw()->SetPlayoutSampleRate( *options.playout_sample_rate)) { LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate); } } return true; } void WebRtcVoiceEngine::SetDefaultDevices() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); #if !defined(WEBRTC_IOS) int in_id = kDefaultAudioDeviceId; int out_id = kDefaultAudioDeviceId; LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ") and speaker to (id=" << out_id << ")"; bool ret = true; if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) { LOG_RTCERR1(SetRecordingDevice, in_id); ret = false; } webrtc::AudioProcessing* ap = voe()->base()->audio_processing(); if (ap) { ap->Initialize(); } if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) { LOG_RTCERR1(SetPlayoutDevice, out_id); ret = false; } if (ret) { LOG(LS_INFO) << "Set microphone to (id=" << in_id << ") and speaker to (id=" << out_id << ")"; } #endif // !WEBRTC_IOS } bool WebRtcVoiceEngine::GetOutputVolume(int* level) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); unsigned int ulevel; if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) { LOG_RTCERR1(GetSpeakerVolume, level); return false; } *level = ulevel; return true; } bool WebRtcVoiceEngine::SetOutputVolume(int level) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(level >= 0 && level <= 255); if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) { LOG_RTCERR1(SetSpeakerVolume, level); return false; } return true; } int WebRtcVoiceEngine::GetInputLevel() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); unsigned int ulevel; return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ? static_cast<int>(ulevel) : -1; } const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() { RTC_DCHECK(signal_thread_checker_.CalledOnValidThread()); return codecs_; } RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const { RTC_DCHECK(signal_thread_checker_.CalledOnValidThread()); RtpCapabilities capabilities; capabilities.header_extensions.push_back(RtpHeaderExtension( kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId)); capabilities.header_extensions.push_back( RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension, kRtpAbsoluteSenderTimeHeaderExtensionDefaultId)); if (webrtc::field_trial::FindFullName("WebRTC-Audio-SendSideBwe") == "Enabled") { capabilities.header_extensions.push_back(RtpHeaderExtension( kRtpTransportSequenceNumberHeaderExtension, kRtpTransportSequenceNumberHeaderExtensionDefaultId)); } return capabilities; } int WebRtcVoiceEngine::GetLastEngineError() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return voe_wrapper_->error(); } void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace, int length) { // Note: This callback can happen on any thread! rtc::LoggingSeverity sev = rtc::LS_VERBOSE; if (level == webrtc::kTraceError || level == webrtc::kTraceCritical) sev = rtc::LS_ERROR; else if (level == webrtc::kTraceWarning) sev = rtc::LS_WARNING; else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo) sev = rtc::LS_INFO; else if (level == webrtc::kTraceTerseInfo) sev = rtc::LS_INFO; // Skip past boilerplate prefix text if (length < 72) { std::string msg(trace, length); LOG(LS_ERROR) << "Malformed webrtc log message: "; LOG_V(sev) << msg; } else { std::string msg(trace + 71, length - 72); LOG_V(sev) << "webrtc: " << msg; } } void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(channel); channels_.push_back(channel); } void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); auto it = std::find(channels_.begin(), channels_.end(), channel); RTC_DCHECK(it != channels_.end()); channels_.erase(it); } // Adjusts the default AGC target level by the specified delta. // NB: If we start messing with other config fields, we'll want // to save the current webrtc::AgcConfig as well. bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); webrtc::AgcConfig config = default_agc_config_; config.targetLeveldBOv -= delta; LOG(LS_INFO) << "Adjusting AGC level from default -" << default_agc_config_.targetLeveldBOv << "dB to -" << config.targetLeveldBOv << "dB"; if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) { LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv); return false; } return true; } bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); if (initialized_) { LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init."; return false; } if (adm_) { adm_->Release(); adm_ = NULL; } if (adm) { adm_ = adm; adm_->AddRef(); } return true; } bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file, int64_t max_size_bytes) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file); if (!aec_dump_file_stream) { LOG(LS_ERROR) << "Could not open AEC dump file stream."; if (!rtc::ClosePlatformFile(file)) LOG(LS_WARNING) << "Could not close file."; return false; } StopAecDump(); if (voe_wrapper_->base()->audio_processing()->StartDebugRecording( aec_dump_file_stream, max_size_bytes) != webrtc::AudioProcessing::kNoError) { LOG_RTCERR0(StartDebugRecording); fclose(aec_dump_file_stream); return false; } is_dumping_aec_ = true; return true; } void WebRtcVoiceEngine::StartAecDump(const std::string& filename) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); if (!is_dumping_aec_) { // Start dumping AEC when we are not dumping. if (voe_wrapper_->base()->audio_processing()->StartDebugRecording( filename.c_str(), -1) != webrtc::AudioProcessing::kNoError) { LOG_RTCERR1(StartDebugRecording, filename.c_str()); } else { is_dumping_aec_ = true; } } } void WebRtcVoiceEngine::StopAecDump() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); if (is_dumping_aec_) { // Stop dumping AEC when we are dumping. if (voe_wrapper_->base()->audio_processing()->StopDebugRecording() != webrtc::AudioProcessing::kNoError) { LOG_RTCERR0(StopDebugRecording); } is_dumping_aec_ = false; } } bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog(); if (event_log) { return event_log->StartLogging(file); } LOG_RTCERR0(StartRtcEventLog); return false; } void WebRtcVoiceEngine::StopRtcEventLog() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog(); if (event_log) { event_log->StopLogging(); return; } LOG_RTCERR0(StopRtcEventLog); } int WebRtcVoiceEngine::CreateVoEChannel() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return voe_wrapper_->base()->CreateChannel(voe_config_); } class WebRtcVoiceMediaChannel::WebRtcAudioSendStream : public AudioRenderer::Sink { public: WebRtcAudioSendStream(int ch, webrtc::AudioTransport* voe_audio_transport, uint32_t ssrc, const std::string& c_name, const std::vector<webrtc::RtpExtension>& extensions, webrtc::Call* call) : voe_audio_transport_(voe_audio_transport), call_(call), config_(nullptr) { RTC_DCHECK_GE(ch, 0); // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore: // RTC_DCHECK(voe_audio_transport); RTC_DCHECK(call); audio_capture_thread_checker_.DetachFromThread(); config_.rtp.ssrc = ssrc; config_.rtp.c_name = c_name; config_.voe_channel_id = ch; RecreateAudioSendStream(extensions); } ~WebRtcAudioSendStream() override { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); Stop(); call_->DestroyAudioSendStream(stream_); } void RecreateAudioSendStream( const std::vector<webrtc::RtpExtension>& extensions) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); if (stream_) { call_->DestroyAudioSendStream(stream_); stream_ = nullptr; } config_.rtp.extensions = extensions; RTC_DCHECK(!stream_); stream_ = call_->CreateAudioSendStream(config_); RTC_CHECK(stream_); } bool SendTelephoneEvent(int payload_type, uint8_t event, uint32_t duration_ms) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(stream_); return stream_->SendTelephoneEvent(payload_type, event, duration_ms); } webrtc::AudioSendStream::Stats GetStats() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(stream_); return stream_->GetStats(); } // Starts the rendering by setting a sink to the renderer to get data // callback. // This method is called on the libjingle worker thread. // TODO(xians): Make sure Start() is called only once. void Start(AudioRenderer* renderer) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(renderer); if (renderer_) { RTC_DCHECK(renderer_ == renderer); return; } renderer->SetSink(this); renderer_ = renderer; } // Stops rendering by setting the sink of the renderer to nullptr. No data // callback will be received after this method. // This method is called on the libjingle worker thread. void Stop() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); if (renderer_) { renderer_->SetSink(nullptr); renderer_ = nullptr; } } // AudioRenderer::Sink implementation. // This method is called on the audio thread. void OnData(const void* audio_data, int bits_per_sample, int sample_rate, size_t number_of_channels, size_t number_of_frames) override { RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread()); RTC_DCHECK(voe_audio_transport_); voe_audio_transport_->OnData(config_.voe_channel_id, audio_data, bits_per_sample, sample_rate, number_of_channels, number_of_frames); } // Callback from the |renderer_| when it is going away. In case Start() has // never been called, this callback won't be triggered. void OnClose() override { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Set |renderer_| to nullptr to make sure no more callback will get into // the renderer. renderer_ = nullptr; } // Accessor to the VoE channel ID. int channel() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return config_.voe_channel_id; } private: rtc::ThreadChecker worker_thread_checker_; rtc::ThreadChecker audio_capture_thread_checker_; webrtc::AudioTransport* const voe_audio_transport_ = nullptr; webrtc::Call* call_ = nullptr; webrtc::AudioSendStream::Config config_; // The stream is owned by WebRtcAudioSendStream and may be reallocated if // configuration changes. webrtc::AudioSendStream* stream_ = nullptr; // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler. // PeerConnection will make sure invalidating the pointer before the object // goes away. AudioRenderer* renderer_ = nullptr; RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream); }; class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream { public: WebRtcAudioReceiveStream(int ch, uint32_t remote_ssrc, uint32_t local_ssrc, bool use_transport_cc, const std::string& sync_group, const std::vector<webrtc::RtpExtension>& extensions, webrtc::Call* call) : call_(call), config_() { RTC_DCHECK_GE(ch, 0); RTC_DCHECK(call); config_.rtp.remote_ssrc = remote_ssrc; config_.rtp.local_ssrc = local_ssrc; config_.voe_channel_id = ch; config_.sync_group = sync_group; RecreateAudioReceiveStream(use_transport_cc, extensions); } ~WebRtcAudioReceiveStream() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); call_->DestroyAudioReceiveStream(stream_); } void RecreateAudioReceiveStream( const std::vector<webrtc::RtpExtension>& extensions) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RecreateAudioReceiveStream(config_.rtp.transport_cc, extensions); } void RecreateAudioReceiveStream(bool use_transport_cc) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RecreateAudioReceiveStream(use_transport_cc, config_.rtp.extensions); } webrtc::AudioReceiveStream::Stats GetStats() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(stream_); return stream_->GetStats(); } int channel() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return config_.voe_channel_id; } void SetRawAudioSink(rtc::scoped_ptr<webrtc::AudioSinkInterface> sink) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); stream_->SetSink(rtc::ScopedToUnique(std::move(sink))); } private: void RecreateAudioReceiveStream( bool use_transport_cc, const std::vector<webrtc::RtpExtension>& extensions) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); if (stream_) { call_->DestroyAudioReceiveStream(stream_); stream_ = nullptr; } config_.rtp.extensions = extensions; config_.rtp.transport_cc = use_transport_cc; RTC_DCHECK(!stream_); stream_ = call_->CreateAudioReceiveStream(config_); RTC_CHECK(stream_); } rtc::ThreadChecker worker_thread_checker_; webrtc::Call* call_ = nullptr; webrtc::AudioReceiveStream::Config config_; // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if // configuration changes. webrtc::AudioReceiveStream* stream_ = nullptr; RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream); }; WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine, const MediaConfig& config, const AudioOptions& options, webrtc::Call* call) : VoiceMediaChannel(config), engine_(engine), call_(call) { LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel"; RTC_DCHECK(call); engine->RegisterChannel(this); SetOptions(options); } WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel"; // TODO(solenberg): Should be able to delete the streams directly, without // going through RemoveNnStream(), once stream objects handle // all (de)configuration. while (!send_streams_.empty()) { RemoveSendStream(send_streams_.begin()->first); } while (!recv_streams_.empty()) { RemoveRecvStream(recv_streams_.begin()->first); } engine()->UnregisterChannel(this); } rtc::DiffServCodePoint WebRtcVoiceMediaChannel::PreferredDscp() const { return kAudioDscpValue; } bool WebRtcVoiceMediaChannel::SetSendParameters( const AudioSendParameters& params) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: " << params.ToString(); // TODO(pthatcher): Refactor this to be more clean now that we have // all the information at once. if (!SetSendCodecs(params.codecs)) { return false; } if (!ValidateRtpExtensions(params.extensions)) { return false; } std::vector<webrtc::RtpExtension> filtered_extensions = FilterRtpExtensions(params.extensions, webrtc::RtpExtension::IsSupportedForAudio, true); if (send_rtp_extensions_ != filtered_extensions) { send_rtp_extensions_.swap(filtered_extensions); for (auto& it : send_streams_) { it.second->RecreateAudioSendStream(send_rtp_extensions_); } } if (!SetMaxSendBandwidth(params.max_bandwidth_bps)) { return false; } return SetOptions(params.options); } bool WebRtcVoiceMediaChannel::SetRecvParameters( const AudioRecvParameters& params) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: " << params.ToString(); // TODO(pthatcher): Refactor this to be more clean now that we have // all the information at once. if (!SetRecvCodecs(params.codecs)) { return false; } if (!ValidateRtpExtensions(params.extensions)) { return false; } std::vector<webrtc::RtpExtension> filtered_extensions = FilterRtpExtensions(params.extensions, webrtc::RtpExtension::IsSupportedForAudio, false); if (recv_rtp_extensions_ != filtered_extensions) { recv_rtp_extensions_.swap(filtered_extensions); for (auto& it : recv_streams_) { it.second->RecreateAudioReceiveStream(recv_rtp_extensions_); } } return true; } bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "Setting voice channel options: " << options.ToString(); // We retain all of the existing options, and apply the given ones // on top. This means there is no way to "clear" options such that // they go back to the engine default. options_.SetAll(options); if (!engine()->ApplyOptions(options_)) { LOG(LS_WARNING) << "Failed to apply engine options during channel SetOptions."; return false; } LOG(LS_INFO) << "Set voice channel options. Current options: " << options_.ToString(); return true; } bool WebRtcVoiceMediaChannel::SetRecvCodecs( const std::vector<AudioCodec>& codecs) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Set the payload types to be used for incoming media. LOG(LS_INFO) << "Setting receive voice codecs."; if (!VerifyUniquePayloadTypes(codecs)) { LOG(LS_ERROR) << "Codec payload types overlap."; return false; } std::vector<AudioCodec> new_codecs; // Find all new codecs. We allow adding new codecs but don't allow changing // the payload type of codecs that is already configured since we might // already be receiving packets with that payload type. for (const AudioCodec& codec : codecs) { AudioCodec old_codec; if (FindCodec(recv_codecs_, codec, &old_codec)) { if (old_codec.id != codec.id) { LOG(LS_ERROR) << codec.name << " payload type changed."; return false; } } else { new_codecs.push_back(codec); } } if (new_codecs.empty()) { // There are no new codecs to configure. Already configured codecs are // never removed. return true; } if (playout_) { // Receive codecs can not be changed while playing. So we temporarily // pause playout. PausePlayout(); } bool result = true; for (const AudioCodec& codec : new_codecs) { webrtc::CodecInst voe_codec; if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) { LOG(LS_INFO) << ToString(codec); voe_codec.pltype = codec.id; for (const auto& ch : recv_streams_) { if (engine()->voe()->codec()->SetRecPayloadType( ch.second->channel(), voe_codec) == -1) { LOG_RTCERR2(SetRecPayloadType, ch.second->channel(), ToString(voe_codec)); result = false; } } } else { LOG(LS_WARNING) << "Unknown codec " << ToString(codec); result = false; break; } } if (result) { recv_codecs_ = codecs; } if (desired_playout_ && !playout_) { ResumePlayout(); } return result; } bool WebRtcVoiceMediaChannel::SetSendCodecs( int channel, const std::vector<AudioCodec>& codecs) { // Disable VAD, FEC, and RED unless we know the other side wants them. engine()->voe()->codec()->SetVADStatus(channel, false); engine()->voe()->rtp()->SetNACKStatus(channel, false, 0); engine()->voe()->rtp()->SetREDStatus(channel, false); engine()->voe()->codec()->SetFECStatus(channel, false); // Scan through the list to figure out the codec to use for sending, along // with the proper configuration for VAD. webrtc::CodecInst send_codec; memset(&send_codec, 0, sizeof(send_codec)); bool nack_enabled = nack_enabled_; bool enable_codec_fec = false; bool enable_opus_dtx = false; int opus_max_playback_rate = 0; int red_payload_type = -1; // Set send codec (the first non-telephone-event/CN codec) const AudioCodec* codec = WebRtcVoiceCodecs::GetPreferredCodec( codecs, &send_codec, &red_payload_type); if (codec) { if (red_payload_type != -1) { // Enable redundant encoding of the specified codec. Treat any // failure as a fatal internal error. LOG(LS_INFO) << "Enabling RED on channel " << channel; if (engine()->voe()->rtp()->SetREDStatus(channel, true, red_payload_type) == -1) { LOG_RTCERR3(SetREDStatus, channel, true, red_payload_type); return false; } } else { nack_enabled = HasNack(*codec); // For Opus as the send codec, we are to determine inband FEC, maximum // playback rate, and opus internal dtx. if (IsCodec(*codec, kOpusCodecName)) { GetOpusConfig(*codec, &send_codec, &enable_codec_fec, &opus_max_playback_rate, &enable_opus_dtx); } // Set packet size if the AudioCodec param kCodecParamPTime is set. int ptime_ms = 0; if (codec->GetParam(kCodecParamPTime, &ptime_ms)) { if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(&send_codec, ptime_ms)) { LOG(LS_WARNING) << "Failed to set packet size for codec " << send_codec.plname; return false; } } } } if (nack_enabled_ != nack_enabled) { SetNack(channel, nack_enabled); nack_enabled_ = nack_enabled; } if (!codec) { LOG(LS_WARNING) << "Received empty list of codecs."; return false; } // Set the codec immediately, since SetVADStatus() depends on whether // the current codec is mono or stereo. if (!SetSendCodec(channel, send_codec)) return false; // FEC should be enabled after SetSendCodec. if (enable_codec_fec) { LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel " << channel; if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) { // Enable codec internal FEC. Treat any failure as fatal internal error. LOG_RTCERR2(SetFECStatus, channel, true); return false; } } if (IsCodec(send_codec, kOpusCodecName)) { // DTX and maxplaybackrate should be set after SetSendCodec. Because current // send codec has to be Opus. // Set Opus internal DTX. LOG(LS_INFO) << "Attempt to " << (enable_opus_dtx ? "enable" : "disable") << " Opus DTX on channel " << channel; if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) { LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx); return false; } // If opus_max_playback_rate <= 0, the default maximum playback rate // (48 kHz) will be used. if (opus_max_playback_rate > 0) { LOG(LS_INFO) << "Attempt to set maximum playback rate to " << opus_max_playback_rate << " Hz on channel " << channel; if (engine()->voe()->codec()->SetOpusMaxPlaybackRate( channel, opus_max_playback_rate) == -1) { LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate); return false; } } } // Always update the |send_codec_| to the currently set send codec. send_codec_.reset(new webrtc::CodecInst(send_codec)); if (send_bitrate_setting_) { SetSendBitrateInternal(send_bitrate_bps_); } // Loop through the codecs list again to config the CN codec. for (const AudioCodec& codec : codecs) { // Ignore codecs we don't know about. The negotiation step should prevent // this, but double-check to be sure. webrtc::CodecInst voe_codec; if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) { LOG(LS_WARNING) << "Unknown codec " << ToString(codec); continue; } if (IsCodec(codec, kCnCodecName)) { // Turn voice activity detection/comfort noise on if supported. // Set the wideband CN payload type appropriately. // (narrowband always uses the static payload type 13). webrtc::PayloadFrequencies cn_freq; switch (codec.clockrate) { case 8000: cn_freq = webrtc::kFreq8000Hz; break; case 16000: cn_freq = webrtc::kFreq16000Hz; break; case 32000: cn_freq = webrtc::kFreq32000Hz; break; default: LOG(LS_WARNING) << "CN frequency " << codec.clockrate << " not supported."; continue; } // Set the CN payloadtype and the VAD status. // The CN payload type for 8000 Hz clockrate is fixed at 13. if (cn_freq != webrtc::kFreq8000Hz) { if (engine()->voe()->codec()->SetSendCNPayloadType( channel, codec.id, cn_freq) == -1) { LOG_RTCERR3(SetSendCNPayloadType, channel, codec.id, cn_freq); // TODO(ajm): This failure condition will be removed from VoE. // Restore the return here when we update to a new enough webrtc. // // Not returning false because the SetSendCNPayloadType will fail if // the channel is already sending. // This can happen if the remote description is applied twice, for // example in the case of ROAP on top of JSEP, where both side will // send the offer. } } // Only turn on VAD if we have a CN payload type that matches the // clockrate for the codec we are going to use. if (codec.clockrate == send_codec.plfreq && send_codec.channels != 2) { // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the // interaction between VAD and Opus FEC. LOG(LS_INFO) << "Enabling VAD"; if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) { LOG_RTCERR2(SetVADStatus, channel, true); return false; } } } } return true; } bool WebRtcVoiceMediaChannel::SetSendCodecs( const std::vector<AudioCodec>& codecs) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // TODO(solenberg): Validate input - that payload types don't overlap, are // within range, filter out codecs we don't support, // redundant codecs etc. // Find the DTMF telephone event "codec" payload type. dtmf_payload_type_ = rtc::Optional<int>(); for (const AudioCodec& codec : codecs) { if (IsCodec(codec, kDtmfCodecName)) { dtmf_payload_type_ = rtc::Optional<int>(codec.id); break; } } // Cache the codecs in order to configure the channel created later. send_codecs_ = codecs; for (const auto& ch : send_streams_) { if (!SetSendCodecs(ch.second->channel(), codecs)) { return false; } } // Set nack status on receive channels and update |nack_enabled_|. for (const auto& ch : recv_streams_) { SetNack(ch.second->channel(), nack_enabled_); } // Check if the transport cc feedback has changed on the preferred send codec, // and in that case reconfigure all receive streams. webrtc::CodecInst voe_codec; int red_payload_type; const AudioCodec* send_codec = WebRtcVoiceCodecs::GetPreferredCodec( send_codecs_, &voe_codec, &red_payload_type); if (send_codec) { bool transport_cc = HasTransportCc(*send_codec); if (transport_cc_enabled_ != transport_cc) { LOG(LS_INFO) << "Recreate all the receive streams because the send " "codec has changed."; transport_cc_enabled_ = transport_cc; for (auto& kv : recv_streams_) { RTC_DCHECK(kv.second != nullptr); kv.second->RecreateAudioReceiveStream(transport_cc_enabled_); } } } return true; } void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) { if (nack_enabled) { LOG(LS_INFO) << "Enabling NACK for channel " << channel; engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets); } else { LOG(LS_INFO) << "Disabling NACK for channel " << channel; engine()->voe()->rtp()->SetNACKStatus(channel, false, 0); } } bool WebRtcVoiceMediaChannel::SetSendCodec( int channel, const webrtc::CodecInst& send_codec) { LOG(LS_INFO) << "Send channel " << channel << " selected voice codec " << ToString(send_codec) << ", bitrate=" << send_codec.rate; webrtc::CodecInst current_codec; if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 && (send_codec == current_codec)) { // Codec is already configured, we can return without setting it again. return true; } if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) { LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec)); return false; } return true; } bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) { desired_playout_ = playout; return ChangePlayout(desired_playout_); } bool WebRtcVoiceMediaChannel::PausePlayout() { return ChangePlayout(false); } bool WebRtcVoiceMediaChannel::ResumePlayout() { return ChangePlayout(desired_playout_); } bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); if (playout_ == playout) { return true; } for (const auto& ch : recv_streams_) { if (!SetPlayout(ch.second->channel(), playout)) { LOG(LS_ERROR) << "SetPlayout " << playout << " on channel " << ch.second->channel() << " failed"; return false; } } playout_ = playout; return true; } bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) { desired_send_ = send; if (!send_streams_.empty()) { return ChangeSend(desired_send_); } return true; } bool WebRtcVoiceMediaChannel::PauseSend() { return ChangeSend(SEND_NOTHING); } bool WebRtcVoiceMediaChannel::ResumeSend() { return ChangeSend(desired_send_); } bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) { if (send_ == send) { return true; } // Apply channel specific options when channel is enabled for sending. if (send == SEND_MICROPHONE) { engine()->ApplyOptions(options_); } // Change the settings on each send channel. for (const auto& ch : send_streams_) { if (!ChangeSend(ch.second->channel(), send)) { return false; } } send_ = send; return true; } bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) { if (send == SEND_MICROPHONE) { if (engine()->voe()->base()->StartSend(channel) == -1) { LOG_RTCERR1(StartSend, channel); return false; } } else { // SEND_NOTHING RTC_DCHECK(send == SEND_NOTHING); if (engine()->voe()->base()->StopSend(channel) == -1) { LOG_RTCERR1(StopSend, channel); return false; } } return true; } bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc, bool enable, const AudioOptions* options, AudioRenderer* renderer) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // TODO(solenberg): The state change should be fully rolled back if any one of // these calls fail. if (!SetLocalRenderer(ssrc, renderer)) { return false; } if (!MuteStream(ssrc, !enable)) { return false; } if (enable && options) { return SetOptions(*options); } return true; } int WebRtcVoiceMediaChannel::CreateVoEChannel() { int id = engine()->CreateVoEChannel(); if (id == -1) { LOG_RTCERR0(CreateVoEChannel); return -1; } if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) { LOG_RTCERR2(RegisterExternalTransport, id, this); engine()->voe()->base()->DeleteChannel(id); return -1; } return id; } bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) { if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) { LOG_RTCERR1(DeRegisterExternalTransport, channel); } if (engine()->voe()->base()->DeleteChannel(channel) == -1) { LOG_RTCERR1(DeleteChannel, channel); return false; } return true; } bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "AddSendStream: " << sp.ToString(); uint32_t ssrc = sp.first_ssrc(); RTC_DCHECK(0 != ssrc); if (GetSendChannelId(ssrc) != -1) { LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc; return false; } // Create a new channel for sending audio data. int channel = CreateVoEChannel(); if (channel == -1) { return false; } // Save the channel to send_streams_, so that RemoveSendStream() can still // delete the channel in case failure happens below. webrtc::AudioTransport* audio_transport = engine()->voe()->base()->audio_transport(); send_streams_.insert(std::make_pair(ssrc, new WebRtcAudioSendStream( channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_))); // Set the current codecs to be used for the new channel. We need to do this // after adding the channel to send_channels_, because of how max bitrate is // currently being configured by SetSendCodec(). if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_)) { RemoveSendStream(ssrc); return false; } // At this point the channel's local SSRC has been updated. If the channel is // the first send channel make sure that all the receive channels are updated // with the same SSRC in order to send receiver reports. if (send_streams_.size() == 1) { receiver_reports_ssrc_ = ssrc; for (const auto& stream : recv_streams_) { int recv_channel = stream.second->channel(); if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) { LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc); return false; } engine()->voe()->base()->AssociateSendChannel(recv_channel, channel); LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel << " is associated with channel #" << channel << "."; } } return ChangeSend(channel, desired_send_); } bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "RemoveSendStream: " << ssrc; auto it = send_streams_.find(ssrc); if (it == send_streams_.end()) { LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc << " which doesn't exist."; return false; } int channel = it->second->channel(); ChangeSend(channel, SEND_NOTHING); // Clean up and delete the send stream+channel. LOG(LS_INFO) << "Removing audio send stream " << ssrc << " with VoiceEngine channel #" << channel << "."; delete it->second; send_streams_.erase(it); if (!DeleteVoEChannel(channel)) { return false; } if (send_streams_.empty()) { ChangeSend(SEND_NOTHING); } return true; } bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "AddRecvStream: " << sp.ToString(); if (!ValidateStreamParams(sp)) { return false; } const uint32_t ssrc = sp.first_ssrc(); if (ssrc == 0) { LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported."; return false; } // Remove the default receive stream if one had been created with this ssrc; // we'll recreate it then. if (IsDefaultRecvStream(ssrc)) { RemoveRecvStream(ssrc); } if (GetReceiveChannelId(ssrc) != -1) { LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc; return false; } // Create a new channel for receiving audio data. const int channel = CreateVoEChannel(); if (channel == -1) { return false; } // Turn off all supported codecs. // TODO(solenberg): Remove once "no codecs" is the default state of a stream. for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) { voe_codec.pltype = -1; if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) { LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec)); DeleteVoEChannel(channel); return false; } } // Only enable those configured for this channel. for (const auto& codec : recv_codecs_) { webrtc::CodecInst voe_codec; if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) { voe_codec.pltype = codec.id; if (engine()->voe()->codec()->SetRecPayloadType( channel, voe_codec) == -1) { LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec)); DeleteVoEChannel(channel); return false; } } } const int send_channel = GetSendChannelId(receiver_reports_ssrc_); if (send_channel != -1) { // Associate receive channel with first send channel (so the receive channel // can obtain RTT from the send channel) engine()->voe()->base()->AssociateSendChannel(channel, send_channel); LOG(LS_INFO) << "VoiceEngine channel #" << channel << " is associated with channel #" << send_channel << "."; } transport_cc_enabled_ = !send_codecs_.empty() ? HasTransportCc(send_codecs_[0]) : false; recv_streams_.insert(std::make_pair( ssrc, new WebRtcAudioReceiveStream(channel, ssrc, receiver_reports_ssrc_, transport_cc_enabled_, sp.sync_label, recv_rtp_extensions_, call_))); SetNack(channel, nack_enabled_); SetPlayout(channel, playout_); return true; } bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "RemoveRecvStream: " << ssrc; const auto it = recv_streams_.find(ssrc); if (it == recv_streams_.end()) { LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc << " which doesn't exist."; return false; } // Deregister default channel, if that's the one being destroyed. if (IsDefaultRecvStream(ssrc)) { default_recv_ssrc_ = -1; } const int channel = it->second->channel(); // Clean up and delete the receive stream+channel. LOG(LS_INFO) << "Removing audio receive stream " << ssrc << " with VoiceEngine channel #" << channel << "."; it->second->SetRawAudioSink(nullptr); delete it->second; recv_streams_.erase(it); return DeleteVoEChannel(channel); } bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32_t ssrc, AudioRenderer* renderer) { auto it = send_streams_.find(ssrc); if (it == send_streams_.end()) { if (renderer) { // Return an error if trying to set a valid renderer with an invalid ssrc. LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc; return false; } // The channel likely has gone away, do nothing. return true; } if (renderer) { it->second->Start(renderer); } else { it->second->Stop(); } return true; } bool WebRtcVoiceMediaChannel::GetActiveStreams( AudioInfo::StreamList* actives) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); actives->clear(); for (const auto& ch : recv_streams_) { int level = GetOutputLevel(ch.second->channel()); if (level > 0) { actives->push_back(std::make_pair(ch.first, level)); } } return true; } int WebRtcVoiceMediaChannel::GetOutputLevel() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int highest = 0; for (const auto& ch : recv_streams_) { highest = std::max(GetOutputLevel(ch.second->channel()), highest); } return highest; } int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() { int ret; if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) { // In case of error, log the info and continue LOG_RTCERR0(TimeSinceLastTyping); ret = -1; } else { ret *= 1000; // We return ms, webrtc returns seconds. } return ret; } void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window, int cost_per_typing, int reporting_threshold, int penalty_decay, int type_event_delay) { if (engine()->voe()->processing()->SetTypingDetectionParameters( time_window, cost_per_typing, reporting_threshold, penalty_decay, type_event_delay) == -1) { // In case of error, log the info and continue LOG_RTCERR5(SetTypingDetectionParameters, time_window, cost_per_typing, reporting_threshold, penalty_decay, type_event_delay); } } bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); if (ssrc == 0) { default_recv_volume_ = volume; if (default_recv_ssrc_ == -1) { return true; } ssrc = static_cast<uint32_t>(default_recv_ssrc_); } int ch_id = GetReceiveChannelId(ssrc); if (ch_id < 0) { LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc; return false; } if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id, volume)) { LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume); return false; } LOG(LS_INFO) << "SetOutputVolume to " << volume << " for channel " << ch_id << " and ssrc " << ssrc; return true; } bool WebRtcVoiceMediaChannel::CanInsertDtmf() { return dtmf_payload_type_ ? true : false; } bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event, int duration) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf"; if (!dtmf_payload_type_) { return false; } // Figure out which WebRtcAudioSendStream to send the event on. auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin(); if (it == send_streams_.end()) { LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use."; return false; } if (event < kMinTelephoneEventCode || event > kMaxTelephoneEventCode) { LOG(LS_WARNING) << "DTMF event code " << event << " out of range."; return false; } if (duration < kMinTelephoneEventDuration || duration > kMaxTelephoneEventDuration) { LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range."; return false; } return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration); } void WebRtcVoiceMediaChannel::OnPacketReceived( rtc::Buffer* packet, const rtc::PacketTime& packet_time) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); uint32_t ssrc = 0; if (!GetRtpSsrc(packet->data(), packet->size(), &ssrc)) { return; } // If we don't have a default channel, and the SSRC is unknown, create a // default channel. if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) { StreamParams sp; sp.ssrcs.push_back(ssrc); LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << "."; if (!AddRecvStream(sp)) { LOG(LS_WARNING) << "Could not create default receive stream."; return; } default_recv_ssrc_ = ssrc; SetOutputVolume(default_recv_ssrc_, default_recv_volume_); if (default_sink_) { rtc::scoped_ptr<webrtc::AudioSinkInterface> proxy_sink( new ProxySink(default_sink_.get())); SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink)); } } // Forward packet to Call. If the SSRC is unknown we'll return after this. const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp, packet_time.not_before); webrtc::PacketReceiver::DeliveryStatus delivery_result = call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO, reinterpret_cast<const uint8_t*>(packet->data()), packet->size(), webrtc_packet_time); if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) { // If the SSRC is unknown here, route it to the default channel, if we have // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208 if (default_recv_ssrc_ == -1) { return; } else { ssrc = default_recv_ssrc_; } } // Find the channel to send this packet to. It must exist since webrtc::Call // was able to demux the packet. int channel = GetReceiveChannelId(ssrc); RTC_DCHECK(channel != -1); // Pass it off to the decoder. engine()->voe()->network()->ReceivedRTPPacket( channel, packet->data(), packet->size(), webrtc_packet_time); } void WebRtcVoiceMediaChannel::OnRtcpReceived( rtc::Buffer* packet, const rtc::PacketTime& packet_time) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Forward packet to Call as well. const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp, packet_time.not_before); call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO, reinterpret_cast<const uint8_t*>(packet->data()), packet->size(), webrtc_packet_time); // Sending channels need all RTCP packets with feedback information. // Even sender reports can contain attached report blocks. // Receiving channels need sender reports in order to create // correct receiver reports. int type = 0; if (!GetRtcpType(packet->data(), packet->size(), &type)) { LOG(LS_WARNING) << "Failed to parse type from received RTCP packet"; return; } // If it is a sender report, find the receive channel that is listening. if (type == kRtcpTypeSR) { uint32_t ssrc = 0; if (!GetRtcpSsrc(packet->data(), packet->size(), &ssrc)) { return; } int recv_channel_id = GetReceiveChannelId(ssrc); if (recv_channel_id != -1) { engine()->voe()->network()->ReceivedRTCPPacket( recv_channel_id, packet->data(), packet->size()); } } // SR may continue RR and any RR entry may correspond to any one of the send // channels. So all RTCP packets must be forwarded all send channels. VoE // will filter out RR internally. for (const auto& ch : send_streams_) { engine()->voe()->network()->ReceivedRTCPPacket( ch.second->channel(), packet->data(), packet->size()); } } bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int channel = GetSendChannelId(ssrc); if (channel == -1) { LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use."; return false; } if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) { LOG_RTCERR2(SetInputMute, channel, muted); return false; } // We set the AGC to mute state only when all the channels are muted. // This implementation is not ideal, instead we should signal the AGC when // the mic channel is muted/unmuted. We can't do it today because there // is no good way to know which stream is mapping to the mic channel. bool all_muted = muted; for (const auto& ch : send_streams_) { if (!all_muted) { break; } if (engine()->voe()->volume()->GetInputMute(ch.second->channel(), all_muted)) { LOG_RTCERR1(GetInputMute, ch.second->channel()); return false; } } webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing(); if (ap) { ap->set_output_will_be_muted(all_muted); } return true; } // TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to // SetMaxSendBitrate() in future. bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) { LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth."; return SetSendBitrateInternal(bps); } bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) { LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal."; send_bitrate_setting_ = true; send_bitrate_bps_ = bps; if (!send_codec_) { LOG(LS_INFO) << "The send codec has not been set up yet. " << "The send bitrate setting will be applied later."; return true; } // Bitrate is auto by default. // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by // SetMaxSendBandwith(0), the second call removes the previous limit. if (bps <= 0) return true; webrtc::CodecInst codec = *send_codec_; bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec); if (is_multi_rate) { // If codec is multi-rate then just set the bitrate. codec.rate = bps; for (const auto& ch : send_streams_) { if (!SetSendCodec(ch.second->channel(), codec)) { LOG(LS_INFO) << "Failed to set codec " << codec.plname << " to bitrate " << bps << " bps."; return false; } } return true; } else { // If codec is not multi-rate and |bps| is less than the fixed bitrate // then fail. If codec is not multi-rate and |bps| exceeds or equal the // fixed bitrate then ignore. if (bps < codec.rate) { LOG(LS_INFO) << "Failed to set codec " << codec.plname << " to bitrate " << bps << " bps" << ", requires at least " << codec.rate << " bps."; return false; } return true; } } bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); RTC_DCHECK(info); // Get SSRC and stats for each sender. RTC_DCHECK(info->senders.size() == 0); for (const auto& stream : send_streams_) { webrtc::AudioSendStream::Stats stats = stream.second->GetStats(); VoiceSenderInfo sinfo; sinfo.add_ssrc(stats.local_ssrc); sinfo.bytes_sent = stats.bytes_sent; sinfo.packets_sent = stats.packets_sent; sinfo.packets_lost = stats.packets_lost; sinfo.fraction_lost = stats.fraction_lost; sinfo.codec_name = stats.codec_name; sinfo.ext_seqnum = stats.ext_seqnum; sinfo.jitter_ms = stats.jitter_ms; sinfo.rtt_ms = stats.rtt_ms; sinfo.audio_level = stats.audio_level; sinfo.aec_quality_min = stats.aec_quality_min; sinfo.echo_delay_median_ms = stats.echo_delay_median_ms; sinfo.echo_delay_std_ms = stats.echo_delay_std_ms; sinfo.echo_return_loss = stats.echo_return_loss; sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement; sinfo.typing_noise_detected = (send_ == SEND_NOTHING ? false : stats.typing_noise_detected); info->senders.push_back(sinfo); } // Get SSRC and stats for each receiver. RTC_DCHECK(info->receivers.size() == 0); for (const auto& stream : recv_streams_) { webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats(); VoiceReceiverInfo rinfo; rinfo.add_ssrc(stats.remote_ssrc); rinfo.bytes_rcvd = stats.bytes_rcvd; rinfo.packets_rcvd = stats.packets_rcvd; rinfo.packets_lost = stats.packets_lost; rinfo.fraction_lost = stats.fraction_lost; rinfo.codec_name = stats.codec_name; rinfo.ext_seqnum = stats.ext_seqnum; rinfo.jitter_ms = stats.jitter_ms; rinfo.jitter_buffer_ms = stats.jitter_buffer_ms; rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms; rinfo.delay_estimate_ms = stats.delay_estimate_ms; rinfo.audio_level = stats.audio_level; rinfo.expand_rate = stats.expand_rate; rinfo.speech_expand_rate = stats.speech_expand_rate; rinfo.secondary_decoded_rate = stats.secondary_decoded_rate; rinfo.accelerate_rate = stats.accelerate_rate; rinfo.preemptive_expand_rate = stats.preemptive_expand_rate; rinfo.decoding_calls_to_silence_generator = stats.decoding_calls_to_silence_generator; rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq; rinfo.decoding_normal = stats.decoding_normal; rinfo.decoding_plc = stats.decoding_plc; rinfo.decoding_cng = stats.decoding_cng; rinfo.decoding_plc_cng = stats.decoding_plc_cng; rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms; info->receivers.push_back(rinfo); } return true; } void WebRtcVoiceMediaChannel::SetRawAudioSink( uint32_t ssrc, rtc::scoped_ptr<webrtc::AudioSinkInterface> sink) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:" << ssrc << " " << (sink ? "(ptr)" : "NULL"); if (ssrc == 0) { if (default_recv_ssrc_ != -1) { rtc::scoped_ptr<webrtc::AudioSinkInterface> proxy_sink( sink ? new ProxySink(sink.get()) : nullptr); SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink)); } default_sink_ = std::move(sink); return; } const auto it = recv_streams_.find(ssrc); if (it == recv_streams_.end()) { LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc; return; } it->second->SetRawAudioSink(std::move(sink)); } int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) { unsigned int ulevel = 0; int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel); return (ret == 0) ? static_cast<int>(ulevel) : -1; } int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); const auto it = recv_streams_.find(ssrc); if (it != recv_streams_.end()) { return it->second->channel(); } return -1; } int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); const auto it = send_streams_.find(ssrc); if (it != send_streams_.end()) { return it->second->channel(); } return -1; } bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) { if (playout) { LOG(LS_INFO) << "Starting playout for channel #" << channel; if (engine()->voe()->base()->StartPlayout(channel) == -1) { LOG_RTCERR1(StartPlayout, channel); return false; } } else { LOG(LS_INFO) << "Stopping playout for channel #" << channel; engine()->voe()->base()->StopPlayout(channel); } return true; } } // namespace cricket #endif // HAVE_WEBRTC_VOICE
35.294071
80
0.673561
[ "object", "vector" ]
371010a29c240cd26eb1641d87b4e22f5859a082
12,192
tpp
C++
libs/base/include/mrpt/otherlibs/stlplus/smart_ptr.tpp
feroze/mrpt-shivang
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
libs/base/include/mrpt/otherlibs/stlplus/smart_ptr.tpp
feroze/mrpt-shivang
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
null
null
null
libs/base/include/mrpt/otherlibs/stlplus/smart_ptr.tpp
feroze/mrpt-shivang
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
1
2018-07-29T09:40:46.000Z
2018-07-29T09:40:46.000Z
/* The STL+ C++ Library Collection Website <http://stlplus.sourceforge.net/> Collection <index.html> License Agreement <http://www.opensource.org/> * License for using the STLplus Library Collection <#license> * The Intent of this License <#intent> * How to Comply with this License <#compliance> * Historical Note <#history> License for using the STLplus Library Collection *© 1999-2008 Andy Rushton. All rights reserved.* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above Copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above Copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the STLplus library 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 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. */ /* Modified version of STL+ sources shipped with the Mobile Robot Programming Toolkit (MRPT). Sources have been modified to support thred-safe smart pointers through atomic operations. 2009, Jose Luis Blanco. University of Malaga. */ #ifndef MRPT_SMARTPTR_H #define MRPT_SMARTPTR_H //////////////////////////////////////////////////////////////////////////////// // Author: Andy Rushton // Copyright: (c) Andy Rushton, 2007 // License: BSD License, see ../docs/license.html //////////////////////////////////////////////////////////////////////////////// namespace stlplus { //////////////////////////////////////////////////////////////////////////////// // internal holder data structure //////////////////////////////////////////////////////////////////////////////// template<typename T,typename COUNTER> class smart_ptr_holder { private: COUNTER m_count; //JL: It was... unsigned m_count; T* m_data; // make these private to disallow copying because the holder doesn't know how to copy inline smart_ptr_holder(const smart_ptr_holder& ) : m_count(0), m_data(0) { } inline smart_ptr_holder& operator=(const smart_ptr_holder& ) { return *this; } public: inline smart_ptr_holder(T* p = 0) : m_count(1), m_data(p) { } ~smart_ptr_holder(void) { clear(); } inline unsigned long count(void) const { return m_count; } inline void increment(void) { ++m_count; } inline bool decrement(void) { return (--m_count)==0; } inline bool null(void) { return m_data == 0; } inline void clear(void) { if(m_data) delete m_data; m_data = 0; } inline void set(T* p = 0) { clear(); m_data = p; } inline T*& pointer(void) { return m_data; } inline const T* pointer(void) const { return m_data; } inline T& value(void) { return *m_data; } inline const T& value(void) const { return *m_data; } }; //////////////////////////////////////////////////////////////////////////////// // smart_ptr_base class //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // constructors, assignments and destructors // create a null pointer template <typename T, typename C, typename COUNTER> smart_ptr_base<T,C,COUNTER>::smart_ptr_base(void) : m_holder(new smart_ptr_holder<T,COUNTER>) { } // create a pointer containing a *copy* of the object pointer template <typename T, typename C, typename COUNTER> smart_ptr_base<T,C,COUNTER>::smart_ptr_base(const T& data) throw(illegal_copy) : m_holder(new smart_ptr_holder<T,COUNTER>) { m_holder->set(C()(data)); } // create a pointer containing a dynamically created object // Note: the object must be allocated *by the user* with new // constructor form - must be called in the form smart_ptr<type> x(new type(args)) template <typename T, typename C, typename COUNTER> smart_ptr_base<T,C,COUNTER>::smart_ptr_base(T* data) : m_holder(new smart_ptr_holder<T,COUNTER>) { m_holder->set(data); } // copy constructor implements counted referencing - no copy is made template <typename T, typename C, typename COUNTER> smart_ptr_base<T,C,COUNTER>::smart_ptr_base(const smart_ptr_base<T,C,COUNTER>& r) : m_holder(0) { m_holder = r.m_holder; m_holder->increment(); } // destructor decrements the reference count and delete only when the last reference is destroyed template <typename T, typename C, typename COUNTER> smart_ptr_base<T,C,COUNTER>::~smart_ptr_base(void) { if(m_holder->decrement()) delete m_holder; } ////////////////////////////////////////////////////////////////////////////// // logical tests to see if there is anything contained in the pointer since it can be null template <typename T, typename C, typename COUNTER> inline bool smart_ptr_base<T,C,COUNTER>::null(void) const { return m_holder->null(); } template <typename T, typename C, typename COUNTER> inline bool smart_ptr_base<T,C,COUNTER>::present(void) const { return !m_holder->null(); } template <typename T, typename C, typename COUNTER> bool smart_ptr_base<T,C,COUNTER>::operator!(void) const { return m_holder->null(); } template <typename T, typename C, typename COUNTER> smart_ptr_base<T,C,COUNTER>::operator bool(void) const { return !m_holder->null(); } ////////////////////////////////////////////////////////////////////////////// // dereference operators and functions template <typename T, typename C, typename COUNTER> inline T& smart_ptr_base<T,C,COUNTER>::operator*(void) throw(null_dereference) { if (m_holder->null()) throw null_dereference("null pointer dereferenced in smart_ptr::operator*"); return m_holder->value(); } template <typename T, typename C, typename COUNTER> inline const T& smart_ptr_base<T,C,COUNTER>::operator*(void) const throw(null_dereference) { if (m_holder->null()) throw null_dereference("null pointer dereferenced in smart_ptr::operator*"); return m_holder->value(); } template <typename T, typename C, typename COUNTER> inline T* smart_ptr_base<T,C,COUNTER>::operator->(void) throw(null_dereference) { if (m_holder->null()) throw null_dereference("null pointer dereferenced in smart_ptr::operator->"); return m_holder->pointer(); } template <typename T, typename C, typename COUNTER> inline const T* smart_ptr_base<T,C,COUNTER>::operator->(void) const throw(null_dereference) { if (m_holder->null()) throw null_dereference("null pointer dereferenced in smart_ptr::operator->"); return m_holder->pointer(); } ////////////////////////////////////////////////////////////////////////////// // explicit function forms of the above assignment dereference operators template <typename T, typename C, typename COUNTER> inline void smart_ptr_base<T,C,COUNTER>::set_value(const T& data) throw(illegal_copy) { m_holder->set(C()(data)); } template <typename T, typename C, typename COUNTER> inline T& smart_ptr_base<T,C,COUNTER>::value(void) throw(null_dereference) { if (m_holder->null()) throw null_dereference("null pointer dereferenced in smart_ptr::value"); return m_holder->value(); } template <typename T, typename C, typename COUNTER> inline const T& smart_ptr_base<T,C,COUNTER>::value(void) const throw(null_dereference) { if (m_holder->null()) throw null_dereference("null pointer dereferenced in smart_ptr::value"); return m_holder->value(); } template <typename T, typename C, typename COUNTER> void smart_ptr_base<T,C,COUNTER>::set(T* data) { m_holder->set(data); } template <typename T, typename C, typename COUNTER> inline T* smart_ptr_base<T,C,COUNTER>::pointer(void) { return m_holder->pointer(); } template <typename T, typename C, typename COUNTER> inline const T* smart_ptr_base<T,C,COUNTER>::pointer(void) const { return m_holder->pointer(); } //////////////////////////////////////////////////////////////////////////////// // functions to manage counted referencing // make this an alias of the passed object template <typename T, typename C, typename COUNTER> void smart_ptr_base<T,C,COUNTER>::alias(const smart_ptr_base<T,C,COUNTER>& r) { // make it alias-copy safe - this means that I don't try to do the // assignment if r is either the same object or an alias of it // if (m_holder == r.m_holder) return; // if (m_holder->decrement()) // delete m_holder; // m_holder = r.m_holder; // m_holder->increment(); make_alias(r.m_holder); } template <typename T, typename C, typename COUNTER> bool smart_ptr_base<T,C,COUNTER>::aliases(const smart_ptr_base<T,C,COUNTER>& r) const { return m_holder == r.m_holder; } template <typename T, typename C, typename COUNTER> unsigned smart_ptr_base<T,C,COUNTER>::alias_count(void) const { return m_holder->count(); } template <typename T, typename C, typename COUNTER> void smart_ptr_base<T,C,COUNTER>::clear(void) { m_holder->clear(); } template <typename T, typename C, typename COUNTER> void smart_ptr_base<T,C,COUNTER>::clear_unique(void) { if (m_holder->count() == 1) m_holder->clear(); else { m_holder->decrement(); m_holder = 0; m_holder = new smart_ptr_holder<T,COUNTER>; } } template <typename T, typename C, typename COUNTER> void smart_ptr_base<T,C,COUNTER>::make_unique(void) throw(illegal_copy) { if (m_holder->count() > 1) { smart_ptr_holder<T,COUNTER>* old_holder = m_holder; m_holder->decrement(); m_holder = 0; m_holder = new smart_ptr_holder<T,COUNTER>; if (old_holder->pointer()) m_holder->set(C()(old_holder->value())); } } template <typename T, typename C, typename COUNTER> void smart_ptr_base<T,C,COUNTER>::copy(const smart_ptr_base<T,C,COUNTER>& data) throw(illegal_copy) { alias(data); make_unique(); } // internal function for distinguishing unique smart_ptr objects // used for example in persistence routines template <typename T, typename C, typename COUNTER> void* smart_ptr_base<T,C,COUNTER>::handle(void) const { return m_holder; } template <typename T, typename C, typename COUNTER> void smart_ptr_base<T,C,COUNTER>::make_alias(void* handle) { smart_ptr_holder<T,COUNTER>* r_holder = (smart_ptr_holder<T,COUNTER>*)handle; if (m_holder != r_holder) { if (m_holder->decrement()) delete m_holder; m_holder = r_holder; m_holder->increment(); } } //////////////////////////////////////////////////////////////////////////////// } // end namespace stlplus #endif
30.253102
103
0.623934
[ "object" ]
3711ab85aebda86064238fdc9d05aa7f1484a790
19,024
cpp
C++
thrift/test/reflection/fatal_folly_dynamic_test.cpp
efiks/fbthrift
bc880a08d36a7265b9a29291cbfc675030f7f21a
[ "Apache-2.0" ]
null
null
null
thrift/test/reflection/fatal_folly_dynamic_test.cpp
efiks/fbthrift
bc880a08d36a7265b9a29291cbfc675030f7f21a
[ "Apache-2.0" ]
null
null
null
thrift/test/reflection/fatal_folly_dynamic_test.cpp
efiks/fbthrift
bc880a08d36a7265b9a29291cbfc675030f7f21a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <sstream> #include <utility> #include <glog/logging.h> #include <folly/String.h> #include <folly/json.h> #include <folly/portability/GTest.h> #include <thrift/lib/cpp2/protocol/Serializer.h> #include <thrift/lib/cpp2/reflection/debug.h> #include <thrift/lib/cpp2/reflection/folly_dynamic.h> #include <thrift/lib/cpp2/reflection/helpers.h> #include <thrift/lib/cpp2/reflection/internal/test_helpers.h> #include <thrift/lib/cpp2/reflection/pretty_print.h> #include <thrift/test/reflection/gen-cpp2/compat_fatal_types.h> #include <thrift/test/reflection/gen-cpp2/global_fatal_types.h> #include <thrift/test/reflection/gen-cpp2/reflection_fatal_types.h> using namespace cpp2; namespace apache { namespace thrift { template <typename T> void test_to_from(T const& pod, folly::dynamic const& json) { std::ostringstream log; try { log.str("to_dynamic(PORTABLE):\n"); auto const actual = apache::thrift::to_dynamic( pod, apache::thrift::dynamic_format::PORTABLE); if (actual != json) { log << "actual: " << folly::toPrettyJson(actual) << std::endl << "expected: " << folly::toPrettyJson(json); LOG(ERROR) << log.str(); } EXPECT_EQ(actual, json); } catch (std::exception const&) { LOG(ERROR) << log.str(); throw; } try { log.str("from_dynamic(PORTABLE):\n"); auto const actual = apache::thrift::from_dynamic<T>( json, apache::thrift::dynamic_format::PORTABLE); if (actual != pod) { apache::thrift::pretty_print(log << "actual: ", actual); log << std::endl; apache::thrift::pretty_print(log << "expected: ", pod); log << std::endl; LOG(ERROR) << log.str(); } EXPECT_EQ(actual, pod); } catch (std::exception const&) { LOG(ERROR) << log.str(); throw; } try { log.str("from_dynamic(PORTABLE)/to_dynamic(PORTABLE):\n"); auto const from = apache::thrift::from_dynamic<T>( json, apache::thrift::dynamic_format::PORTABLE); auto const to = apache::thrift::to_dynamic( from, apache::thrift::dynamic_format::PORTABLE); if (json != to) { apache::thrift::pretty_print(log << "from: ", from); log << std::endl << "to: " << folly::toPrettyJson(to) << std::endl << "expected: " << folly::toPrettyJson(json); LOG(ERROR) << log.str(); } EXPECT_EQ(json, to); } catch (std::exception const&) { LOG(ERROR) << log.str(); throw; } try { log.str("to_dynamic(PORTABLE)/from_dynamic(PORTABLE):\n"); auto const to = apache::thrift::to_dynamic( pod, apache::thrift::dynamic_format::PORTABLE); auto const from = apache::thrift::from_dynamic<T>( to, apache::thrift::dynamic_format::PORTABLE); if (pod != from) { log << "to: " << folly::toPrettyJson(to) << std::endl; apache::thrift::pretty_print(log << "from: ", from); log << std::endl; apache::thrift::pretty_print(log << "expected: ", pod); log << std::endl; LOG(ERROR) << log.str(); } EXPECT_EQ(pod, from); } catch (std::exception const&) { LOG(ERROR) << log.str(); throw; } try { log.str("to_dynamic(PORTABLE)/from_dynamic(PORTABLE,LENIENT):\n"); auto const to = apache::thrift::to_dynamic( pod, apache::thrift::dynamic_format::PORTABLE); auto const from = apache::thrift::from_dynamic<T>( to, apache::thrift::dynamic_format::PORTABLE, apache::thrift::format_adherence::LENIENT); if (pod != from) { log << "to: " << folly::toPrettyJson(to) << std::endl; apache::thrift::pretty_print(log << "from: ", from); log << std::endl; apache::thrift::pretty_print(log << "expected: ", pod); log << std::endl; LOG(ERROR) << log.str(); } EXPECT_EQ(pod, from); } catch (std::exception const&) { LOG(ERROR) << log.str(); throw; } try { log.str("to_dynamic(PORTABLE)/from_dynamic(JSON_1,LENIENT):\n"); auto const to = apache::thrift::to_dynamic( pod, apache::thrift::dynamic_format::PORTABLE); auto const from = apache::thrift::from_dynamic<T>( to, apache::thrift::dynamic_format::JSON_1, apache::thrift::format_adherence::LENIENT); if (pod != from) { log << "to: " << folly::toPrettyJson(to) << std::endl; apache::thrift::pretty_print(log << "from: ", from); log << std::endl; apache::thrift::pretty_print(log << "expected: ", pod); log << std::endl; LOG(ERROR) << log.str(); } EXPECT_EQ(pod, from); } catch (std::exception const&) { LOG(ERROR) << log.str(); throw; } try { log.str("to_dynamic(JSON_1)/from_dynamic(PORTABLE,LENIENT):\n"); auto const to = apache::thrift::to_dynamic(pod, apache::thrift::dynamic_format::JSON_1); auto const from = apache::thrift::from_dynamic<T>( to, apache::thrift::dynamic_format::PORTABLE, apache::thrift::format_adherence::LENIENT); if (pod != from) { log << "to: " << folly::toPrettyJson(to) << std::endl; apache::thrift::pretty_print(log << "from: ", from); log << std::endl; apache::thrift::pretty_print(log << "expected: ", pod); log << std::endl; LOG(ERROR) << log.str(); } EXPECT_EQ(pod, from); } catch (std::exception const&) { LOG(ERROR) << log.str(); throw; } try { log.str("to_dynamic(JSON_1)/from_dynamic(JSON_1,LENIENT):\n"); auto const to = apache::thrift::to_dynamic(pod, apache::thrift::dynamic_format::JSON_1); auto const from = apache::thrift::from_dynamic<T>( to, apache::thrift::dynamic_format::JSON_1, apache::thrift::format_adherence::LENIENT); if (pod != from) { log << "to: " << folly::toPrettyJson(to) << std::endl; apache::thrift::pretty_print(log << "from: ", from); log << std::endl; apache::thrift::pretty_print(log << "expected: ", pod); log << std::endl; LOG(ERROR) << log.str(); } EXPECT_EQ(pod, from); } catch (std::exception const&) { LOG(ERROR) << log.str(); throw; } } template < typename Struct3, typename StructA, typename StructB, typename Enum1, typename Enum2> std::pair<Struct3, std::string> test_data_1() { StructA a1; a1.a_ref().ensure(); *a1.a_ref() = 99; a1.b_ref().ensure(); *a1.b_ref() = "abc"; StructA a2; a2.a_ref().ensure(); *a2.a_ref() = 1001; a2.b_ref().ensure(); *a2.b_ref() = "foo"; StructA a3; a3.a_ref().ensure(); *a3.a_ref() = 654; a3.b_ref().ensure(); *a3.b_ref() = "bar"; StructA a4; a4.a_ref().ensure(); *a4.a_ref() = 9791; a4.b_ref().ensure(); *a4.b_ref() = "baz"; StructA a5; a5.a_ref().ensure(); *a5.a_ref() = 111; a5.b_ref().ensure(); *a5.b_ref() = "gaz"; StructB b1; b1.c_ref().ensure(); *b1.c_ref() = 1.23; b1.d_ref().ensure(); *b1.d_ref() = true; StructB b2; b2.c_ref().ensure(); *b2.c_ref() = 9.8; b2.d_ref().ensure(); *b2.d_ref() = false; StructB b3; b3.c_ref().ensure(); *b3.c_ref() = 10.01; b3.d_ref().ensure(); *b3.d_ref() = true; StructB b4; b4.c_ref().ensure(); *b4.c_ref() = 159.73; b4.d_ref().ensure(); *b4.d_ref() = false; StructB b5; b5.c_ref().ensure(); *b5.c_ref() = 468.02; b5.d_ref().ensure(); *b5.d_ref() = true; Struct3 pod; pod.fieldA_ref().ensure(); *pod.fieldA_ref() = 141; pod.fieldB_ref().ensure(); *pod.fieldB_ref() = "this is a test"; pod.fieldC_ref().ensure(); *pod.fieldC_ref() = Enum1::field0; pod.fieldD_ref().ensure(); *pod.fieldD_ref() = Enum2::field1_2; pod.fieldE_ref().ensure(); pod.fieldE_ref()->set_ud(5.6); pod.fieldF_ref().ensure(); pod.fieldF_ref()->set_us_2("this is a variant"); pod.fieldG_ref().ensure(); pod.fieldG_ref()->field0 = 98; pod.fieldG_ref()->field1_ref() = "hello, world"; pod.fieldG_ref()->__isset.field2 = true; *pod.fieldG_ref()->field2_ref() = Enum1::field2; pod.fieldG_ref()->field3 = Enum2::field0_2; pod.fieldG_ref()->field4_ref() = {}; pod.fieldG_ref()->field4_ref()->set_ui(19937); pod.fieldG_ref()->__isset.field5 = true; pod.fieldG_ref()->field5_ref()->set_ue_2(Enum1::field1); // fieldH intentionally left empty pod.fieldI_ref().ensure(); *pod.fieldI_ref() = {3, 5, 7, 9}; pod.fieldJ_ref().ensure(); *pod.fieldJ_ref() = {"a", "b", "c", "d"}; pod.fieldK_ref().ensure(); *pod.fieldK_ref() = {}; pod.fieldL_ref().ensure(); pod.fieldL_ref()->push_back(a1); pod.fieldL_ref()->push_back(a2); pod.fieldL_ref()->push_back(a3); pod.fieldL_ref()->push_back(a4); pod.fieldL_ref()->push_back(a5); pod.fieldM_ref().ensure(); *pod.fieldM_ref() = {2, 4, 6, 8}; pod.fieldN_ref().ensure(); *pod.fieldN_ref() = {"w", "x", "y", "z"}; pod.fieldO_ref().ensure(); *pod.fieldO_ref() = {}; pod.fieldP_ref().ensure(); *pod.fieldP_ref() = {b1, b2, b3, b4, b5}; pod.fieldQ_ref().ensure(); *pod.fieldQ_ref() = {{"a1", a1}, {"a2", a2}, {"a3", a3}}; pod.fieldR_ref().ensure(); *pod.fieldR_ref() = {}; auto const json = folly::stripLeftMargin(R"({ "fieldA": 141, "fieldB": "this is a test", "fieldC": "field0", "fieldD": "field1_2", "fieldE": { "ud": 5.6 }, "fieldF": { "us_2": "this is a variant" }, "fieldG": { "field0": 98, "field1": "hello, world", "field2": "field2", "field3": "field0_2", "field4": { "ui": 19937 }, "field5": { "ue_2": "field1" } }, "fieldH": {}, "fieldI": [3, 5, 7, 9], "fieldJ": ["a", "b", "c", "d"], "fieldK": [], "fieldL": [ { "a": 99, "b": "abc" }, { "a": 1001, "b": "foo" }, { "a": 654, "b": "bar" }, { "a": 9791, "b": "baz" }, { "a": 111, "b": "gaz" } ], "fieldM": [2, 4, 6, 8], "fieldN": ["w", "x", "y", "z"], "fieldO": [], "fieldP": [ { "c": 1.23, "d": true }, { "c": 9.8, "d": false }, { "c": 10.01, "d": true }, { "c": 159.73, "d": false }, { "c": 468.02, "d": true } ], "fieldQ": { "a1": { "a": 99, "b": "abc" }, "a2": { "a": 1001, "b": "foo" }, "a3": { "a": 654, "b": "bar" } }, "fieldR": {}, "fieldS": {} })"); return std::make_pair(pod, json); } TEST(fatal_folly_dynamic, to_from_dynamic) { auto const data = test_data_1< test_cpp2::cpp_reflection::struct3, test_cpp2::cpp_reflection::structA, test_cpp2::cpp_reflection::structB, test_cpp2::cpp_reflection::enum1, test_cpp2::cpp_reflection::enum2>(); auto const pod = data.first; auto const json = folly::parseJson(data.second); test_to_from(pod, json); } TEST(fatal_folly_dynamic, booleans) { auto const decode = [](char const* json) { return apache::thrift::from_dynamic<test_cpp2::cpp_reflection::structB>( folly::parseJson(json), apache::thrift::dynamic_format::PORTABLE); }; test_cpp2::cpp_reflection::structB expected; *expected.c_ref() = 1.3; *expected.d_ref() = true; EXPECT_EQ(expected, decode(R"({ "c": 1.3, "d": 1})")); EXPECT_EQ(expected, decode(R"({ "c": 1.3, "d": 100})")); EXPECT_EQ(expected, decode(R"({ "c": 1.3, "d": true})")); } TEST(fatal_folly_dynamic, to_from_dynamic_compat) { auto const data = test_data_1< test_cpp2::cpp_compat::compat_struct3, test_cpp2::cpp_compat::compat_structA, test_cpp2::cpp_compat::compat_structB, test_cpp2::cpp_compat::compat_enum1, test_cpp2::cpp_compat::compat_enum2>(); auto const pod = data.first; auto const json = folly::parseJson(data.second); test_to_from(pod, json); } TEST(fatal_folly_dynamic, to_from_dynamic_global) { auto const data = test_data_1< ::global_struct3, ::global_structA, ::global_structB, ::global_enum1, ::global_enum2>(); auto const pod = data.first; auto const json = folly::parseJson(data.second); test_to_from(pod, json); } TEST(fatal_folly_dynamic, to_from_dynamic_binary) { folly::dynamic actl = folly::dynamic::object; folly::dynamic expt = folly::dynamic::object; // to test_cpp2::cpp_reflection::struct_binary a; *a.bi_ref() = "123abc"; actl = to_dynamic(a, dynamic_format::PORTABLE); expt = folly::dynamic::object("bi", "123abc"); EXPECT_EQ(expt, actl); // from auto obj = from_dynamic<test_cpp2::cpp_reflection::struct_binary>( folly::dynamic::object("bi", "123abc"), apache::thrift::dynamic_format::PORTABLE); EXPECT_EQ("123abc", *obj.bi_ref()); } } // namespace thrift } // namespace apache namespace test_cpp1 { namespace cpp_compat {} // namespace cpp_compat } // namespace test_cpp1 TEST(fatal_folly_dynamic, optional_string) { auto obj = apache::thrift::from_dynamic<global_struct1>( folly::dynamic::object("field1", "asdf"), apache::thrift::dynamic_format::PORTABLE); EXPECT_EQ("asdf", *obj.field1_ref()); } TEST(fatal_folly_dynamic, list_from_empty_object) { // some dynamic languages (lua, php) conflate empty array and empty object; // check that we do not throw in such cases using type = global_structC; using member_name = fatal::sequence<char, 'j', '3'>; using member_meta = apache::thrift::get_struct_member_by_name<type, member_name>; EXPECT_SAME< // sanity check member_meta::type_class, apache::thrift::type_class::list< apache::thrift::type_class::structure>>(); auto obj = apache::thrift::from_dynamic<type>( folly::dynamic::object( fatal::z_data<member_name>(), folly::dynamic::object), apache::thrift::dynamic_format::PORTABLE); EXPECT_TRUE(member_meta::is_set(obj)); EXPECT_EQ(0, member_meta::getter{}(obj).size()); } TEST(fatal_folly_dynamic, set_from_empty_object) { // some dynamic languages (lua, php) conflate empty array and empty object; // check that we do not throw in such cases using type = global_structC; using member_name = fatal::sequence<char, 'k', '3'>; using member_meta = apache::thrift::get_struct_member_by_name<type, member_name>; EXPECT_SAME< // sanity check member_meta::type_class, apache::thrift::type_class::set<apache::thrift::type_class::structure>>(); auto obj = apache::thrift::from_dynamic<type>( folly::dynamic::object( fatal::z_data<member_name>(), folly::dynamic::object), apache::thrift::dynamic_format::PORTABLE); EXPECT_TRUE(member_meta::is_set(obj)); EXPECT_EQ(0, member_meta::getter{}(obj).size()); } TEST(fatal_folly_dynamic, map_from_empty_array) { // some dynamic languages (lua, php) conflate empty array and empty object; // check that we do not throw in such cases using type = global_structC; using member_name = fatal::sequence<char, 'l', '3'>; using member_meta = apache::thrift::get_struct_member_by_name<type, member_name>; EXPECT_SAME< // sanity check member_meta::type_class, apache::thrift::type_class::map< apache::thrift::type_class::integral, apache::thrift::type_class::structure>>(); auto obj = apache::thrift::from_dynamic<type>( folly::dynamic::object( fatal::z_data<member_name>(), folly::dynamic::array), apache::thrift::dynamic_format::PORTABLE); EXPECT_TRUE(member_meta::is_set(obj)); EXPECT_EQ(0, member_meta::getter{}(obj).size()); } TEST(fatal_folly_dynamic, from_iobuf) { folly::dynamic dyn = folly::dynamic::object("buf", "foo"); auto obj = apache::thrift::from_dynamic<test_cpp2::cpp_reflection::StructWithIOBuf>( dyn, apache::thrift::dynamic_format::PORTABLE); EXPECT_EQ((*obj.buf_ref())->moveToFbString(), "foo"); } namespace { class fatal_folly_dynamic_enum : public ::testing::Test { protected: void SetUp() override { EXPECT_SAME< // sanity check member_meta::type_class, apache::thrift::type_class::enumeration>(); } using type = global_structC; using member_name = fatal::sequence<char, 'e'>; using member_meta = apache::thrift::get_struct_member_by_name<type, member_name>; std::string member_name_s{fatal::to_instance<std::string, member_name>()}; }; } // namespace TEST_F(fatal_folly_dynamic_enum, from_string_strict) { folly::dynamic dyn = folly::dynamic::object(member_name_s, "field0"); auto obj = apache::thrift::from_dynamic<type>( dyn, apache::thrift::dynamic_format::PORTABLE); EXPECT_TRUE(member_meta::is_set(obj)); EXPECT_EQ(global_enum1::field0, member_meta::getter{}(obj)); EXPECT_THROW( apache::thrift::from_dynamic<type>( dyn, apache::thrift::dynamic_format::JSON_1), folly::ConversionError); } TEST_F(fatal_folly_dynamic_enum, from_integer_strict) { folly::dynamic dyn = folly::dynamic::object(member_name_s, 0); auto obj = apache::thrift::from_dynamic<type>( dyn, apache::thrift::dynamic_format::JSON_1); EXPECT_TRUE(member_meta::is_set(obj)); EXPECT_EQ(global_enum1::field0, member_meta::getter{}(obj)); EXPECT_THROW( apache::thrift::from_dynamic<type>( dyn, apache::thrift::dynamic_format::PORTABLE), std::invalid_argument); } TEST_F(fatal_folly_dynamic_enum, from_string_lenient) { folly::dynamic dyn = folly::dynamic::object(member_name_s, "field0"); auto obj1 = apache::thrift::from_dynamic<type>( dyn, apache::thrift::dynamic_format::PORTABLE, apache::thrift::format_adherence::LENIENT); EXPECT_TRUE(member_meta::is_set(obj1)); EXPECT_EQ(global_enum1::field0, member_meta::getter{}(obj1)); auto obj2 = apache::thrift::from_dynamic<type>( dyn, apache::thrift::dynamic_format::JSON_1, apache::thrift::format_adherence::LENIENT); EXPECT_TRUE(member_meta::is_set(obj2)); EXPECT_EQ(global_enum1::field0, member_meta::getter{}(obj2)); } TEST_F(fatal_folly_dynamic_enum, from_integer_lenient) { folly::dynamic dyn = folly::dynamic::object(member_name_s, 0); auto obj1 = apache::thrift::from_dynamic<type>( dyn, apache::thrift::dynamic_format::PORTABLE, apache::thrift::format_adherence::LENIENT); EXPECT_TRUE(member_meta::is_set(obj1)); EXPECT_EQ(global_enum1::field0, member_meta::getter{}(obj1)); auto obj2 = apache::thrift::from_dynamic<type>( dyn, apache::thrift::dynamic_format::JSON_1, apache::thrift::format_adherence::LENIENT); EXPECT_TRUE(member_meta::is_set(obj2)); EXPECT_EQ(global_enum1::field0, member_meta::getter{}(obj2)); }
32.298812
80
0.631728
[ "object" ]
3713bce11d117ad2b8f263072348f0e05590a74c
1,552
cpp
C++
android-31/android/os/TokenWatcher.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/os/TokenWatcher.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/os/TokenWatcher.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./Handler.hpp" #include "../../java/io/PrintWriter.hpp" #include "../../JString.hpp" #include "./TokenWatcher.hpp" namespace android::os { // Fields // QJniObject forward TokenWatcher::TokenWatcher(QJniObject obj) : JObject(obj) {} // Constructors TokenWatcher::TokenWatcher(android::os::Handler arg0, JString arg1) : JObject( "android.os.TokenWatcher", "(Landroid/os/Handler;Ljava/lang/String;)V", arg0.object(), arg1.object<jstring>() ) {} // Methods void TokenWatcher::acquire(JObject arg0, JString arg1) const { callMethod<void>( "acquire", "(Landroid/os/IBinder;Ljava/lang/String;)V", arg0.object(), arg1.object<jstring>() ); } void TokenWatcher::acquired() const { callMethod<void>( "acquired", "()V" ); } void TokenWatcher::cleanup(JObject arg0, jboolean arg1) const { callMethod<void>( "cleanup", "(Landroid/os/IBinder;Z)V", arg0.object(), arg1 ); } void TokenWatcher::dump() const { callMethod<void>( "dump", "()V" ); } void TokenWatcher::dump(java::io::PrintWriter arg0) const { callMethod<void>( "dump", "(Ljava/io/PrintWriter;)V", arg0.object() ); } jboolean TokenWatcher::isAcquired() const { return callMethod<jboolean>( "isAcquired", "()Z" ); } void TokenWatcher::release(JObject arg0) const { callMethod<void>( "release", "(Landroid/os/IBinder;)V", arg0.object() ); } void TokenWatcher::released() const { callMethod<void>( "released", "()V" ); } } // namespace android::os
17.83908
68
0.635309
[ "object" ]
37140f77c54aaf90fcf62d96b22dc925d6607244
4,838
hpp
C++
include/Mono/Http/NtlmClient_--c.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/Mono/Http/NtlmClient_--c.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/Mono/Http/NtlmClient_--c.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: Mono.Http.NtlmClient #include "Mono/Http/NtlmClient.hpp" // Including type: System.Runtime.CompilerServices.ConditionalWeakTable`2 #include "System/Runtime/CompilerServices/ConditionalWeakTable_2.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Net namespace System::Net { // Forward declaring type: HttpWebRequest class HttpWebRequest; } // Forward declaring namespace: Mono::Http namespace Mono::Http { // Forward declaring type: NtlmSession class NtlmSession; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::Mono::Http::NtlmClient::$$c); DEFINE_IL2CPP_ARG_TYPE(::Mono::Http::NtlmClient::$$c*, "Mono.Http", "NtlmClient/<>c"); // Type namespace: Mono.Http namespace Mono::Http { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: Mono.Http.NtlmClient/Mono.Http.<>c // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF class NtlmClient::$$c : public ::Il2CppObject { public: // Get static field: static public readonly Mono.Http.NtlmClient/Mono.Http.<>c <>9 static ::Mono::Http::NtlmClient::$$c* _get_$$9(); // Set static field: static public readonly Mono.Http.NtlmClient/Mono.Http.<>c <>9 static void _set_$$9(::Mono::Http::NtlmClient::$$c* value); // Get static field: static public System.Runtime.CompilerServices.ConditionalWeakTable`2/System.Runtime.CompilerServices.CreateValueCallback<System.Net.HttpWebRequest,Mono.Http.NtlmSession> <>9__1_0 static typename ::System::Runtime::CompilerServices::ConditionalWeakTable_2<::System::Net::HttpWebRequest*, ::Mono::Http::NtlmSession*>::CreateValueCallback* _get_$$9__1_0(); // Set static field: static public System.Runtime.CompilerServices.ConditionalWeakTable`2/System.Runtime.CompilerServices.CreateValueCallback<System.Net.HttpWebRequest,Mono.Http.NtlmSession> <>9__1_0 static void _set_$$9__1_0(typename ::System::Runtime::CompilerServices::ConditionalWeakTable_2<::System::Net::HttpWebRequest*, ::Mono::Http::NtlmSession*>::CreateValueCallback* value); // static private System.Void .cctor() // Offset: 0x8E107C static void _cctor(); // Mono.Http.NtlmSession <Authenticate>b__1_0(System.Net.HttpWebRequest x) // Offset: 0x8E10E4 ::Mono::Http::NtlmSession* $Authenticate$b__1_0(::System::Net::HttpWebRequest* x); // public System.Void .ctor() // Offset: 0x8E10DC // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NtlmClient::$$c* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::Mono::Http::NtlmClient::$$c::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NtlmClient::$$c*, creationType>())); } }; // Mono.Http.NtlmClient/Mono.Http.<>c #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Mono::Http::NtlmClient::$$c::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&Mono::Http::NtlmClient::$$c::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Mono::Http::NtlmClient::$$c*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Mono::Http::NtlmClient::$$c::$Authenticate$b__1_0 // Il2CppName: <Authenticate>b__1_0 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Mono::Http::NtlmSession* (Mono::Http::NtlmClient::$$c::*)(::System::Net::HttpWebRequest*)>(&Mono::Http::NtlmClient::$$c::$Authenticate$b__1_0)> { static const MethodInfo* get() { static auto* x = &::il2cpp_utils::GetClassFromName("System.Net", "HttpWebRequest")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Mono::Http::NtlmClient::$$c*), "<Authenticate>b__1_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x}); } }; // Writing MetadataGetter for method: Mono::Http::NtlmClient::$$c::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
54.359551
216
0.725093
[ "object", "vector" ]
37169eb17e29e6ee705bd4dd065cc24adadffde8
2,562
cpp
C++
ScannerBit/src/scanners/simple/raster.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
2
2020-09-08T20:05:27.000Z
2021-04-26T07:57:56.000Z
ScannerBit/src/scanners/simple/raster.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
9
2020-10-19T09:56:17.000Z
2021-05-28T06:12:03.000Z
ScannerBit/src/scanners/simple/raster.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
5
2020-09-08T02:23:34.000Z
2021-03-23T08:48:04.000Z
// GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// Toy MCMC sampler. /// /// ********************************************* /// /// Authors (add name and date if you modify): // /// \author Gregory Martinez /// (gregory.david.martinez@gmail.com) /// \date 2013 August /// /// ********************************************* #ifdef WITH_MPI #include "mpi.h" #endif #include <vector> #include <string> #include <cmath> #include <iostream> #include <map> #include <sstream> #include "gambit/ScannerBit/scanner_plugin.hpp" #include "gambit/Utils/threadsafe_rng.hpp" scanner_plugin(raster, version(1, 0, 0)) { std::map<std::string, std::vector<double>> param_map; int N = 0, numtasks, rank; plugin_constructor { YAML::Node node = get_inifile_node("parameters"); if (!node) { scan_err << "Need to specify a set of parameters in parameters subsection." << scan_end; } if (!node.IsMap()) { scan_err << "parameters subsection needs to be of map formatt." << scan_end; } for (auto it = node.begin(), end = node.end(); it != end; ++it) { param_map[it->first.as<std::string>()] = get_yaml_vector<double>(it->second); int temp = param_map[it->first.as<std::string>()].size(); if (temp > N) N = temp; } #ifdef WITH_MPI MPI_Comm_size(MPI_COMM_WORLD, &numtasks); MPI_Comm_rank(MPI_COMM_WORLD, &rank); #else numtasks = 1; rank = 0; #endif } int plugin_main (void) { like_ptr LogLike = get_purpose(get_inifile_value<std::string>("like")); int ma = get_dimension(); std::vector<double> a(ma); std::cout << "Starting Raster Scanner over " << N << " points." << ma << std::endl; for (int i = rank; i < N; i+=numtasks) { std::unordered_map<std::string, double> map; for (auto it = param_map.begin(), end = param_map.end(); it != end; ++it) { map[it->first] = it->second[i%it->second.size()]; } for (int j = 0; j < ma; j++) { a[j] = Gambit::Random::draw(); } LogLike(map, a); std::cout << "Point " << i << " done." << std::endl; } std::cout << "Finished!" << std::endl; return 0; } }
26.142857
100
0.484778
[ "vector" ]
37180213c89a1e93d03cb19fddc692707d125178
5,281
cpp
C++
FluidEngine/CameraTarget.cpp
jingquanalex/FluidEngine
11a5c7de187636b446bdc6b4666543b4741c8b64
[ "MIT" ]
3
2017-12-27T10:31:28.000Z
2021-04-17T13:15:35.000Z
FluidEngine/CameraTarget.cpp
jingquanalex/FluidEngine
11a5c7de187636b446bdc6b4666543b4741c8b64
[ "MIT" ]
null
null
null
FluidEngine/CameraTarget.cpp
jingquanalex/FluidEngine
11a5c7de187636b446bdc6b4666543b4741c8b64
[ "MIT" ]
1
2019-10-14T07:29:41.000Z
2019-10-14T07:29:41.000Z
#include "CameraTarget.h" using namespace glm; using namespace std; extern int window_width; extern int window_height; CameraTarget::CameraTarget(Object* target, float distance) : Camera() { view = Views::Chase; defaultYaw = yaw = 0.0f; defaultPitch = pitch = 0.0f; this->targetObject = target; this->distance = distance; updateViewMatrix(); } CameraTarget::~CameraTarget() { } void CameraTarget::update(float dt) { if (!isActive) return; direction = normalize(targetPosition - position); updateViewMatrix(); } void CameraTarget::updateViewMatrix() { if (targetObject == nullptr) { vec3 dirVec = rotate(vec3(0, 0, 1), radians(yaw), vec3(0, 1, 0)); vec3 right = cross(-dirVec, vec3(0, 1, 0)); position = targetPosition + rotate(dirVec, radians(pitch), right) * distance; matView = lookAt(position, targetPosition, vec3(0, 1, 0)); } else { // Airplane Camera stuff mat4 matRotation = targetObject->getRotationMatrix(); vec3 forward = vec3(matRotation[2][0], matRotation[2][1], matRotation[2][2]); vec3 up = vec3(matRotation[1][0], matRotation[1][1], matRotation[1][2]); vec3 right = vec3(matRotation[0][0], matRotation[0][1], matRotation[0][2]); switch (view) { case Views::Chase: if (stateLookAround) { vec3 dirVec = rotate(vec3(0, 0, 1), radians(yaw), vec3(0, 1, 0)); vec3 right = cross(-dirVec, vec3(0, 1, 0)); position = targetPosition + rotate(dirVec, radians(pitch), right) * distance; matView = lookAt(position, targetPosition, vec3(0, 1, 0)); } else { position = targetPosition + rotate(-forward, radians(-defaultPitch), right) * distance; matView = lookAt(position, targetPosition, up); } break; case Views::Cockpit: position = targetPosition + forward; matView = lookAt(position, position + forward, up); break; case Views::Left: position = targetPosition + right * 1.5 - up * 0.5; matView = lookAt(position, position + forward, up); break; case Views::Right: position = targetPosition - forward * 3.0 - right * 1.5 - up * 0.5; matView = lookAt(position, position + forward, up); break; case Views::Ground: matView = lookAt(groundObject->getPosition(), targetPosition, vec3(0, 1, 0)); break; case Views::Sky: matView = lookAt(groundObject->getPosition(), targetPosition, vec3(0, 1, 0)); break; } } if (!isActive) return; glBindBuffer(GL_UNIFORM_BUFFER, Shader::uboMatrices); glBufferSubData(GL_UNIFORM_BUFFER, sizeof(mat4), sizeof(mat4), value_ptr(getMatView())); glBindBuffer(GL_UNIFORM_BUFFER, 0); glBindBuffer(GL_UNIFORM_BUFFER, Shader::uboLighting); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(vec4), value_ptr(position)); glBindBuffer(GL_UNIFORM_BUFFER, 0); } void CameraTarget::mouse(int button, int state) { if (!isActive) return; if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { stateLookAround = true; } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_UP) { stateLookAround = false; } // Airplane stuff /*if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { if (view == Views::Chase) { stateLookAround = true; // Maintain cursor center position while moving mouse mouseTriggered = true; isWrappingPointer = true; glutWarpPointer(glutGet(GLUT_WINDOW_WIDTH) / 2, glutGet(GLUT_WINDOW_HEIGHT) / 2); mouseLastX = glutGet(GLUT_WINDOW_WIDTH) / 2; mouseLastY = glutGet(GLUT_WINDOW_HEIGHT) / 2; yaw = defaultYaw; pitch = defaultPitch; } } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_UP) { if (view == Views::Chase) { stateLookAround = false; //mouseTriggered = false; } }*/ } // Track the delta for the mouse movements void CameraTarget::mouseMotion(int x, int y) { if (!isActive) return; Camera::mouseMotion(x, y); if (stateLookAround) { // Update yaw and pitch and limit pitch yaw += -mouseDeltaX * mouseSensitivity; pitch += -mouseDeltaY * mouseSensitivity; pitch = clamp(pitch, -89.0f, 89.0f); } } void CameraTarget::mouseMotionPassive(int x, int y) { if (!isActive) return; Camera::mouseMotionPassive(x, y); } void CameraTarget::mouseWheel(int dir) { if (!isActive) return; if (stateLookAround) { distance += -dir * 0.5f; distance = clamp(distance, 0.0001f, 100.0f); } } void CameraTarget::keyboard(unsigned char key) { if (!isActive) return; switch (key) { case '1': view = Views::Chase; break; case '2': view = Views::Cockpit; break; case '3': view = Views::Left; break; case '4': view = Views::Right; break; case '5': view = Views::Ground; break; case '6': view = Views::Sky; break; } } void CameraTarget::keyboardUp(unsigned char key) { } void CameraTarget::setTargetObject(Object* target, Object* target2) { this->targetObject = target; this->groundObject = target2; setTarget(target->getPosition()); } void CameraTarget::setTarget(glm::vec3 target) { this->targetPosition = target; } void CameraTarget::setDistance(float distance) { this->distance = distance; } void CameraTarget::setOrientation(float yaw, float pitch) { defaultYaw = this->yaw = yaw; defaultPitch = this->pitch = pitch; } Object* CameraTarget::getTargetObject() const { return targetObject; } float CameraTarget::getDistance() const { return distance; }
21.822314
91
0.683015
[ "object" ]
3719e01510aafbc54049a3cdc2728e8cc32ee3a9
14,497
cc
C++
L1Trigger/L1THGCal/src/HGCalTriggerTowerGeometryHelper.cc
hakimialexandre/cmssw
6027e58832d8fb3a85c8d179d02c1e449555717a
[ "Apache-2.0" ]
4
2015-10-12T10:31:12.000Z
2018-02-26T20:40:58.000Z
L1Trigger/L1THGCal/src/HGCalTriggerTowerGeometryHelper.cc
hakimialexandre/cmssw
6027e58832d8fb3a85c8d179d02c1e449555717a
[ "Apache-2.0" ]
220
2015-06-23T20:18:12.000Z
2022-02-08T11:01:37.000Z
L1Trigger/L1THGCal/src/HGCalTriggerTowerGeometryHelper.cc
hakimialexandre/cmssw
6027e58832d8fb3a85c8d179d02c1e449555717a
[ "Apache-2.0" ]
7
2016-10-25T11:34:24.000Z
2021-11-16T14:09:12.000Z
#include "L1Trigger/L1THGCal/interface/HGCalTriggerTowerGeometryHelper.h" #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/Utilities/interface/EDMException.h" #include "DataFormats/DetId/interface/DetId.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <cmath> #include <iostream> #include <fstream> #include <algorithm> HGCalTriggerTowerGeometryHelper::HGCalTriggerTowerGeometryHelper(const edm::ParameterSet& conf) : doNose_(conf.getParameter<bool>("doNose")), minEta_(conf.getParameter<double>("minEta")), maxEta_(conf.getParameter<double>("maxEta")), minPhi_(conf.getParameter<double>("minPhi")), maxPhi_(conf.getParameter<double>("maxPhi")), nBinsEta_(conf.getParameter<int>("nBinsEta")), nBinsPhi_(conf.getParameter<int>("nBinsPhi")), binsEta_(conf.getParameter<std::vector<double> >("binsEta")), binsPhi_(conf.getParameter<std::vector<double> >("binsPhi")), splitModuleSum_(conf.getParameter<bool>("splitModuleSum")) { if (!binsEta_.empty() && ((unsigned int)(binsEta_.size()) != nBinsEta_ + 1)) { throw edm::Exception(edm::errors::Configuration, "Configuration") << "HGCalTriggerTowerGeometryHelper nBinsEta for the tower map not consistent with binsEta size" << std::endl; } if (!binsPhi_.empty() && ((unsigned int)(binsPhi_.size()) != nBinsPhi_ + 1)) { throw edm::Exception(edm::errors::Configuration, "Configuration") << "HGCalTriggerTowerGeometryHelper nBinsPhi for the tower map not consistent with binsPhi size" << std::endl; } // if the bin vecctor is empty we assume the bins to be regularly spaced if (binsEta_.empty()) { for (unsigned int bin1 = 0; bin1 != nBinsEta_ + 1; bin1++) { binsEta_.push_back(minEta_ + bin1 * ((maxEta_ - minEta_) / nBinsEta_)); } } // if the bin vecctor is empty we assume the bins to be regularly spaced if (binsPhi_.empty()) { for (unsigned int bin2 = 0; bin2 != nBinsPhi_ + 1; bin2++) { binsPhi_.push_back(minPhi_ + bin2 * ((maxPhi_ - minPhi_) / nBinsPhi_)); } } for (int zside = -1; zside <= 1; zside += 2) { for (unsigned int bin1 = 0; bin1 != nBinsEta_; bin1++) { for (unsigned int bin2 = 0; bin2 != nBinsPhi_; bin2++) { l1t::HGCalTowerID towerId(doNose_, zside, bin1, bin2); tower_coords_.emplace_back(towerId.rawId(), zside * ((binsEta_[bin1 + 1] + binsEta_[bin1]) / 2), (binsPhi_[bin2 + 1] + binsPhi_[bin2]) / 2); } } } if (conf.getParameter<bool>("readMappingFile")) { // We read the TC to TT mapping from file, // otherwise we derive the TC to TT mapping on the fly from eta-phi coord. of the TCs std::ifstream l1tTriggerTowerMappingStream(conf.getParameter<edm::FileInPath>("L1TTriggerTowerMapping").fullPath()); if (!l1tTriggerTowerMappingStream.is_open()) { throw cms::Exception("MissingDataFile") << "Cannot open HGCalTriggerGeometry L1TTriggerTowerMapping file\n"; } unsigned trigger_cell_id = 0; unsigned short iEta = 0; unsigned short iPhi = 0; for (; l1tTriggerTowerMappingStream >> trigger_cell_id >> iEta >> iPhi;) { if (iEta >= nBinsEta_ || iPhi >= nBinsPhi_) { throw edm::Exception(edm::errors::Configuration, "Configuration") << "HGCalTriggerTowerGeometryHelper warning inconsistent mapping TC : " << trigger_cell_id << " to TT iEta: " << iEta << " iPhi: " << iPhi << " when max #bins eta: " << nBinsEta_ << " phi: " << nBinsPhi_ << std::endl; } l1t::HGCalTowerID towerId(doNose_, triggerTools_.zside(DetId(trigger_cell_id)), iEta, iPhi); cells_to_trigger_towers_[trigger_cell_id] = towerId.rawId(); } l1tTriggerTowerMappingStream.close(); } if (splitModuleSum_) { //variables for transforming towers rotate180Deg_ = int(nBinsPhi_) / 2; rotate120Deg_ = int(nBinsPhi_) / 3; reverseX_ = int(nBinsPhi_) / 2 - 1; std::ifstream moduleTowerMappingStream(conf.getParameter<edm::FileInPath>("moduleTowerMapping").fullPath()); if (!moduleTowerMappingStream.is_open()) { throw cms::Exception("MissingDataFile") << "Cannot open HGCalTowerMapProducer moduleTowerMapping file\n"; } //get split divisors std::string line; std::getline(moduleTowerMappingStream, line); //Skip row std::getline(moduleTowerMappingStream, line); std::stringstream ss(line); ss >> splitDivisorSilic_ >> splitDivisorScint_; //get towers and module sum shares std::getline(moduleTowerMappingStream, line); //Skip row std::getline(moduleTowerMappingStream, line); //Skip row const int minNumOfWordsPerRow = 5; const int numOfWordsPerTower = 3; for (std::string line; std::getline(moduleTowerMappingStream, line);) { int numOfWordsInThisRow = 0; for (std::string::size_type i = 0; i < line.size(); i++) { if (line[i] != ' ' && line[i + 1] == ' ') { numOfWordsInThisRow++; } } if (numOfWordsInThisRow < minNumOfWordsPerRow) { throw edm::Exception(edm::errors::Configuration, "Configuration") << "HGCalTriggerTowerGeometryHelper warning: Incorrect/incomplete values for module ID in the mapping " "file.\n" << "The incorrect line is:" << line << std::endl; } int subdet; int layer; int moduleU; int moduleV; int numTowers; std::stringstream ss(line); ss >> subdet >> layer >> moduleU >> moduleV >> numTowers; if (numOfWordsInThisRow != (numTowers * numOfWordsPerTower + minNumOfWordsPerRow)) { throw edm::Exception(edm::errors::Configuration, "Configuration") << "HGCalTriggerTowerGeometryHelper warning: Incorrect/incomplete values for module ID or tower " "share/eta/phi in the mapping file.\n" << "The incorrect line is:" << line << std::endl; } unsigned packed_modID = packLayerSubdetWaferId(subdet, layer, moduleU, moduleV); std::vector<unsigned> towers; for (int itr_tower = 0; itr_tower < numTowers; itr_tower++) { int iEta_raw; int iPhi_raw; int towerShare; ss >> iEta_raw >> iPhi_raw >> towerShare; int splitDivisor = (subdet == 2) ? splitDivisorScint_ : splitDivisorSilic_; if ((towerShare > splitDivisor) || (towerShare < 1)) { throw edm::Exception(edm::errors::Configuration, "Configuration") << "HGCalTriggerTowerGeometryHelper warning: invalid tower share in the mapping file.\n" << "Tower share must be a positive integer and less than splitDivisor. The incorrect values found for " "module ID:" << std::endl << "subdet=" << subdet << ", l=" << layer << ", u=" << moduleU << ", v=" << moduleV << std::endl; } towers.push_back(packTowerIDandShare(iEta_raw, iPhi_raw, towerShare)); } modules_to_trigger_towers_[packed_modID] = towers; } moduleTowerMappingStream.close(); } } unsigned HGCalTriggerTowerGeometryHelper::packLayerSubdetWaferId(int subdet, int layer, int moduleU, int moduleV) const { unsigned packed_modID = 0; packed_modID |= ((subdet & HGCalTriggerModuleDetId::kHGCalTriggerSubdetMask) << HGCalTriggerModuleDetId::kHGCalTriggerSubdetOffset); packed_modID |= ((layer & HGCalTriggerModuleDetId::kHGCalLayerMask) << HGCalTriggerModuleDetId::kHGCalLayerOffset); packed_modID |= ((moduleU & HGCalTriggerModuleDetId::kHGCalModuleUMask) << HGCalTriggerModuleDetId::kHGCalModuleUOffset); packed_modID |= ((moduleV & HGCalTriggerModuleDetId::kHGCalModuleVMask) << HGCalTriggerModuleDetId::kHGCalModuleVOffset); return packed_modID; } unsigned HGCalTriggerTowerGeometryHelper::packTowerIDandShare(int iEta_raw, int iPhi_raw, int towerShare) const { unsigned packed_towerIDandShare = 0; unsigned iEtaAbs = std::abs(iEta_raw); unsigned iEtaSign = std::signbit(iEta_raw); unsigned iPhiAbs = std::abs(iPhi_raw); unsigned iPhiSign = std::signbit(iPhi_raw); packed_towerIDandShare |= ((iEtaAbs & l1t::HGCalTowerID::coordMask) << l1t::HGCalTowerID::coord1Shift); packed_towerIDandShare |= ((iEtaSign & signMask) << sign1Shift); packed_towerIDandShare |= ((iPhiAbs & l1t::HGCalTowerID::coordMask) << l1t::HGCalTowerID::coord2Shift); packed_towerIDandShare |= ((iPhiSign & signMask) << sign2Shift); packed_towerIDandShare |= ((towerShare & towerShareMask) << towerShareShift); return packed_towerIDandShare; } void HGCalTriggerTowerGeometryHelper::unpackTowerIDandShare(unsigned towerIDandShare, int& iEta_raw, int& iPhi_raw, int& towerShare) const { //eta iEta_raw = (towerIDandShare >> l1t::HGCalTowerID::coord1Shift) & l1t::HGCalTowerID::coordMask; unsigned iEtaSign = (towerIDandShare >> sign1Shift) & signMask; iEta_raw = (iEtaSign) ? -1 * iEta_raw : iEta_raw; //phi iPhi_raw = (towerIDandShare >> l1t::HGCalTowerID::coord2Shift) & l1t::HGCalTowerID::coordMask; unsigned iPhiSign = (towerIDandShare >> sign2Shift) & signMask; iPhi_raw = (iPhiSign) ? -1 * iPhi_raw : iPhi_raw; //tower share towerShare = (towerIDandShare >> towerShareShift) & towerShareMask; } int HGCalTriggerTowerGeometryHelper::moveToCorrectSector(int iPhi_raw, int sector) const { int iPhi = (iPhi_raw + sector * rotate120Deg_ + rotate180Deg_) % int(nBinsPhi_); return iPhi; } void HGCalTriggerTowerGeometryHelper::reverseXaxis(int& iPhi) const { iPhi = reverseX_ - iPhi; //correct x -> -x in z>0 iPhi = (int(nBinsPhi_) + iPhi) % int(nBinsPhi_); // make all phi between 0 to nBinsPhi_-1 } const std::vector<l1t::HGCalTowerCoord>& HGCalTriggerTowerGeometryHelper::getTowerCoordinates() const { return tower_coords_; } unsigned short HGCalTriggerTowerGeometryHelper::getTriggerTowerFromEtaPhi(const float& eta, const float& phi) const { auto bin_eta_l = std::lower_bound(binsEta_.begin(), binsEta_.end(), fabs(eta)); unsigned int bin_eta = 0; // we add a protection for TCs in Hadron part which are outside the boundaries and possible rounding effects if (bin_eta_l == binsEta_.end()) { if (fabs(eta) < minEta_) { bin_eta = 0; } else if (fabs(eta) >= maxEta_) { bin_eta = nBinsEta_; } else { edm::LogError("HGCalTriggerTowerGeometryHelper") << " did not manage to map eta " << eta << " to any Trigger Tower\n"; } } else { bin_eta = bin_eta_l - binsEta_.begin() - 1; } auto bin_phi_l = std::lower_bound(binsPhi_.begin(), binsPhi_.end(), phi); unsigned int bin_phi = 0; if (bin_phi_l == binsPhi_.end()) { if (phi < minPhi_) { bin_phi = nBinsPhi_; } else if (phi >= maxPhi_) { bin_phi = 0; } else { edm::LogError("HGCalTriggerTowerGeometryHelper") << " did not manage to map phi " << phi << " to any Trigger Tower\n"; } } else { bin_phi = bin_phi_l - binsPhi_.begin() - 1; } int zside = eta < 0 ? -1 : 1; return l1t::HGCalTowerID(doNose_, zside, bin_eta, bin_phi).rawId(); } std::unordered_map<unsigned short, float> HGCalTriggerTowerGeometryHelper::getTriggerTower( const l1t::HGCalTriggerCell& thecell) const { std::unordered_map<unsigned short, float> towerIDandShares = {}; unsigned int trigger_cell_id = thecell.detId(); // NOTE: if the TC is not found in the map than it is mapped via eta-phi coords. // this can be considered dangerous (silent failure of the map) but it actually allows to save // memory mapping explicitly only what is actually needed auto tower_id_itr = cells_to_trigger_towers_.find(trigger_cell_id); if (tower_id_itr != cells_to_trigger_towers_.end()) { towerIDandShares.insert({tower_id_itr->second, 1.0}); return towerIDandShares; } towerIDandShares.insert({getTriggerTowerFromEtaPhi(thecell.position().eta(), thecell.position().phi()), 1.0}); return towerIDandShares; } std::unordered_map<unsigned short, float> HGCalTriggerTowerGeometryHelper::getTriggerTower( const l1t::HGCalTriggerSums& thesum) const { std::unordered_map<unsigned short, float> towerIDandShares = {}; if (!splitModuleSum_) { towerIDandShares.insert({getTriggerTowerFromEtaPhi(thesum.position().eta(), thesum.position().phi()), 1.0}); return towerIDandShares; } else { HGCalTriggerModuleDetId detid(thesum.detId()); int moduleU = detid.moduleU(); int moduleV = detid.moduleV(); int layer = detid.layer(); int sector = detid.sector(); int zside = detid.zside(); int subdet = 0; int splitDivisor = splitDivisorSilic_; if (detid.isHScintillator()) { subdet = 2; splitDivisor = splitDivisorScint_; } else if (detid.isEE()) { subdet = 0; splitDivisor = splitDivisorSilic_; } else if (detid.isHSilicon()) { subdet = 1; splitDivisor = splitDivisorSilic_; } else { //HFNose towerIDandShares.insert({getTriggerTowerFromEtaPhi(thesum.position().eta(), thesum.position().phi()), 1.0}); return towerIDandShares; } unsigned packed_modID = packLayerSubdetWaferId(subdet, layer, moduleU, moduleV); auto module_id_itr = modules_to_trigger_towers_.find(packed_modID); if (module_id_itr != modules_to_trigger_towers_.end()) { //eta variables int iEta = -999; int iEta_raw = -999; int offsetEta = 2; //phi variables int iPhi = -999; int iPhi_raw = -999; int towerShare = -999; //the share each tower gets from module sum for (auto towerIDandShare : module_id_itr->second) { unpackTowerIDandShare(towerIDandShare, iEta_raw, iPhi_raw, towerShare); iEta = offsetEta + iEta_raw; iPhi = moveToCorrectSector(iPhi_raw, sector); if (zside == 1) { reverseXaxis(iPhi); } towerIDandShares.insert( {l1t::HGCalTowerID(doNose_, zside, iEta, iPhi).rawId(), double(towerShare) / splitDivisor}); } return towerIDandShares; } else { // for modules not found in the mapping file (currently a few partial modules) use the traditional method. towerIDandShares.insert({getTriggerTowerFromEtaPhi(thesum.position().eta(), thesum.position().phi()), 1.0}); return towerIDandShares; } } }
45.303125
121
0.667035
[ "vector" ]
371b19ac2d7269fea3293baac6d538ab52d287ce
29,438
cpp
C++
renderdoc/driver/d3d12/d3d12_command_queue_wrap.cpp
songtm/renderdoc
7533c6b7ac7cac7cfab2d1a1ddc011c693202a47
[ "MIT" ]
1
2019-11-14T08:52:26.000Z
2019-11-14T08:52:26.000Z
renderdoc/driver/d3d12/d3d12_command_queue_wrap.cpp
songtm/renderdoc
7533c6b7ac7cac7cfab2d1a1ddc011c693202a47
[ "MIT" ]
null
null
null
renderdoc/driver/d3d12/d3d12_command_queue_wrap.cpp
songtm/renderdoc
7533c6b7ac7cac7cfab2d1a1ddc011c693202a47
[ "MIT" ]
null
null
null
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2019 Baldur Karlsson * * 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 "d3d12_command_queue.h" #include "d3d12_command_list.h" #include "d3d12_resources.h" template <typename SerialiserType> bool WrappedID3D12CommandQueue::Serialise_UpdateTileMappings( SerialiserType &ser, ID3D12Resource *pResource, UINT NumResourceRegions, const D3D12_TILED_RESOURCE_COORDINATE *pResourceRegionStartCoordinates, const D3D12_TILE_REGION_SIZE *pResourceRegionSizes, ID3D12Heap *pHeap, UINT NumRanges, const D3D12_TILE_RANGE_FLAGS *pRangeFlags, const UINT *pHeapRangeStartOffsets, const UINT *pRangeTileCounts, D3D12_TILE_MAPPING_FLAGS Flags) { D3D12NOTIMP("Tiled Resources"); return true; } void STDMETHODCALLTYPE WrappedID3D12CommandQueue::UpdateTileMappings( ID3D12Resource *pResource, UINT NumResourceRegions, const D3D12_TILED_RESOURCE_COORDINATE *pResourceRegionStartCoordinates, const D3D12_TILE_REGION_SIZE *pResourceRegionSizes, ID3D12Heap *pHeap, UINT NumRanges, const D3D12_TILE_RANGE_FLAGS *pRangeFlags, const UINT *pHeapRangeStartOffsets, const UINT *pRangeTileCounts, D3D12_TILE_MAPPING_FLAGS Flags) { D3D12NOTIMP("Tiled Resources"); m_pReal->UpdateTileMappings(Unwrap(pResource), NumResourceRegions, pResourceRegionStartCoordinates, pResourceRegionSizes, Unwrap(pHeap), NumRanges, pRangeFlags, pHeapRangeStartOffsets, pRangeTileCounts, Flags); } template <typename SerialiserType> bool WrappedID3D12CommandQueue::Serialise_CopyTileMappings( SerialiserType &ser, ID3D12Resource *pDstResource, const D3D12_TILED_RESOURCE_COORDINATE *pDstRegionStartCoordinate, ID3D12Resource *pSrcResource, const D3D12_TILED_RESOURCE_COORDINATE *pSrcRegionStartCoordinate, const D3D12_TILE_REGION_SIZE *pRegionSize, D3D12_TILE_MAPPING_FLAGS Flags) { D3D12NOTIMP("Tiled Resources"); return true; } void STDMETHODCALLTYPE WrappedID3D12CommandQueue::CopyTileMappings( ID3D12Resource *pDstResource, const D3D12_TILED_RESOURCE_COORDINATE *pDstRegionStartCoordinate, ID3D12Resource *pSrcResource, const D3D12_TILED_RESOURCE_COORDINATE *pSrcRegionStartCoordinate, const D3D12_TILE_REGION_SIZE *pRegionSize, D3D12_TILE_MAPPING_FLAGS Flags) { D3D12NOTIMP("Tiled Resources"); m_pReal->CopyTileMappings(Unwrap(pDstResource), pDstRegionStartCoordinate, Unwrap(pSrcResource), pSrcRegionStartCoordinate, pRegionSize, Flags); } template <typename SerialiserType> bool WrappedID3D12CommandQueue::Serialise_ExecuteCommandLists(SerialiserType &ser, UINT NumCommandLists, ID3D12CommandList *const *ppCommandLists) { ID3D12CommandQueue *pQueue = this; SERIALISE_ELEMENT(pQueue); SERIALISE_ELEMENT(NumCommandLists); SERIALISE_ELEMENT_ARRAY(ppCommandLists, NumCommandLists); { std::vector<DebugMessage> DebugMessages; if(ser.IsWriting()) DebugMessages = m_pDevice->GetDebugMessages(); SERIALISE_ELEMENT(DebugMessages); if(ser.IsReading() && IsLoading(m_State)) { // if we're using replay-time API validation, ignore messages from capture time if(m_pDevice->GetReplayOptions().apiValidation) DebugMessages.clear(); for(const DebugMessage &msg : DebugMessages) m_Cmd.m_EventMessages.push_back(msg); } } SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { ID3D12CommandQueue *real = Unwrap(pQueue); if(m_PrevQueueId != GetResID(pQueue)) { RDCDEBUG("Previous queue execution was on queue %llu, now executing %llu, syncing GPU", m_PrevQueueId, GetResID(pQueue)); if(m_PrevQueueId != ResourceId()) m_pDevice->GPUSync(GetResourceManager()->GetCurrentAs<ID3D12CommandQueue>(m_PrevQueueId)); m_PrevQueueId = GetResID(pQueue); } if(IsLoading(m_State)) { m_Cmd.AddEvent(); // we're adding multiple events, need to increment ourselves m_Cmd.m_RootEventID++; for(uint32_t i = 0; i < NumCommandLists; i++) { ResourceId cmd = GetResourceManager()->GetOriginalID(GetResID(ppCommandLists[i])); if(m_Cmd.m_BakedCmdListInfo[cmd].executeEvents.empty() || m_Cmd.m_BakedCmdListInfo[cmd].executeEvents[0].patched) { ID3D12CommandList *list = Unwrap(ppCommandLists[i]); real->ExecuteCommandLists(1, &list); #if ENABLED(SINGLE_FLUSH_VALIDATE) m_pDevice->GPUSync(); #endif } else { BakedCmdListInfo &info = m_Cmd.m_BakedCmdListInfo[cmd]; // execute the first half of the cracked list ID3D12CommandList *list = Unwrap(info.crackedLists[0]); real->ExecuteCommandLists(1, &list); for(size_t c = 1; c < info.crackedLists.size(); c++) { // ensure all work on all queues has finished m_pDevice->GPUSyncAllQueues(); // readback the patch buffer and perform patching m_ReplayList->PatchExecuteIndirect(info, uint32_t(c - 1)); // execute next list with this indirect. list = Unwrap(info.crackedLists[c]); real->ExecuteCommandLists(1, &list); } #if ENABLED(SINGLE_FLUSH_VALIDATE) m_pDevice->GPUSync(); #endif } } for(uint32_t i = 0; i < NumCommandLists; i++) { ResourceId cmd = GetResID(ppCommandLists[i]); m_pDevice->ApplyBarriers(m_Cmd.m_BakedCmdListInfo[cmd].barriers); } std::string basename = StringFormat::Fmt("ExecuteCommandLists(%u)", NumCommandLists); for(uint32_t c = 0; c < NumCommandLists; c++) { ResourceId cmd = GetResourceManager()->GetOriginalID(GetResID(ppCommandLists[c])); BakedCmdListInfo &cmdListInfo = m_Cmd.m_BakedCmdListInfo[cmd]; // add a fake marker DrawcallDescription draw; draw.name = StringFormat::Fmt("=> %s[%u]: Reset(%s)", basename.c_str(), c, ToStr(cmd).c_str()); draw.flags = DrawFlags::PassBoundary | DrawFlags::BeginPass; m_Cmd.AddEvent(); m_Cmd.m_RootEvents.back().chunkIndex = cmdListInfo.beginChunk; m_Cmd.m_Events.back().chunkIndex = cmdListInfo.beginChunk; m_Cmd.AddDrawcall(draw, true); m_Cmd.m_RootEventID++; // insert the baked command list in-line into this list of notes, assigning new event and // drawIDs m_Cmd.InsertDrawsAndRefreshIDs(cmd, cmdListInfo.draw->children); for(size_t e = 0; e < cmdListInfo.draw->executedCmds.size(); e++) { std::vector<uint32_t> &submits = m_Cmd.m_Partial[D3D12CommandData::Secondary] .cmdListExecs[cmdListInfo.draw->executedCmds[e]]; for(size_t s = 0; s < submits.size(); s++) submits[s] += m_Cmd.m_RootEventID; } for(size_t i = 0; i < cmdListInfo.debugMessages.size(); i++) { DebugMessage msg = cmdListInfo.debugMessages[i]; msg.eventId += m_Cmd.m_RootEventID; m_pDevice->AddDebugMessage(msg); } // only primary command lists can be submitted m_Cmd.m_Partial[D3D12CommandData::Primary].cmdListExecs[cmd].push_back(m_Cmd.m_RootEventID); m_Cmd.m_RootEventID += cmdListInfo.eventCount; m_Cmd.m_RootDrawcallID += cmdListInfo.drawCount; draw.name = StringFormat::Fmt("=> %s[%u]: Close(%s)", basename.c_str(), c, ToStr(cmd).c_str()); draw.flags = DrawFlags::PassBoundary | DrawFlags::EndPass; m_Cmd.AddEvent(); m_Cmd.m_RootEvents.back().chunkIndex = cmdListInfo.endChunk; m_Cmd.m_Events.back().chunkIndex = cmdListInfo.endChunk; m_Cmd.AddDrawcall(draw, true); m_Cmd.m_RootEventID++; } // account for the outer loop thinking we've added one event and incrementing, // since we've done all the handling ourselves this will be off by one. m_Cmd.m_RootEventID--; } else { // account for the queue submit event m_Cmd.m_RootEventID++; uint32_t startEID = m_Cmd.m_RootEventID; // advance m_CurEventID to match the events added when reading for(uint32_t c = 0; c < NumCommandLists; c++) { ResourceId cmd = GetResourceManager()->GetOriginalID(GetResID(ppCommandLists[c])); // 2 extra for the virtual labels around the command list m_Cmd.m_RootEventID += 2 + m_Cmd.m_BakedCmdListInfo[cmd].eventCount; m_Cmd.m_RootDrawcallID += 2 + m_Cmd.m_BakedCmdListInfo[cmd].drawCount; } // same accounting for the outer loop as above m_Cmd.m_RootEventID--; if(NumCommandLists == 0) { // do nothing, don't bother with the logic below } else if(m_Cmd.m_LastEventID <= startEID) { #if ENABLED(VERBOSE_PARTIAL_REPLAY) RDCDEBUG("Queue Submit no replay %u == %u", m_Cmd.m_LastEventID, startEID); #endif } else { #if ENABLED(VERBOSE_PARTIAL_REPLAY) RDCDEBUG("Queue Submit re-recording from %u", m_Cmd.m_RootEventID); #endif uint32_t eid = startEID; std::vector<ID3D12CommandList *> rerecordedCmds; for(uint32_t c = 0; c < NumCommandLists; c++) { ResourceId cmdId = GetResourceManager()->GetOriginalID(GetResID(ppCommandLists[c])); // account for the virtual label at the start of the events here // so it matches up to baseEvent eid++; #if ENABLED(VERBOSE_PARTIAL_REPLAY) uint32_t end = eid + m_Cmd.m_BakedCmdListInfo[cmdId].eventCount; #endif if(eid <= m_Cmd.m_LastEventID) { ID3D12CommandList *cmd = m_Cmd.RerecordCmdList(cmdId); ResourceId rerecord = GetResID(cmd); #if ENABLED(VERBOSE_PARTIAL_REPLAY) RDCDEBUG("Queue submit re-recorded replay of %llu, using %llu (%u -> %u <= %u)", cmdId, rerecord, eid, end, m_Cmd.m_LastEventID); #endif rerecordedCmds.push_back(Unwrap(cmd)); m_pDevice->ApplyBarriers(m_Cmd.m_BakedCmdListInfo[rerecord].barriers); } else { #if ENABLED(VERBOSE_PARTIAL_REPLAY) RDCDEBUG("Queue not submitting %llu", cmdId); #endif } // 1 extra to account for the virtual end command list label (begin is accounted for // above) eid += 1 + m_Cmd.m_BakedCmdListInfo[cmdId].eventCount; } #if ENABLED(SINGLE_FLUSH_VALIDATE) for(size_t i = 0; i < rerecordedCmds.size(); i++) { real->ExecuteCommandLists(1, &rerecordedCmds[i]); m_pDevice->GPUSync(); } #else real->ExecuteCommandLists((UINT)rerecordedCmds.size(), &rerecordedCmds[0]); #endif } } } return true; } void WrappedID3D12CommandQueue::ExecuteCommandLists(UINT NumCommandLists, ID3D12CommandList *const *ppCommandLists) { ExecuteCommandListsInternal(NumCommandLists, ppCommandLists, false, false); } void WrappedID3D12CommandQueue::ExecuteCommandListsInternal(UINT NumCommandLists, ID3D12CommandList *const *ppCommandLists, bool InFrameCaptureBoundary, bool SkipRealExecute) { ID3D12CommandList **unwrapped = m_pDevice->GetTempArray<ID3D12CommandList *>(NumCommandLists); for(UINT i = 0; i < NumCommandLists; i++) unwrapped[i] = Unwrap(ppCommandLists[i]); if(!m_MarkedActive) { m_MarkedActive = true; RenderDoc::Inst().AddActiveDriver(RDCDriver::D3D12, false); } if(IsActiveCapturing(m_State)) m_pDevice->AddCaptureSubmission(); if(!SkipRealExecute) { SERIALISE_TIME_CALL(m_pReal->ExecuteCommandLists(NumCommandLists, unwrapped)); } if(IsCaptureMode(m_State)) { SCOPED_LOCK(m_Lock); if(!InFrameCaptureBoundary) m_pDevice->GetCapTransitionLock().ReadLock(); bool capframe = IsActiveCapturing(m_State); std::set<ResourceId> refdIDs; for(UINT i = 0; i < NumCommandLists; i++) { WrappedID3D12GraphicsCommandList *wrapped = (WrappedID3D12GraphicsCommandList *)ppCommandLists[i]; D3D12ResourceRecord *record = GetRecord(ppCommandLists[i]); if(record->ContainsExecuteIndirect) m_QueueRecord->ContainsExecuteIndirect = true; m_pDevice->ApplyBarriers(record->bakedCommands->cmdInfo->barriers); // need to lock the whole section of code, not just the check on // m_State, as we also need to make sure we don't check the state, // start marking dirty resources then while we're doing so the // state becomes capframe. // the next sections where we mark resources referenced and add // the submit chunk to the frame record don't have to be protected. // Only the decision of whether we're inframe or not, and marking // dirty. for(auto it = record->bakedCommands->cmdInfo->dirtied.begin(); it != record->bakedCommands->cmdInfo->dirtied.end(); ++it) GetResourceManager()->MarkDirtyResource(*it); if(capframe) { // any descriptor copies or writes could reference new resources not in the // bound descs list yet. So we take all of those referenced descriptors and // include them to see if we need to flush std::vector<D3D12Descriptor> dynDescRefs; m_pDevice->GetDynamicDescriptorReferences(dynDescRefs); for(size_t d = 0; d < dynDescRefs.size(); d++) { ResourceId id, id2; FrameRefType ref = eFrameRef_Read; dynDescRefs[d].GetRefIDs(id, id2, ref); if(id != ResourceId()) { refdIDs.insert(id); GetResourceManager()->MarkResourceFrameReferenced(id, ref); } if(id2 != ResourceId()) { refdIDs.insert(id2); GetResourceManager()->MarkResourceFrameReferenced(id2, ref); } } // for each bound descriptor table, mark it referenced as well as all resources currently // bound to it for(auto it = record->bakedCommands->cmdInfo->boundDescs.begin(); it != record->bakedCommands->cmdInfo->boundDescs.end(); ++it) { D3D12Descriptor *desc = *it; ResourceId id, id2; FrameRefType ref = eFrameRef_Read; desc->GetRefIDs(id, id2, ref); if(id != ResourceId()) { refdIDs.insert(id); GetResourceManager()->MarkResourceFrameReferenced(id, ref); } if(id2 != ResourceId()) { refdIDs.insert(id2); GetResourceManager()->MarkResourceFrameReferenced(id2, ref); } } // pull in frame refs from this baked command list record->bakedCommands->AddResourceReferences(GetResourceManager()); record->bakedCommands->AddReferencedIDs(refdIDs); // mark the creation record as referenced so it gets pulled in. GetResourceManager()->MarkResourceFrameReferenced( wrapped->GetCreationRecord()->GetResourceID(), eFrameRef_Read); // reference all executed bundles as well for(size_t b = 0; b < record->bakedCommands->cmdInfo->bundles.size(); b++) { record->bakedCommands->cmdInfo->bundles[b]->bakedCommands->AddResourceReferences( GetResourceManager()); record->bakedCommands->cmdInfo->bundles[b]->bakedCommands->AddReferencedIDs(refdIDs); GetResourceManager()->MarkResourceFrameReferenced( record->bakedCommands->cmdInfo->bundles[b]->GetResourceID(), eFrameRef_Read); record->bakedCommands->cmdInfo->bundles[b]->bakedCommands->AddRef(); } { m_CmdListRecords.push_back(record->bakedCommands); for(size_t sub = 0; sub < record->bakedCommands->cmdInfo->bundles.size(); sub++) m_CmdListRecords.push_back(record->bakedCommands->cmdInfo->bundles[sub]->bakedCommands); } record->bakedCommands->AddRef(); } record->cmdInfo->dirtied.clear(); } if(capframe) { std::vector<MapState> maps = m_pDevice->GetMaps(); for(auto it = maps.begin(); it != maps.end(); ++it) { WrappedID3D12Resource1 *res = GetWrapped(it->res); UINT subres = it->subres; size_t size = (size_t)it->totalSize; // only need to flush memory that could affect this submitted batch of work if(refdIDs.find(res->GetResourceID()) == refdIDs.end()) { RDCDEBUG("Map of memory %llu not referenced in this queue - not flushing", res->GetResourceID()); continue; } size_t diffStart = 0, diffEnd = 0; bool found = true; byte *ref = res->GetShadow(subres); byte *data = res->GetMap(subres); if(ref) found = FindDiffRange(data, ref, size, diffStart, diffEnd); else diffEnd = size; if(found) { RDCLOG("Persistent map flush forced for %llu (%llu -> %llu)", res->GetResourceID(), (uint64_t)diffStart, (uint64_t)diffEnd); D3D12_RANGE range = {diffStart, diffEnd}; m_pDevice->MapDataWrite(res, subres, data, range); if(ref == NULL) { res->AllocShadow(subres, size); ref = res->GetShadow(subres); } // update comparison shadow for next time memcpy(ref, res->GetMap(subres), size); GetResourceManager()->MarkDirtyResource(res->GetResourceID()); } else { RDCDEBUG("Persistent map flush not needed for %llu", res->GetResourceID()); } } { WriteSerialiser &ser = GetThreadSerialiser(); ser.SetDrawChunk(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Queue_ExecuteCommandLists); Serialise_ExecuteCommandLists(ser, NumCommandLists, ppCommandLists); m_QueueRecord->AddChunk(scope.Get()); } } if(!InFrameCaptureBoundary) m_pDevice->GetCapTransitionLock().ReadUnlock(); } } template <typename SerialiserType> bool WrappedID3D12CommandQueue::Serialise_SetMarker(SerialiserType &ser, UINT Metadata, const void *pData, UINT Size) { std::string MarkerText = ""; if(ser.IsWriting() && pData && Size) MarkerText = DecodeMarkerString(Metadata, pData, Size); ID3D12CommandQueue *pQueue = this; SERIALISE_ELEMENT(pQueue); SERIALISE_ELEMENT(MarkerText); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { D3D12MarkerRegion::Set(m_pReal, MarkerText); if(IsLoading(m_State)) { DrawcallDescription draw; draw.name = MarkerText; draw.flags |= DrawFlags::SetMarker; m_Cmd.AddEvent(); m_Cmd.AddDrawcall(draw, false); } } return true; } void STDMETHODCALLTYPE WrappedID3D12CommandQueue::SetMarker(UINT Metadata, const void *pData, UINT Size) { SERIALISE_TIME_CALL(m_pReal->SetMarker(Metadata, pData, Size)); if(IsActiveCapturing(m_State)) { CACHE_THREAD_SERIALISER(); ser.SetDrawChunk(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Queue_SetMarker); Serialise_SetMarker(ser, Metadata, pData, Size); m_QueueRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedID3D12CommandQueue::Serialise_BeginEvent(SerialiserType &ser, UINT Metadata, const void *pData, UINT Size) { std::string MarkerText = ""; if(ser.IsWriting() && pData && Size) MarkerText = DecodeMarkerString(Metadata, pData, Size); ID3D12CommandQueue *pQueue = this; SERIALISE_ELEMENT(pQueue); SERIALISE_ELEMENT(MarkerText); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { D3D12MarkerRegion::Begin(m_pReal, MarkerText); if(IsLoading(m_State)) { DrawcallDescription draw; draw.name = MarkerText; draw.flags |= DrawFlags::PushMarker; m_Cmd.AddEvent(); m_Cmd.AddDrawcall(draw, false); // now push the drawcall stack m_Cmd.GetDrawcallStack().push_back(&m_Cmd.GetDrawcallStack().back()->children.back()); } } return true; } void STDMETHODCALLTYPE WrappedID3D12CommandQueue::BeginEvent(UINT Metadata, const void *pData, UINT Size) { SERIALISE_TIME_CALL(m_pReal->BeginEvent(Metadata, pData, Size)); if(IsActiveCapturing(m_State)) { CACHE_THREAD_SERIALISER(); ser.SetDrawChunk(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Queue_BeginEvent); Serialise_BeginEvent(ser, Metadata, pData, Size); m_QueueRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedID3D12CommandQueue::Serialise_EndEvent(SerialiserType &ser) { ID3D12CommandQueue *pQueue = this; SERIALISE_ELEMENT(pQueue); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { D3D12MarkerRegion::End(m_pReal); if(IsLoading(m_State)) { if(m_Cmd.GetDrawcallStack().size() > 1) m_Cmd.GetDrawcallStack().pop_back(); // Skip - pop marker draws aren't processed otherwise, we just apply them to the drawcall // stack. } } return true; } void STDMETHODCALLTYPE WrappedID3D12CommandQueue::EndEvent() { SERIALISE_TIME_CALL(m_pReal->EndEvent()); if(IsActiveCapturing(m_State)) { CACHE_THREAD_SERIALISER(); ser.SetDrawChunk(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Queue_EndEvent); Serialise_EndEvent(ser); m_QueueRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedID3D12CommandQueue::Serialise_Signal(SerialiserType &ser, ID3D12Fence *pFence, UINT64 Value) { ID3D12CommandQueue *pQueue = this; SERIALISE_ELEMENT(pQueue); SERIALISE_ELEMENT(pFence); SERIALISE_ELEMENT(Value); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading() && pFence) { m_pReal->Signal(Unwrap(pFence), Value); m_pDevice->GPUSync(); } return true; } HRESULT STDMETHODCALLTYPE WrappedID3D12CommandQueue::Signal(ID3D12Fence *pFence, UINT64 Value) { HRESULT ret; SERIALISE_TIME_CALL(ret = m_pReal->Signal(Unwrap(pFence), Value)); if(IsActiveCapturing(m_State)) { SCOPED_LOCK(m_Lock); WriteSerialiser &ser = GetThreadSerialiser(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Queue_Signal); Serialise_Signal(ser, pFence, Value); m_QueueRecord->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(GetResID(pFence), eFrameRef_Read); } return ret; } template <typename SerialiserType> bool WrappedID3D12CommandQueue::Serialise_Wait(SerialiserType &ser, ID3D12Fence *pFence, UINT64 Value) { ID3D12CommandQueue *pQueue = this; SERIALISE_ELEMENT(pQueue); SERIALISE_ELEMENT(pFence); SERIALISE_ELEMENT(Value); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading() && pFence) { m_pDevice->GPUSync(); } return true; } HRESULT STDMETHODCALLTYPE WrappedID3D12CommandQueue::Wait(ID3D12Fence *pFence, UINT64 Value) { HRESULT ret; SERIALISE_TIME_CALL(ret = m_pReal->Wait(Unwrap(pFence), Value)); if(IsActiveCapturing(m_State)) { SCOPED_LOCK(m_Lock); WriteSerialiser &ser = GetThreadSerialiser(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Queue_Wait); Serialise_Wait(ser, pFence, Value); m_QueueRecord->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(GetResID(pFence), eFrameRef_Read); } return ret; } HRESULT STDMETHODCALLTYPE WrappedID3D12CommandQueue::GetTimestampFrequency(UINT64 *pFrequency) { return m_pReal->GetTimestampFrequency(pFrequency); } HRESULT STDMETHODCALLTYPE WrappedID3D12CommandQueue::GetClockCalibration(UINT64 *pGpuTimestamp, UINT64 *pCpuTimestamp) { return m_pReal->GetClockCalibration(pGpuTimestamp, pCpuTimestamp); } HRESULT STDMETHODCALLTYPE WrappedID3D12CommandQueue::Present( _In_ ID3D12GraphicsCommandList *pOpenCommandList, _In_ ID3D12Resource *pSourceTex2D, _In_ HWND hWindow, D3D12_DOWNLEVEL_PRESENT_FLAGS Flags) { // D3D12 on windows 7 if(!RenderDoc::Inst().GetCaptureOptions().allowVSync) { Flags = D3D12_DOWNLEVEL_PRESENT_FLAG_NONE; } // store the timestamp, thread ID etc. Don't store the duration SERIALISE_TIME_CALL(); if(IsCaptureMode(m_State)) { WrappedID3D12GraphicsCommandList *list = (WrappedID3D12GraphicsCommandList *)pOpenCommandList; // add a marker const char str[] = "ID3D12CommandQueueDownlevel::Present()"; list->SetMarker(PIX_EVENT_ANSI_VERSION, str, sizeof(str) - 1); // the list is implicitly closed, serialise that D3D12ResourceRecord *listRecord = GetRecord(list); { CACHE_THREAD_SERIALISER(); ser.SetDrawChunk(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::List_Close); list->Serialise_Close(ser); listRecord->AddChunk(scope.Get()); } listRecord->Bake(); // this queue implicitly submits the list, serialise that ID3D12CommandList *submitlist = list; ExecuteCommandListsInternal(1, &submitlist, false, true); } if(m_pPresentHWND != NULL) { // don't let the device actually release any refs on the resource, just make it release internal // resources m_pPresentSource->AddRef(); m_pDevice->ReleaseSwapchainResources(this, 0, NULL, NULL); } m_pPresentSource = pSourceTex2D; m_pPresentHWND = hWindow; m_pDevice->WrapSwapchainBuffer(this, GetFormat(), 0, m_pPresentSource); m_pDevice->Present(pOpenCommandList, this, Flags == D3D12_DOWNLEVEL_PRESENT_FLAG_WAIT_FOR_VBLANK ? 1 : 0, 0); return m_pDownlevel->Present(Unwrap(pOpenCommandList), Unwrap(pSourceTex2D), hWindow, Flags); } INSTANTIATE_FUNCTION_SERIALISED( void, WrappedID3D12CommandQueue, UpdateTileMappings, ID3D12Resource *pResource, UINT NumResourceRegions, const D3D12_TILED_RESOURCE_COORDINATE *pResourceRegionStartCoordinates, const D3D12_TILE_REGION_SIZE *pResourceRegionSizes, ID3D12Heap *pHeap, UINT NumRanges, const D3D12_TILE_RANGE_FLAGS *pRangeFlags, const UINT *pHeapRangeStartOffsets, const UINT *pRangeTileCounts, D3D12_TILE_MAPPING_FLAGS Flags); INSTANTIATE_FUNCTION_SERIALISED(void, WrappedID3D12CommandQueue, CopyTileMappings, ID3D12Resource *pDstResource, const D3D12_TILED_RESOURCE_COORDINATE *pDstRegionStartCoordinate, ID3D12Resource *pSrcResource, const D3D12_TILED_RESOURCE_COORDINATE *pSrcRegionStartCoordinate, const D3D12_TILE_REGION_SIZE *pRegionSize, D3D12_TILE_MAPPING_FLAGS Flags); INSTANTIATE_FUNCTION_SERIALISED(void, WrappedID3D12CommandQueue, ExecuteCommandLists, UINT NumCommandLists, ID3D12CommandList *const *ppCommandLists); INSTANTIATE_FUNCTION_SERIALISED(void, WrappedID3D12CommandQueue, SetMarker, UINT Metadata, const void *pData, UINT Size); INSTANTIATE_FUNCTION_SERIALISED(void, WrappedID3D12CommandQueue, BeginEvent, UINT Metadata, const void *pData, UINT Size); INSTANTIATE_FUNCTION_SERIALISED(void, WrappedID3D12CommandQueue, EndEvent); INSTANTIATE_FUNCTION_SERIALISED(void, WrappedID3D12CommandQueue, Wait, ID3D12Fence *pFence, UINT64 Value); INSTANTIATE_FUNCTION_SERIALISED(void, WrappedID3D12CommandQueue, Signal, ID3D12Fence *pFence, UINT64 Value); INSTANTIATE_FUNCTION_SERIALISED(void, WrappedID3D12CommandQueue, Wait, ID3D12Fence *pFence, UINT64 Value);
34.190476
103
0.662477
[ "vector" ]
7debccd6e268f00a1ae11133e72cc4ca5e4f3fc9
79,410
cc
C++
src/ui/views/win/hwnd_message_handler.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
src/ui/views/win/hwnd_message_handler.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
null
null
null
src/ui/views/win/hwnd_message_handler.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/win/hwnd_message_handler.h" #include <dwmapi.h> #include <shellapi.h> #include "base/bind.h" #include "base/debug/trace_event.h" #include "base/win/windows_version.h" #include "ui/base/events/event.h" #include "ui/base/events/event_utils.h" #include "ui/base/gestures/gesture_sequence.h" #include "ui/base/keycodes/keyboard_code_conversion_win.h" #include "ui/base/win/hwnd_util.h" #include "ui/base/win/mouse_wheel_util.h" #include "ui/base/win/shell.h" #include "ui/base/win/touch_input.h" #include "ui/gfx/canvas.h" #include "ui/gfx/canvas_skia_paint.h" #include "ui/gfx/icon_util.h" #include "ui/gfx/insets.h" #include "ui/gfx/path.h" #include "ui/gfx/path_win.h" #include "ui/gfx/screen.h" #include "ui/native_theme/native_theme_win.h" #include "ui/views/views_delegate.h" #include "ui/views/widget/monitor_win.h" #include "ui/views/widget/native_widget_win.h" #include "ui/views/widget/widget_hwnd_utils.h" #include "ui/views/win/fullscreen_handler.h" #include "ui/views/win/hwnd_message_handler_delegate.h" #include "ui/views/win/scoped_fullscreen_visibility.h" #if !defined(USE_AURA) #include "ui/views/accessibility/native_view_accessibility_win.h" #include "ui/views/widget/child_window_message_processor.h" #endif namespace views { namespace { // MoveLoopMouseWatcher is used to determine if the user canceled or completed a // move. win32 doesn't appear to offer a way to determine the result of a move, // so we install hooks to determine if we got a mouse up and assume the move // completed. class MoveLoopMouseWatcher { public: explicit MoveLoopMouseWatcher(HWNDMessageHandler* host); ~MoveLoopMouseWatcher(); // Returns true if the mouse is up, or if we couldn't install the hook. bool got_mouse_up() const { return got_mouse_up_; } private: // Instance that owns the hook. We only allow one instance to hook the mouse // at a time. static MoveLoopMouseWatcher* instance_; // Key and mouse callbacks from the hook. static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param); static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param); void Unhook(); // HWNDMessageHandler that created us. HWNDMessageHandler* host_; // Did we get a mouse up? bool got_mouse_up_; // Hook identifiers. HHOOK mouse_hook_; HHOOK key_hook_; DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher); }; // static MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL; MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host) : host_(host), got_mouse_up_(false), mouse_hook_(NULL), key_hook_(NULL) { // Only one instance can be active at a time. if (instance_) instance_->Unhook(); mouse_hook_ = SetWindowsHookEx( WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId()); if (mouse_hook_) { instance_ = this; // We don't care if setting the key hook succeeded. key_hook_ = SetWindowsHookEx( WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId()); } if (instance_ != this) { // Failed installation. Assume we got a mouse up in this case, otherwise // we'll think all drags were canceled. got_mouse_up_ = true; } } MoveLoopMouseWatcher::~MoveLoopMouseWatcher() { Unhook(); } void MoveLoopMouseWatcher::Unhook() { if (instance_ != this) return; DCHECK(mouse_hook_); UnhookWindowsHookEx(mouse_hook_); if (key_hook_) UnhookWindowsHookEx(key_hook_); key_hook_ = NULL; mouse_hook_ = NULL; instance_ = NULL; } // static LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code, WPARAM w_param, LPARAM l_param) { DCHECK(instance_); if (n_code == HC_ACTION && w_param == WM_LBUTTONUP) instance_->got_mouse_up_ = true; return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param); } // static LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code == HC_ACTION && w_param == VK_ESCAPE) { if (base::win::GetVersion() >= base::win::VERSION_VISTA) { int value = TRUE; HRESULT result = DwmSetWindowAttribute( instance_->host_->hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &value, sizeof(value)); } // Hide the window on escape, otherwise the window is visibly going to snap // back to the original location before we close it. // This behavior is specific to tab dragging, in that we generally wouldn't // want this functionality if we have other consumers using this API. instance_->host_->Hide(); } return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param); } // Called from OnNCActivate. BOOL CALLBACK EnumChildWindowsForRedraw(HWND hwnd, LPARAM lparam) { DWORD process_id; GetWindowThreadProcessId(hwnd, &process_id); int flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME; if (process_id == GetCurrentProcessId()) flags |= RDW_UPDATENOW; RedrawWindow(hwnd, NULL, NULL, flags); return TRUE; } bool GetMonitorAndRects(const RECT& rect, HMONITOR* monitor, gfx::Rect* monitor_rect, gfx::Rect* work_area) { DCHECK(monitor); DCHECK(monitor_rect); DCHECK(work_area); *monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL); if (!*monitor) return false; MONITORINFO monitor_info = { 0 }; monitor_info.cbSize = sizeof(monitor_info); GetMonitorInfo(*monitor, &monitor_info); *monitor_rect = gfx::Rect(monitor_info.rcMonitor); *work_area = gfx::Rect(monitor_info.rcWork); return true; } struct FindOwnedWindowsData { HWND window; std::vector<Widget*> owned_widgets; }; BOOL CALLBACK FindOwnedWindowsCallback(HWND hwnd, LPARAM param) { // TODO(beng): resolve wrt aura. #if !defined(USE_AURA) FindOwnedWindowsData* data = reinterpret_cast<FindOwnedWindowsData*>(param); if (GetWindow(hwnd, GW_OWNER) == data->window) { Widget* widget = Widget::GetWidgetForNativeView(hwnd); if (widget) data->owned_widgets.push_back(widget); } #endif return TRUE; } // Enables or disables the menu item for the specified command and menu. void EnableMenuItemByCommand(HMENU menu, UINT command, bool enabled) { UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, command, flags); } // Callback used to notify child windows that the top level window received a // DWMCompositionChanged message. BOOL CALLBACK SendDwmCompositionChanged(HWND window, LPARAM param) { SendMessage(window, WM_DWMCOMPOSITIONCHANGED, 0, 0); return TRUE; } // See comments in OnNCPaint() for details of this struct. struct ClipState { // The window being painted. HWND parent; // DC painting to. HDC dc; // Origin of the window in terms of the screen. int x; int y; }; // See comments in OnNCPaint() for details of this function. static BOOL CALLBACK ClipDCToChild(HWND window, LPARAM param) { ClipState* clip_state = reinterpret_cast<ClipState*>(param); if (GetParent(window) == clip_state->parent && IsWindowVisible(window)) { RECT bounds; GetWindowRect(window, &bounds); ExcludeClipRect(clip_state->dc, bounds.left - clip_state->x, bounds.top - clip_state->y, bounds.right - clip_state->x, bounds.bottom - clip_state->y); } return TRUE; } #if !defined(USE_AURA) // Get the source HWND of the specified message. Depending on the message, the // source HWND is encoded in either the WPARAM or the LPARAM value. HWND GetControlHWNDForMessage(UINT message, WPARAM w_param, LPARAM l_param) { // Each of the following messages can be sent by a child HWND and must be // forwarded to its associated NativeControlWin for handling. switch (message) { case WM_NOTIFY: return reinterpret_cast<NMHDR*>(l_param)->hwndFrom; case WM_COMMAND: return reinterpret_cast<HWND>(l_param); case WM_CONTEXTMENU: return reinterpret_cast<HWND>(w_param); case WM_CTLCOLORBTN: case WM_CTLCOLORSTATIC: return reinterpret_cast<HWND>(l_param); } return NULL; } // Some messages may be sent to us by a child HWND. If this is the case, this // function will forward those messages on to the object associated with the // source HWND and return true, in which case the window procedure must not do // any further processing of the message. If there is no associated // ChildWindowMessageProcessor, the return value will be false and the WndProc // can continue processing the message normally. |l_result| contains the result // of the message processing by the control and must be returned by the WndProc // if the return value is true. bool ProcessChildWindowMessage(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* l_result) { *l_result = 0; HWND control_hwnd = GetControlHWNDForMessage(message, w_param, l_param); if (IsWindow(control_hwnd)) { ChildWindowMessageProcessor* processor = ChildWindowMessageProcessor::Get(control_hwnd); if (processor) return processor->ProcessMessage(message, w_param, l_param, l_result); } return false; } #endif // The thickness of an auto-hide taskbar in pixels. const int kAutoHideTaskbarThicknessPx = 2; // For windows with the standard frame removed, the client area needs to be // different from the window area to avoid a "feature" in Windows's handling of // WM_NCCALCSIZE data. See the comment near the bottom of GetClientAreaInsets // for more details. const int kClientAreaBottomInsetHack = -1; } // namespace // A scoping class that prevents a window from being able to redraw in response // to invalidations that may occur within it for the lifetime of the object. // // Why would we want such a thing? Well, it turns out Windows has some // "unorthodox" behavior when it comes to painting its non-client areas. // Occasionally, Windows will paint portions of the default non-client area // right over the top of the custom frame. This is not simply fixed by handling // WM_NCPAINT/WM_PAINT, with some investigation it turns out that this // rendering is being done *inside* the default implementation of some message // handlers and functions: // . WM_SETTEXT // . WM_SETICON // . WM_NCLBUTTONDOWN // . EnableMenuItem, called from our WM_INITMENU handler // The solution is to handle these messages and call DefWindowProc ourselves, // but prevent the window from being able to update itself for the duration of // the call. We do this with this class, which automatically calls its // associated Window's lock and unlock functions as it is created and destroyed. // See documentation in those methods for the technique used. // // The lock only has an effect if the window was visible upon lock creation, as // it doesn't guard against direct visiblility changes, and multiple locks may // exist simultaneously to handle certain nested Windows messages. // // IMPORTANT: Do not use this scoping object for large scopes or periods of // time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh). // // I would love to hear Raymond Chen's explanation for all this. And maybe a // list of other messages that this applies to ;-) class HWNDMessageHandler::ScopedRedrawLock { public: explicit ScopedRedrawLock(HWNDMessageHandler* owner) : owner_(owner), hwnd_(owner_->hwnd()), was_visible_(owner_->IsVisible()), cancel_unlock_(false), force_(!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION)) { if (was_visible_ && ::IsWindow(hwnd_)) owner_->LockUpdates(force_); } ~ScopedRedrawLock() { if (!cancel_unlock_ && was_visible_ && ::IsWindow(hwnd_)) owner_->UnlockUpdates(force_); } // Cancel the unlock operation, call this if the Widget is being destroyed. void CancelUnlockOperation() { cancel_unlock_ = true; } private: // The owner having its style changed. HWNDMessageHandler* owner_; // The owner's HWND, cached to avoid action after window destruction. HWND hwnd_; // Records the HWND visibility at the time of creation. bool was_visible_; // A flag indicating that the unlock operation was canceled. bool cancel_unlock_; // If true, perform the redraw lock regardless of Aero state. bool force_; DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock); }; //////////////////////////////////////////////////////////////////////////////// // HWNDMessageHandler, public: HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate) : delegate_(delegate), fullscreen_handler_(new FullscreenHandler), close_widget_factory_(this), remove_standard_frame_(false), use_system_default_icon_(false), restore_focus_when_enabled_(false), restored_enabled_(false), previous_cursor_(NULL), active_mouse_tracking_flags_(0), is_right_mouse_pressed_on_caption_(false), lock_updates_count_(0), destroyed_(NULL), ignore_window_pos_changes_(false), ignore_pos_changes_factory_(this), last_monitor_(NULL), use_layered_buffer_(false), layered_alpha_(255), paint_layered_window_factory_(this), can_update_layered_window_(true), is_first_nccalc_(true) { } HWNDMessageHandler::~HWNDMessageHandler() { delegate_ = NULL; if (destroyed_ != NULL) *destroyed_ = true; // Prevent calls back into this class via WNDPROC now that we've been // destroyed. ClearUserData(); } void HWNDMessageHandler::Init(HWND parent, const gfx::Rect& bounds) { TRACE_EVENT0("views", "HWNDMessageHandler::Init"); GetMonitorAndRects(bounds.ToRECT(), &last_monitor_, &last_monitor_rect_, &last_work_area_); // Create the window. WindowImpl::Init(parent, bounds); } void HWNDMessageHandler::InitModalType(ui::ModalType modal_type) { if (modal_type == ui::MODAL_TYPE_NONE) return; // We implement modality by crawling up the hierarchy of windows starting // at the owner, disabling all of them so that they don't receive input // messages. HWND start = ::GetWindow(hwnd(), GW_OWNER); while (start) { ::EnableWindow(start, FALSE); start = ::GetParent(start); } } void HWNDMessageHandler::Close() { if (!IsWindow(hwnd())) return; // No need to do anything. // Let's hide ourselves right away. Hide(); // Modal dialog windows disable their owner windows; re-enable them now so // they can activate as foreground windows upon this window's destruction. RestoreEnabledIfNecessary(); if (!close_widget_factory_.HasWeakPtrs()) { // And we delay the close so that if we are called from an ATL callback, // we don't destroy the window before the callback returned (as the caller // may delete ourselves on destroy and the ATL callback would still // dereference us when the callback returns). base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&HWNDMessageHandler::CloseNow, close_widget_factory_.GetWeakPtr())); } } void HWNDMessageHandler::CloseNow() { // We may already have been destroyed if the selection resulted in a tab // switch which will have reactivated the browser window and closed us, so // we need to check to see if we're still a window before trying to destroy // ourself. if (IsWindow(hwnd())) DestroyWindow(hwnd()); } gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const { RECT r; GetWindowRect(hwnd(), &r); return gfx::Rect(r); } gfx::Rect HWNDMessageHandler::GetClientAreaBoundsInScreen() const { RECT r; GetClientRect(hwnd(), &r); POINT point = { r.left, r.top }; ClientToScreen(hwnd(), &point); return gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top); } gfx::Rect HWNDMessageHandler::GetRestoredBounds() const { // If we're in fullscreen mode, we've changed the normal bounds to the monitor // rect, so return the saved bounds instead. if (fullscreen_handler_->fullscreen()) return fullscreen_handler_->GetRestoreBounds(); gfx::Rect bounds; GetWindowPlacement(&bounds, NULL); return bounds; } void HWNDMessageHandler::GetWindowPlacement( gfx::Rect* bounds, ui::WindowShowState* show_state) const { WINDOWPLACEMENT wp; wp.length = sizeof(wp); const bool succeeded = !!::GetWindowPlacement(hwnd(), &wp); DCHECK(succeeded); if (bounds != NULL) { if (wp.showCmd == SW_SHOWNORMAL) { // GetWindowPlacement can return misleading position if a normalized // window was resized using Aero Snap feature (see comment 9 in bug // 36421). As a workaround, using GetWindowRect for normalized windows. const bool succeeded = GetWindowRect(hwnd(), &wp.rcNormalPosition) != 0; DCHECK(succeeded); *bounds = gfx::Rect(wp.rcNormalPosition); } else { MONITORINFO mi; mi.cbSize = sizeof(mi); const bool succeeded = GetMonitorInfo( MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST), &mi) != 0; DCHECK(succeeded); *bounds = gfx::Rect(wp.rcNormalPosition); // Convert normal position from workarea coordinates to screen // coordinates. bounds->Offset(mi.rcWork.left - mi.rcMonitor.left, mi.rcWork.top - mi.rcMonitor.top); } } if (show_state) { if (wp.showCmd == SW_SHOWMAXIMIZED) *show_state = ui::SHOW_STATE_MAXIMIZED; else if (wp.showCmd == SW_SHOWMINIMIZED) *show_state = ui::SHOW_STATE_MINIMIZED; else *show_state = ui::SHOW_STATE_NORMAL; } } void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds) { LONG style = GetWindowLong(hwnd(), GWL_STYLE); if (style & WS_MAXIMIZE) SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE); SetWindowPos(hwnd(), NULL, bounds.x(), bounds.y(), bounds.width(), bounds.height(), SWP_NOACTIVATE | SWP_NOZORDER); } void HWNDMessageHandler::SetSize(const gfx::Size& size) { SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(), SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE); } void HWNDMessageHandler::CenterWindow(const gfx::Size& size) { HWND parent = GetParent(hwnd()); if (!IsWindow(hwnd())) parent = ::GetWindow(hwnd(), GW_OWNER); ui::CenterAndSizeWindow(parent, hwnd(), size); } void HWNDMessageHandler::SetRegion(HRGN region) { SetWindowRgn(hwnd(), region, TRUE); } void HWNDMessageHandler::StackAbove(HWND other_hwnd) { SetWindowPos(hwnd(), other_hwnd, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); } void HWNDMessageHandler::StackAtTop() { SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); } void HWNDMessageHandler::Show() { if (IsWindow(hwnd())) ShowWindowWithState(ui::SHOW_STATE_INACTIVE); } void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state) { TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState"); DWORD native_show_state; switch (show_state) { case ui::SHOW_STATE_INACTIVE: native_show_state = SW_SHOWNOACTIVATE; break; case ui::SHOW_STATE_MAXIMIZED: native_show_state = SW_SHOWMAXIMIZED; break; case ui::SHOW_STATE_MINIMIZED: native_show_state = SW_SHOWMINIMIZED; break; default: native_show_state = delegate_->GetInitialShowState(); break; } Show(native_show_state); } void HWNDMessageHandler::Show(int show_state) { ShowWindow(hwnd(), show_state); // When launched from certain programs like bash and Windows Live Messenger, // show_state is set to SW_HIDE, so we need to correct that condition. We // don't just change show_state to SW_SHOWNORMAL because MSDN says we must // always first call ShowWindow with the specified value from STARTUPINFO, // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead, // we call ShowWindow again in this case. if (show_state == SW_HIDE) { show_state = SW_SHOWNORMAL; ShowWindow(hwnd(), show_state); } // We need to explicitly activate the window if we've been shown with a state // that should activate, because if we're opened from a desktop shortcut while // an existing window is already running it doesn't seem to be enough to use // one of these flags to activate the window. if (show_state == SW_SHOWNORMAL || show_state == SW_SHOWMAXIMIZED) Activate(); if (!delegate_->HandleInitialFocus()) SetInitialFocus(); } void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect& bounds) { WINDOWPLACEMENT placement = { 0 }; placement.length = sizeof(WINDOWPLACEMENT); placement.showCmd = SW_SHOWMAXIMIZED; placement.rcNormalPosition = bounds.ToRECT(); SetWindowPlacement(hwnd(), &placement); } void HWNDMessageHandler::Hide() { if (IsWindow(hwnd())) { // NOTE: Be careful not to activate any windows here (for example, calling // ShowWindow(SW_HIDE) will automatically activate another window). This // code can be called while a window is being deactivated, and activating // another window will screw up the activation that is already in progress. SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER); if (!GetParent(hwnd())) NotifyOwnedWindowsParentClosing(); } } void HWNDMessageHandler::Maximize() { ExecuteSystemMenuCommand(SC_MAXIMIZE); } void HWNDMessageHandler::Minimize() { ExecuteSystemMenuCommand(SC_MINIMIZE); delegate_->HandleNativeBlur(NULL); } void HWNDMessageHandler::Restore() { ExecuteSystemMenuCommand(SC_RESTORE); } void HWNDMessageHandler::Activate() { if (IsMinimized()) ::ShowWindow(hwnd(), SW_RESTORE); ::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); SetForegroundWindow(hwnd()); } void HWNDMessageHandler::Deactivate() { HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT); if (next_hwnd) ::SetForegroundWindow(next_hwnd); } void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) { ::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } bool HWNDMessageHandler::IsVisible() const { return !!::IsWindowVisible(hwnd()); } bool HWNDMessageHandler::IsActive() const { return GetActiveWindow() == hwnd(); } bool HWNDMessageHandler::IsMinimized() const { return !!::IsIconic(hwnd()); } bool HWNDMessageHandler::IsMaximized() const { return !!::IsZoomed(hwnd()); } bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset) { ReleaseCapture(); MoveLoopMouseWatcher watcher(this); SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002, GetMessagePos()); // Windows doesn't appear to offer a way to determine whether the user // canceled the move or not. We assume if the user released the mouse it was // successful. return watcher.got_mouse_up(); } void HWNDMessageHandler::EndMoveLoop() { SendMessage(hwnd(), WM_CANCELMODE, 0, 0); } void HWNDMessageHandler::SendFrameChanged() { SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER); } void HWNDMessageHandler::FlashFrame(bool flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = hwnd(); if (flash) { fwi.dwFlags = FLASHW_ALL; fwi.uCount = 4; fwi.dwTimeout = 0; } else { fwi.dwFlags = FLASHW_STOP; } FlashWindowEx(&fwi); } void HWNDMessageHandler::ClearNativeFocus() { ::SetFocus(hwnd()); } void HWNDMessageHandler::SetCapture() { DCHECK(!HasCapture()); ::SetCapture(hwnd()); } void HWNDMessageHandler::ReleaseCapture() { if (HasCapture()) ::ReleaseCapture(); } bool HWNDMessageHandler::HasCapture() const { return ::GetCapture() == hwnd(); } void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) { if (base::win::GetVersion() >= base::win::VERSION_VISTA) { int dwm_value = enabled ? FALSE : TRUE; DwmSetWindowAttribute( hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value, sizeof(dwm_value)); } } void HWNDMessageHandler::SetTitle(const string16& title) { SetWindowText(hwnd(), title.c_str()); } void HWNDMessageHandler::SetCursor(HCURSOR cursor) { if (cursor) { previous_cursor_ = ::SetCursor(cursor); } else if (previous_cursor_) { ::SetCursor(previous_cursor_); previous_cursor_ = NULL; } } void HWNDMessageHandler::FrameTypeChanged() { // Called when the frame type could possibly be changing (theme change or // DWM composition change). if (base::win::GetVersion() >= base::win::VERSION_VISTA) { // We need to toggle the rendering policy of the DWM/glass frame as we // change from opaque to glass. "Non client rendering enabled" means that // the DWM's glass non-client rendering is enabled, which is why // DWMNCRP_ENABLED is used for the native frame case. _DISABLED means the // DWM doesn't render glass, and so is used in the custom frame case. DWMNCRENDERINGPOLICY policy = !delegate_->IsUsingCustomFrame() ? DWMNCRP_ENABLED : DWMNCRP_DISABLED; DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY, &policy, sizeof(DWMNCRENDERINGPOLICY)); } ResetWindowRegion(true); // The non-client view needs to update too. delegate_->HandleFrameChanged(); // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want // to notify our children too, since we can have MDI child windows who need to // update their appearance. EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL); } void HWNDMessageHandler::SchedulePaintInRect(const gfx::Rect& rect) { if (use_layered_buffer_) { // We must update the back-buffer immediately, since Windows' handling of // invalid rects is somewhat mysterious. invalid_rect_.Union(rect); // In some situations, such as drag and drop, when Windows itself runs a // nested message loop our message loop appears to be starved and we don't // receive calls to DidProcessMessage(). This only seems to affect layered // windows, so we schedule a redraw manually using a task, since those never // seem to be starved. Also, wtf. if (!paint_layered_window_factory_.HasWeakPtrs()) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&HWNDMessageHandler::RedrawLayeredWindowContents, paint_layered_window_factory_.GetWeakPtr())); } } else { // InvalidateRect() expects client coordinates. RECT r = rect.ToRECT(); InvalidateRect(hwnd(), &r, FALSE); } } void HWNDMessageHandler::SetOpacity(BYTE opacity) { layered_alpha_ = opacity; } void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) { if (!window_icon.isNull()) { HICON windows_icon = IconUtil::CreateHICONFromSkBitmap( *window_icon.bitmap()); // We need to make sure to destroy the previous icon, otherwise we'll leak // these GDI objects until we crash! HICON old_icon = reinterpret_cast<HICON>( SendMessage(hwnd(), WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(windows_icon))); if (old_icon) DestroyIcon(old_icon); } if (!app_icon.isNull()) { HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap()); HICON old_icon = reinterpret_cast<HICON>( SendMessage(hwnd(), WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(windows_icon))); if (old_icon) DestroyIcon(old_icon); } } //////////////////////////////////////////////////////////////////////////////// // HWNDMessageHandler, InputMethodDelegate implementation: void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent& key) { SetMsgHandled(delegate_->HandleKeyEvent(key)); } //////////////////////////////////////////////////////////////////////////////// // HWNDMessageHandler, ui::WindowImpl overrides: HICON HWNDMessageHandler::GetDefaultWindowIcon() const { if (use_system_default_icon_) return NULL; return ViewsDelegate::views_delegate ? ViewsDelegate::views_delegate->GetDefaultWindowIcon() : NULL; } LRESULT HWNDMessageHandler::OnWndProc(UINT message, WPARAM w_param, LPARAM l_param) { HWND window = hwnd(); LRESULT result = 0; if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result)) return result; #if !defined(USE_AURA) // First allow messages sent by child controls to be processed directly by // their associated views. If such a view is present, it will handle the // message *instead of* this NativeWidgetWin. if (ProcessChildWindowMessage(message, w_param, l_param, &result)) return result; #endif // Otherwise we handle everything else. if (!ProcessWindowMessage(window, message, w_param, l_param, result)) result = DefWindowProc(window, message, w_param, l_param); // DefWindowProc() may have destroyed the window in a nested message loop. if (!::IsWindow(window)) return result; if (delegate_) delegate_->PostHandleMSG(message, w_param, l_param); if (message == WM_NCDESTROY) { base::MessageLoopForUI::current()->RemoveObserver(this); if (delegate_) delegate_->HandleDestroyed(); } // Only top level widget should store/restore focus. if (message == WM_ACTIVATE && delegate_->CanSaveFocus()) PostProcessActivateMessage(LOWORD(w_param)); if (message == WM_ENABLE && restore_focus_when_enabled_) { // This path should be executed only for top level as // restore_focus_when_enabled_ is set in PostProcessActivateMessage. DCHECK(delegate_->CanSaveFocus()); restore_focus_when_enabled_ = false; delegate_->RestoreFocusOnEnable(); } return result; } //////////////////////////////////////////////////////////////////////////////// // HWNDMessageHandler, MessageLoopForUI::Observer implementation: base::EventStatus HWNDMessageHandler::WillProcessEvent( const base::NativeEvent& event) { return base::EVENT_CONTINUE; } void HWNDMessageHandler::DidProcessEvent(const base::NativeEvent& event) { RedrawInvalidRect(); } //////////////////////////////////////////////////////////////////////////////// // HWNDMessageHandler, private: void HWNDMessageHandler::SetInitialFocus() { if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) && !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) { // The window does not get keyboard messages unless we focus it. SetFocus(hwnd()); } } void HWNDMessageHandler::PostProcessActivateMessage(int activation_state) { DCHECK(delegate_->CanSaveFocus()); if (WA_INACTIVE == activation_state) { // We might get activated/inactivated without being enabled, so we need to // clear restore_focus_when_enabled_. restore_focus_when_enabled_ = false; delegate_->SaveFocusOnDeactivate(); } else { // We must restore the focus after the message has been DefProc'ed as it // does set the focus to the last focused HWND. // Note that if the window is not enabled, we cannot restore the focus as // calling ::SetFocus on a child of the non-enabled top-window would fail. // This is the case when showing a modal dialog (such as 'open file', // 'print'...) from a different thread. // In that case we delay the focus restoration to when the window is enabled // again. if (!IsWindowEnabled(hwnd())) { DCHECK(!restore_focus_when_enabled_); restore_focus_when_enabled_ = true; return; } delegate_->RestoreFocusOnActivate(); } } void HWNDMessageHandler::RestoreEnabledIfNecessary() { if (delegate_->IsModal() && !restored_enabled_) { restored_enabled_ = true; // If we were run modally, we need to undo the disabled-ness we inflicted on // the owner's parent hierarchy. HWND start = ::GetWindow(hwnd(), GW_OWNER); while (start) { ::EnableWindow(start, TRUE); start = ::GetParent(start); } } } void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) { if (command) SendMessage(hwnd(), WM_SYSCOMMAND, command, 0); } void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) { // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE // when the user moves the mouse outside this HWND's bounds. if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) { if (mouse_tracking_flags & TME_CANCEL) { // We're about to cancel active mouse tracking, so empty out the stored // state. active_mouse_tracking_flags_ = 0; } else { active_mouse_tracking_flags_ = mouse_tracking_flags; } TRACKMOUSEEVENT tme; tme.cbSize = sizeof(tme); tme.dwFlags = mouse_tracking_flags; tme.hwndTrack = hwnd(); tme.dwHoverTime = 0; TrackMouseEvent(&tme); } else if (mouse_tracking_flags != active_mouse_tracking_flags_) { TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL); TrackMouseEvents(mouse_tracking_flags); } } void HWNDMessageHandler::ClientAreaSizeChanged() { RECT r = {0, 0, 0, 0}; // In case of minimized window GetWindowRect can return normally unexpected // coordinates. if (!IsMinimized()) { if (delegate_->WidgetSizeIsClientSize()) { GetClientRect(hwnd(), &r); // This is needed due to a hack that works around a "feature" in // Windows's handling of WM_NCCALCSIZE. See the comment near the end of // GetClientAreaInsets for more details. if (remove_standard_frame_ && !IsMaximized()) r.bottom += kClientAreaBottomInsetHack; } else { GetWindowRect(hwnd(), &r); } } gfx::Size s(std::max(0, static_cast<int>(r.right - r.left)), std::max(0, static_cast<int>(r.bottom - r.top))); delegate_->HandleClientSizeChanged(s); if (use_layered_buffer_) { layered_window_contents_.reset( new gfx::Canvas(s, ui::SCALE_FACTOR_100P, false)); } } gfx::Insets HWNDMessageHandler::GetClientAreaInsets() const { gfx::Insets insets; if (delegate_->GetClientAreaInsets(&insets)) return insets; DCHECK(insets.empty()); // Returning an empty Insets object causes the default handling in // NativeWidgetWin::OnNCCalcSize() to be invoked. if (!delegate_->IsWidgetWindow() || (!delegate_->IsUsingCustomFrame() && !remove_standard_frame_)) { return insets; } if (IsMaximized()) { // Windows automatically adds a standard width border to all sides when a // window is maximized. int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME); if (remove_standard_frame_) border_thickness -= 1; return gfx::Insets(border_thickness, border_thickness, border_thickness, border_thickness); } // Returning empty insets for a window with the standard frame removed seems // to cause Windows to treat the window specially, treating black as // transparent and changing around some of the painting logic. I suspect it's // some sort of horrible backwards-compatability hack, but the upshot of it // is that if the insets are empty then in certain conditions (it seems to // be subtly related to timing), the contents of windows with the standard // frame removed will flicker to transparent during resize. // // To work around this, we increase the size of the client area by 1px // *beyond* the bottom of the window. This prevents Windows from having a // hissy fit and flashing the window incessantly during resizes, but it also // means that the client area is reported 1px larger than it really is, so // user code has to compensate by making its content shorter if it wants // everything to appear inside the window. if (remove_standard_frame_) return gfx::Insets(0, 0, IsMaximized() ? 0 : kClientAreaBottomInsetHack, 0); // This is weird, but highly essential. If we don't offset the bottom edge // of the client rect, the window client area and window area will match, // and when returning to glass rendering mode from non-glass, the client // area will not paint black as transparent. This is because (and I don't // know why) the client area goes from matching the window rect to being // something else. If the client area is not the window rect in both // modes, the blackness doesn't occur. Because of this, we need to tell // the RootView to lay out to fit the window rect, rather than the client // rect when using the opaque frame. // Note: this is only required for non-fullscreen windows. Note that // fullscreen windows are in restored state, not maximized. return gfx::Insets(0, 0, fullscreen_handler_->fullscreen() ? 0 : 1, 0); } void HWNDMessageHandler::ResetWindowRegion(bool force) { // A native frame uses the native window region, and we don't want to mess // with it. if (!delegate_->IsUsingCustomFrame() || !delegate_->IsWidgetWindow()) { if (force) SetWindowRgn(hwnd(), NULL, TRUE); return; } // Changing the window region is going to force a paint. Only change the // window region if the region really differs. HRGN current_rgn = CreateRectRgn(0, 0, 0, 0); int current_rgn_result = GetWindowRgn(hwnd(), current_rgn); CRect window_rect; GetWindowRect(hwnd(), &window_rect); HRGN new_region; if (IsMaximized()) { HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST); MONITORINFO mi; mi.cbSize = sizeof mi; GetMonitorInfo(monitor, &mi); CRect work_rect = mi.rcWork; work_rect.OffsetRect(-window_rect.left, -window_rect.top); new_region = CreateRectRgnIndirect(&work_rect); } else { gfx::Path window_mask; delegate_->GetWindowMask( gfx::Size(window_rect.Width(), window_rect.Height()), &window_mask); new_region = gfx::CreateHRGNFromSkPath(window_mask); } if (current_rgn_result == ERROR || !EqualRgn(current_rgn, new_region)) { // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion. SetWindowRgn(hwnd(), new_region, TRUE); } else { DeleteObject(new_region); } DeleteObject(current_rgn); } LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message, WPARAM w_param, LPARAM l_param) { ScopedRedrawLock lock(this); // The Widget and HWND can be destroyed in the call to DefWindowProc, so use // the |destroyed_| flag to avoid unlocking (and crashing) after destruction. bool destroyed = false; destroyed_ = &destroyed; LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param); if (destroyed) lock.CancelUnlockOperation(); else destroyed_ = NULL; return result; } void HWNDMessageHandler::NotifyOwnedWindowsParentClosing() { FindOwnedWindowsData data; data.window = hwnd(); EnumThreadWindows(GetCurrentThreadId(), FindOwnedWindowsCallback, reinterpret_cast<LPARAM>(&data)); for (size_t i = 0; i < data.owned_widgets.size(); ++i) data.owned_widgets[i]->OnOwnerClosing(); } void HWNDMessageHandler::LockUpdates(bool force) { // We skip locked updates when Aero is on for two reasons: // 1. Because it isn't necessary // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is // attempting to present a child window's backbuffer onscreen. When these // two actions race with one another, the child window will either flicker // or will simply stop updating entirely. if ((force || !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_ == 1) { SetWindowLong(hwnd(), GWL_STYLE, GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE); } } void HWNDMessageHandler::UnlockUpdates(bool force) { if ((force || !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_ <= 0) { SetWindowLong(hwnd(), GWL_STYLE, GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE); lock_updates_count_ = 0; } } void HWNDMessageHandler::RedrawInvalidRect() { if (!use_layered_buffer_) { RECT r = { 0, 0, 0, 0 }; if (GetUpdateRect(hwnd(), &r, FALSE) && !IsRectEmpty(&r)) { RedrawWindow(hwnd(), &r, NULL, RDW_INVALIDATE | RDW_UPDATENOW | RDW_NOCHILDREN); } } } void HWNDMessageHandler::RedrawLayeredWindowContents() { if (invalid_rect_.IsEmpty()) return; // We need to clip to the dirty rect ourselves. layered_window_contents_->sk_canvas()->save(SkCanvas::kClip_SaveFlag); layered_window_contents_->ClipRect(invalid_rect_); delegate_->PaintLayeredWindow(layered_window_contents_.get()); layered_window_contents_->sk_canvas()->restore(); RECT wr; GetWindowRect(hwnd(), &wr); SIZE size = {wr.right - wr.left, wr.bottom - wr.top}; POINT position = {wr.left, wr.top}; HDC dib_dc = skia::BeginPlatformPaint(layered_window_contents_->sk_canvas()); POINT zero = {0, 0}; BLENDFUNCTION blend = {AC_SRC_OVER, 0, layered_alpha_, AC_SRC_ALPHA}; UpdateLayeredWindow(hwnd(), NULL, &position, &size, dib_dc, &zero, RGB(0xFF, 0xFF, 0xFF), &blend, ULW_ALPHA); invalid_rect_.SetRect(0, 0, 0, 0); skia::EndPlatformPaint(layered_window_contents_->sk_canvas()); } // Message handlers ------------------------------------------------------------ void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) { if (delegate_->IsWidgetWindow() && !active && thread_id != GetCurrentThreadId()) { delegate_->HandleAppDeactivated(); // Also update the native frame if it is rendering the non-client area. if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0); } } BOOL HWNDMessageHandler::OnAppCommand(HWND window, short command, WORD device, int keystate) { BOOL handled = !!delegate_->HandleAppCommand(command); SetMsgHandled(handled); // Make sure to return TRUE if the event was handled or in some cases the // system will execute the default handler which can cause bugs like going // forward or back two pages instead of one. return handled; } void HWNDMessageHandler::OnCancelMode() { delegate_->HandleCancelMode(); // Need default handling, otherwise capture and other things aren't canceled. SetMsgHandled(FALSE); } void HWNDMessageHandler::OnCaptureChanged(HWND window) { delegate_->HandleCaptureLost(); } void HWNDMessageHandler::OnClose() { delegate_->HandleClose(); } void HWNDMessageHandler::OnCommand(UINT notification_code, int command, HWND window) { // If the notification code is > 1 it means it is control specific and we // should ignore it. if (notification_code > 1 || delegate_->HandleAppCommand(command)) SetMsgHandled(FALSE); } LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) { use_layered_buffer_ = !!(window_ex_style() & WS_EX_LAYERED); #if defined(USE_AURA) if (window_ex_style() & WS_EX_COMPOSITED) { if (base::win::GetVersion() >= base::win::VERSION_VISTA) { // This is part of the magic to emulate layered windows with Aura // see the explanation elsewere when we set WS_EX_COMPOSITED style. MARGINS margins = {-1,-1,-1,-1}; DwmExtendFrameIntoClientArea(hwnd(), &margins); } } #endif fullscreen_handler_->set_hwnd(hwnd()); // This message initializes the window so that focus border are shown for // windows. SendMessage(hwnd(), WM_CHANGEUISTATE, MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS), 0); // Bug 964884: detach the IME attached to this window. // We should attach IMEs only when we need to input CJK strings. ImmAssociateContextEx(hwnd(), NULL, 0); if (remove_standard_frame_) { SetWindowLong(hwnd(), GWL_STYLE, GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION); SendFrameChanged(); } // Get access to a modifiable copy of the system menu. GetSystemMenu(hwnd(), false); if (base::win::GetVersion() >= base::win::VERSION_WIN7) RegisterTouchWindow(hwnd(), 0); // We need to allow the delegate to size its contents since the window may not // receive a size notification when its initial bounds are specified at window // creation time. ClientAreaSizeChanged(); // We need to add ourselves as a message loop observer so that we can repaint // aggressively if the contents of our window become invalid. Unfortunately // WM_PAINT messages are starved and we get flickery redrawing when resizing // if we do not do this. base::MessageLoopForUI::current()->AddObserver(this); delegate_->HandleCreate(); // TODO(beng): move more of NWW::OnCreate here. return 0; } void HWNDMessageHandler::OnDestroy() { delegate_->HandleDestroying(); } void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel, const CSize& screen_size) { delegate_->HandleDisplayChange(); } LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg, WPARAM w_param, LPARAM l_param) { if (!delegate_->IsWidgetWindow()) { SetMsgHandled(FALSE); return 0; } // For some reason, we need to hide the window while we're changing the frame // type only when we're changing it in response to WM_DWMCOMPOSITIONCHANGED. // If we don't, the client area will be filled with black. I'm suspecting // something skia-ey. // Frame type toggling caused by the user (e.g. switching theme) doesn't seem // to have this requirement. FrameTypeChanged(); return 0; } void HWNDMessageHandler::OnEnterSizeMove() { delegate_->HandleBeginWMSizeMove(); SetMsgHandled(FALSE); } LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) { // Needed to prevent resize flicker. return 1; } void HWNDMessageHandler::OnExitSizeMove() { delegate_->HandleEndWMSizeMove(); SetMsgHandled(FALSE); } void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) { gfx::Size min_window_size; gfx::Size max_window_size; delegate_->GetMinMaxSize(&min_window_size, &max_window_size); // Add the native frame border size to the minimum and maximum size if the // view reports its size as the client size. if (delegate_->WidgetSizeIsClientSize()) { CRect client_rect, window_rect; GetClientRect(hwnd(), &client_rect); GetWindowRect(hwnd(), &window_rect); // Due to the client area bottom inset hack (detailed elsewhere), adjust // the reported size of the client area in the case that the standard frame // has been removed. if (remove_standard_frame_) client_rect.bottom += kClientAreaBottomInsetHack; window_rect -= client_rect; min_window_size.Enlarge(window_rect.Width(), window_rect.Height()); if (!max_window_size.IsEmpty()) max_window_size.Enlarge(window_rect.Width(), window_rect.Height()); } minmax_info->ptMinTrackSize.x = min_window_size.width(); minmax_info->ptMinTrackSize.y = min_window_size.height(); if (max_window_size.width() || max_window_size.height()) { if (!max_window_size.width()) max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK)); if (!max_window_size.height()) max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK)); minmax_info->ptMaxTrackSize.x = max_window_size.width(); minmax_info->ptMaxTrackSize.y = max_window_size.height(); } SetMsgHandled(FALSE); } LRESULT HWNDMessageHandler::OnGetObject(UINT message, WPARAM w_param, LPARAM l_param) { LRESULT reference_result = static_cast<LRESULT>(0L); // Accessibility readers will send an OBJID_CLIENT message if (OBJID_CLIENT == l_param) { // Retrieve MSAA dispatch object for the root view. base::win::ScopedComPtr<IAccessible> root( delegate_->GetNativeViewAccessible()); // Create a reference that MSAA will marshall to the client. reference_result = LresultFromObject(IID_IAccessible, w_param, static_cast<IAccessible*>(root.Detach())); } return reference_result; } LRESULT HWNDMessageHandler::OnImeMessages(UINT message, WPARAM w_param, LPARAM l_param) { LRESULT result = 0; SetMsgHandled(delegate_->HandleIMEMessage( message, w_param, l_param, &result)); return result; } void HWNDMessageHandler::OnInitMenu(HMENU menu) { bool is_fullscreen = fullscreen_handler_->fullscreen(); bool is_minimized = IsMinimized(); bool is_maximized = IsMaximized(); bool is_restored = !is_fullscreen && !is_minimized && !is_maximized; ScopedRedrawLock lock(this); EnableMenuItemByCommand(menu, SC_RESTORE, is_minimized || is_maximized); EnableMenuItemByCommand(menu, SC_MOVE, is_restored); EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored); EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() && !is_fullscreen && !is_maximized); EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMaximize() && !is_minimized); } void HWNDMessageHandler::OnInputLangChange(DWORD character_set, HKL input_language_id) { delegate_->HandleInputLanguageChange(character_set, input_language_id); } LRESULT HWNDMessageHandler::OnKeyEvent(UINT message, WPARAM w_param, LPARAM l_param) { MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() }; ui::KeyEvent key(msg, message == WM_CHAR); if (!delegate_->HandleUntranslatedKeyEvent(key)) DispatchKeyEventPostIME(key); return 0; } void HWNDMessageHandler::OnKillFocus(HWND focused_window) { delegate_->HandleNativeBlur(focused_window); SetMsgHandled(FALSE); } LRESULT HWNDMessageHandler::OnMouseActivate(UINT message, WPARAM w_param, LPARAM l_param) { // TODO(beng): resolve this with the GetWindowLong() check on the subsequent // line. if (delegate_->IsWidgetWindow()) return delegate_->CanActivate() ? MA_ACTIVATE : MA_NOACTIVATEANDEAT; if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE) return MA_NOACTIVATE; SetMsgHandled(FALSE); return MA_ACTIVATE; } LRESULT HWNDMessageHandler::OnMouseRange(UINT message, WPARAM w_param, LPARAM l_param) { #if defined(USE_AURA) // We handle touch events on Windows Aura. Ignore synthesized mouse messages // from Windows. if (!touch_ids_.empty() || ui::IsMouseEventFromTouch(message)) return 0; #endif if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) { is_right_mouse_pressed_on_caption_ = false; ReleaseCapture(); // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu() // expect screen coordinates. CPoint screen_point(l_param); MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1); w_param = SendMessage(hwnd(), WM_NCHITTEST, 0, MAKELPARAM(screen_point.x, screen_point.y)); if (w_param == HTCAPTION || w_param == HTSYSMENU) { ui::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point)); return 0; } } else if (message == WM_NCLBUTTONDOWN && delegate_->IsUsingCustomFrame()) { switch (w_param) { case HTCLOSE: case HTMINBUTTON: case HTMAXBUTTON: { // When the mouse is pressed down in these specific non-client areas, // we need to tell the RootView to send the mouse pressed event (which // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_ // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be // sent by the applicable button's ButtonListener. We _have_ to do this // way rather than letting Windows just send the syscommand itself (as // would happen if we never did this dance) because for some insane // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed // window control button appearance, in the Windows classic style, over // our view! Ick! By handling this message we prevent Windows from // doing this undesirable thing, but that means we need to roll the // sys-command handling ourselves. // Combine |w_param| with common key state message flags. w_param |= base::win::IsCtrlPressed() ? MK_CONTROL : 0; w_param |= base::win::IsShiftPressed() ? MK_SHIFT : 0; } } } else if (message == WM_NCRBUTTONDOWN && (w_param == HTCAPTION || w_param == HTSYSMENU)) { is_right_mouse_pressed_on_caption_ = true; // We SetCapture() to ensure we only show the menu when the button // down and up are both on the caption. Note: this causes the button up to // be WM_RBUTTONUP instead of WM_NCRBUTTONUP. SetCapture(); } MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime(), { GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param) } }; ui::MouseEvent event(msg); if (!touch_ids_.empty() || ui::IsMouseEventFromTouch(message)) event.set_flags(event.flags() | ui::EF_FROM_TOUCH); if (!(event.flags() & ui::EF_IS_NON_CLIENT)) delegate_->HandleTooltipMouseMove(message, w_param, l_param); if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture()) { // Windows only fires WM_MOUSELEAVE events if the application begins // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events. // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE. TrackMouseEvents((message == WM_NCMOUSEMOVE) ? TME_NONCLIENT | TME_LEAVE : TME_LEAVE); } else if (event.type() == ui::ET_MOUSE_EXITED) { // Reset our tracking flags so future mouse movement over this // NativeWidgetWin results in a new tracking session. Fall through for // OnMouseEvent. active_mouse_tracking_flags_ = 0; } else if (event.type() == ui::ET_MOUSEWHEEL) { // Reroute the mouse wheel to the window under the pointer if applicable. return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) || delegate_->HandleMouseEvent(ui::MouseWheelEvent(msg))) ? 0 : 1; } bool handled = delegate_->HandleMouseEvent(event); if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU && delegate_->IsUsingCustomFrame()) { // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround. // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we // need to call it inside a ScopedRedrawLock. This may cause other negative // side-effects (ex/ stifling non-client mouse releases). DefWindowProcWithRedrawLock(message, w_param, l_param); handled = true; } SetMsgHandled(handled); return 0; } void HWNDMessageHandler::OnMove(const CPoint& point) { delegate_->HandleMove(); SetMsgHandled(FALSE); } void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) { delegate_->HandleMove(); } LRESULT HWNDMessageHandler::OnNCActivate(BOOL active) { if (delegate_->CanActivate()) delegate_->HandleActivationChanged(!!active); if (!delegate_->IsWidgetWindow()) { SetMsgHandled(FALSE); return 0; } if (!delegate_->CanActivate()) return TRUE; // On activation, lift any prior restriction against rendering as inactive. bool inactive_rendering_disabled = delegate_->IsInactiveRenderingDisabled(); if (active && inactive_rendering_disabled) delegate_->EnableInactiveRendering(); if (delegate_->IsUsingCustomFrame()) { // TODO(beng, et al): Hack to redraw this window and child windows // synchronously upon activation. Not all child windows are redrawing // themselves leading to issues like http://crbug.com/74604 // We redraw out-of-process HWNDs asynchronously to avoid hanging the // whole app if a child HWND belonging to a hung plugin is encountered. RedrawWindow(hwnd(), NULL, NULL, RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW); EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL); } // The frame may need to redraw as a result of the activation change. // We can get WM_NCACTIVATE before we're actually visible. If we're not // visible, no need to paint. if (IsVisible()) delegate_->SchedulePaint(); // Avoid DefWindowProc non-client rendering over our custom frame on newer // Windows versions only (breaks taskbar activation indication on XP/Vista). if (delegate_->IsUsingCustomFrame() && base::win::GetVersion() > base::win::VERSION_VISTA) { SetMsgHandled(TRUE); return TRUE; } return DefWindowProcWithRedrawLock( WM_NCACTIVATE, inactive_rendering_disabled || active, 0); } LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) { // We only override the default handling if we need to specify a custom // non-client edge width. Note that in most cases "no insets" means no // custom width, but in fullscreen mode or when the NonClientFrameView // requests it, we want a custom width of 0. // Let User32 handle the first nccalcsize for captioned windows // so it updates its internal structures (specifically caption-present) // Without this Tile & Cascade windows won't work. // See http://code.google.com/p/chromium/issues/detail?id=900 if (is_first_nccalc_) { is_first_nccalc_ = false; if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) { SetMsgHandled(FALSE); return 0; } } gfx::Insets insets = GetClientAreaInsets(); if (insets.empty() && !fullscreen_handler_->fullscreen() && !(mode && remove_standard_frame_)) { SetMsgHandled(FALSE); return 0; } RECT* client_rect = mode ? &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) : reinterpret_cast<RECT*>(l_param); client_rect->left += insets.left(); client_rect->top += insets.top(); client_rect->bottom -= insets.bottom(); client_rect->right -= insets.right(); if (IsMaximized()) { // Find all auto-hide taskbars along the screen edges and adjust in by the // thickness of the auto-hide taskbar on each such edge, so the window isn't // treated as a "fullscreen app", which would cause the taskbars to // disappear. HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL); if (!monitor) { // We might end up here if the window was previously minimized and the // user clicks on the taskbar button to restore it in the previously // maximized position. In that case WM_NCCALCSIZE is sent before the // window coordinates are restored to their previous values, so our // (left,top) would probably be (-32000,-32000) like all minimized // windows. So the above MonitorFromWindow call fails, but if we check // the window rect given with WM_NCCALCSIZE (which is our previous // restored window position) we will get the correct monitor handle. monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL); if (!monitor) { // This is probably an extreme case that we won't hit, but if we don't // intersect any monitor, let us not adjust the client rect since our // window will not be visible anyway. return 0; } } if (GetTopmostAutoHideTaskbarForEdge(ABE_LEFT, monitor)) client_rect->left += kAutoHideTaskbarThicknessPx; if (GetTopmostAutoHideTaskbarForEdge(ABE_TOP, monitor)) { if (!delegate_->IsUsingCustomFrame()) { // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of // WM_NCHITTEST, having any nonclient area atop the window causes the // caption buttons to draw onscreen but not respond to mouse // hover/clicks. // So for a taskbar at the screen top, we can't push the // client_rect->top down; instead, we move the bottom up by one pixel, // which is the smallest change we can make and still get a client area // less than the screen size. This is visibly ugly, but there seems to // be no better solution. --client_rect->bottom; } else { client_rect->top += kAutoHideTaskbarThicknessPx; } } if (GetTopmostAutoHideTaskbarForEdge(ABE_RIGHT, monitor)) client_rect->right -= kAutoHideTaskbarThicknessPx; if (GetTopmostAutoHideTaskbarForEdge(ABE_BOTTOM, monitor)) client_rect->bottom -= kAutoHideTaskbarThicknessPx; // We cannot return WVR_REDRAW when there is nonclient area, or Windows // exhibits bugs where client pixels and child HWNDs are mispositioned by // the width/height of the upper-left nonclient area. return 0; } // If the window bounds change, we're going to relayout and repaint anyway. // Returning WVR_REDRAW avoids an extra paint before that of the old client // pixels in the (now wrong) location, and thus makes actions like resizing a // window from the left edge look slightly less broken. // We special case when left or top insets are 0, since these conditions // actually require another repaint to correct the layout after glass gets // turned on and off. if (insets.left() == 0 || insets.top() == 0) return 0; return mode ? WVR_REDRAW : 0; } LRESULT HWNDMessageHandler::OnNCHitTest(const CPoint& point) { if (!delegate_->IsWidgetWindow()) { SetMsgHandled(FALSE); return 0; } // If the DWM is rendering the window controls, we need to give the DWM's // default window procedure first chance to handle hit testing. if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) { LRESULT result; if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0, MAKELPARAM(point.x, point.y), &result)) { return result; } } // First, give the NonClientView a chance to test the point to see if it // provides any of the non-client area. POINT temp = point; MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1); int component = delegate_->GetNonClientComponent(gfx::Point(temp)); if (component != HTNOWHERE) return component; // Otherwise, we let Windows do all the native frame non-client handling for // us. SetMsgHandled(FALSE); return 0; } void HWNDMessageHandler::OnNCPaint(HRGN rgn) { // We only do non-client painting if we're not using the native frame. // It's required to avoid some native painting artifacts from appearing when // the window is resized. if (!delegate_->IsWidgetWindow() || !delegate_->IsUsingCustomFrame()) { SetMsgHandled(FALSE); return; } // We have an NC region and need to paint it. We expand the NC region to // include the dirty region of the root view. This is done to minimize // paints. CRect window_rect; GetWindowRect(hwnd(), &window_rect); gfx::Size root_view_size = delegate_->GetRootViewSize(); if (gfx::Size(window_rect.Width(), window_rect.Height()) != root_view_size) { // If the size of the window differs from the size of the root view it // means we're being asked to paint before we've gotten a WM_SIZE. This can // happen when the user is interactively resizing the window. To avoid // mass flickering we don't do anything here. Once we get the WM_SIZE we'll // reset the region of the window which triggers another WM_NCPAINT and // all is well. return; } CRect dirty_region; // A value of 1 indicates paint all. if (!rgn || rgn == reinterpret_cast<HRGN>(1)) { dirty_region = CRect(0, 0, window_rect.Width(), window_rect.Height()); } else { RECT rgn_bounding_box; GetRgnBox(rgn, &rgn_bounding_box); if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect)) return; // Dirty region doesn't intersect window bounds, bale. // rgn_bounding_box is in screen coordinates. Map it to window coordinates. OffsetRect(&dirty_region, -window_rect.left, -window_rect.top); } // In theory GetDCEx should do what we want, but I couldn't get it to work. // In particular the docs mentiond DCX_CLIPCHILDREN, but as far as I can tell // it doesn't work at all. So, instead we get the DC for the window then // manually clip out the children. HDC dc = GetWindowDC(hwnd()); ClipState clip_state; clip_state.x = window_rect.left; clip_state.y = window_rect.top; clip_state.parent = hwnd(); clip_state.dc = dc; EnumChildWindows(hwnd(), &ClipDCToChild, reinterpret_cast<LPARAM>(&clip_state)); gfx::Rect old_paint_region = invalid_rect_; if (!old_paint_region.IsEmpty()) { // The root view has a region that needs to be painted. Include it in the // region we're going to paint. CRect old_paint_region_crect = old_paint_region.ToRECT(); CRect tmp = dirty_region; UnionRect(&dirty_region, &tmp, &old_paint_region_crect); } SchedulePaintInRect(gfx::Rect(dirty_region)); // gfx::CanvasSkiaPaint's destructor does the actual painting. As such, wrap // the following in a block to force paint to occur so that we can release // the dc. if (!delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region))) { gfx::CanvasSkiaPaint canvas(dc, true, dirty_region.left, dirty_region.top, dirty_region.Width(), dirty_region.Height()); delegate_->HandlePaint(&canvas); } ReleaseDC(hwnd(), dc); // When using a custom frame, we want to avoid calling DefWindowProc() since // that may render artifacts. SetMsgHandled(delegate_->IsUsingCustomFrame()); } LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message, WPARAM w_param, LPARAM l_param) { // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for // an explanation about why we need to handle this message. SetMsgHandled(delegate_->IsUsingCustomFrame()); return 0; } LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message, WPARAM w_param, LPARAM l_param) { // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for // an explanation about why we need to handle this message. SetMsgHandled(delegate_->IsUsingCustomFrame()); return 0; } LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) { LRESULT l_result = 0; SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result)); return l_result; } void HWNDMessageHandler::OnPaint(HDC dc) { RECT dirty_rect; // Try to paint accelerated first. if (GetUpdateRect(hwnd(), &dirty_rect, FALSE) && !IsRectEmpty(&dirty_rect)) { if (delegate_->HandlePaintAccelerated(gfx::Rect(dirty_rect))) { ValidateRect(hwnd(), NULL); } else { #if defined(USE_AURA) delegate_->HandlePaint(NULL); #else scoped_ptr<gfx::CanvasPaint> canvas( gfx::CanvasPaint::CreateCanvasPaint(hwnd())); delegate_->HandlePaint(canvas->AsCanvas()); #endif } } else { // TODO(msw): Find a better solution for this crbug.com/93530 workaround. // Some scenarios otherwise fail to validate minimized app/popup windows. ValidateRect(hwnd(), NULL); } } LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message, WPARAM w_param, LPARAM l_param) { SetMsgHandled(FALSE); return 0; } LRESULT HWNDMessageHandler::OnSetCursor(UINT message, WPARAM w_param, LPARAM l_param) { // Reimplement the necessary default behavior here. Calling DefWindowProc can // trigger weird non-client painting for non-glass windows with custom frames. // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow // content behind this window to incorrectly paint in front of this window. // Invalidating the window to paint over either set of artifacts is not ideal. wchar_t* cursor = IDC_ARROW; switch (LOWORD(l_param)) { case HTSIZE: cursor = IDC_SIZENWSE; break; case HTLEFT: case HTRIGHT: cursor = IDC_SIZEWE; break; case HTTOP: case HTBOTTOM: cursor = IDC_SIZENS; break; case HTTOPLEFT: case HTBOTTOMRIGHT: cursor = IDC_SIZENWSE; break; case HTTOPRIGHT: case HTBOTTOMLEFT: cursor = IDC_SIZENESW; break; case HTCLIENT: // Client-area mouse events set the proper cursor from View::GetCursor. return 0; default: // Use the default value, IDC_ARROW. break; } SetCursor(LoadCursor(NULL, cursor)); return 0; } void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) { delegate_->HandleNativeFocus(last_focused_window); SetMsgHandled(FALSE); } LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) { // Use a ScopedRedrawLock to avoid weird non-client painting. return DefWindowProcWithRedrawLock(WM_SETICON, size_type, reinterpret_cast<LPARAM>(new_icon)); } LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) { // Use a ScopedRedrawLock to avoid weird non-client painting. return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL, reinterpret_cast<LPARAM>(text)); } void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) { if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) && !delegate_->WillProcessWorkAreaChange()) { // Fire a dummy SetWindowPos() call, so we'll trip the code in // OnWindowPosChanging() below that notices work area changes. ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER); SetMsgHandled(TRUE); } else { if (flags == SPI_SETWORKAREA) delegate_->HandleWorkAreaChanged(); SetMsgHandled(FALSE); } } void HWNDMessageHandler::OnSize(UINT param, const CSize& size) { RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN); // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've // invoked OnSize we ensure the RootView has been laid out. ResetWindowRegion(false); } void HWNDMessageHandler::OnSysCommand(UINT notification_code, const CPoint& point) { if (!delegate_->ShouldHandleSystemCommands()) return; // Windows uses the 4 lower order bits of |notification_code| for type- // specific information so we must exclude this when comparing. static const int sc_mask = 0xFFF0; // Ignore size/move/maximize in fullscreen mode. if (fullscreen_handler_->fullscreen() && (((notification_code & sc_mask) == SC_SIZE) || ((notification_code & sc_mask) == SC_MOVE) || ((notification_code & sc_mask) == SC_MAXIMIZE))) return; if (delegate_->IsUsingCustomFrame()) { if ((notification_code & sc_mask) == SC_MINIMIZE || (notification_code & sc_mask) == SC_MAXIMIZE || (notification_code & sc_mask) == SC_RESTORE) { delegate_->ResetWindowControls(); } else if ((notification_code & sc_mask) == SC_MOVE || (notification_code & sc_mask) == SC_SIZE) { if (!IsVisible()) { // Circumvent ScopedRedrawLocks and force visibility before entering a // resize or move modal loop to get continuous sizing/moving feedback. SetWindowLong(hwnd(), GWL_STYLE, GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE); } } } // Handle SC_KEYMENU, which means that the user has pressed the ALT // key and released it, so we should focus the menu bar. if ((notification_code & sc_mask) == SC_KEYMENU && point.x == 0) { int modifiers = ui::EF_NONE; if (base::win::IsShiftPressed()) modifiers |= ui::EF_SHIFT_DOWN; if (base::win::IsCtrlPressed()) modifiers |= ui::EF_CONTROL_DOWN; // Retrieve the status of shift and control keys to prevent consuming // shift+alt keys, which are used by Windows to change input languages. ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU), modifiers); delegate_->HandleAccelerator(accelerator); return; } // If the delegate can't handle it, the system implementation will be called. if (!delegate_->HandleCommand(notification_code)) { DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code, MAKELPARAM(point.x, point.y)); } } void HWNDMessageHandler::OnThemeChanged() { ui::NativeThemeWin::instance()->CloseHandles(); } LRESULT HWNDMessageHandler::OnTouchEvent(UINT message, WPARAM w_param, LPARAM l_param) { int num_points = LOWORD(w_param); scoped_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]); if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param), num_points, input.get(), sizeof(TOUCHINPUT))) { for (int i = 0; i < num_points; ++i) { ui::EventType touch_event_type = ui::ET_UNKNOWN; if (input[i].dwFlags & TOUCHEVENTF_DOWN) { touch_ids_.insert(input[i].dwID); touch_event_type = ui::ET_TOUCH_PRESSED; } else if (input[i].dwFlags & TOUCHEVENTF_UP) { touch_ids_.erase(input[i].dwID); touch_event_type = ui::ET_TOUCH_RELEASED; } else if (input[i].dwFlags & TOUCHEVENTF_MOVE) { touch_event_type = ui::ET_TOUCH_MOVED; } // Handle touch events only on Aura for now. #if defined(USE_AURA) if (touch_event_type != ui::ET_UNKNOWN) { POINT point; point.x = TOUCH_COORD_TO_PIXEL(input[i].x); point.y = TOUCH_COORD_TO_PIXEL(input[i].y); ScreenToClient(hwnd(), &point); ui::TouchEvent event( touch_event_type, gfx::Point(point.x, point.y), input[i].dwID % ui::GestureSequence::kMaxGesturePoints, base::TimeDelta::FromMilliseconds(input[i].dwTime)); delegate_->HandleTouchEvent(event); } #endif } } CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param)); SetMsgHandled(FALSE); return 0; } void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) { if (ignore_window_pos_changes_) { // If somebody's trying to toggle our visibility, change the nonclient area, // change our Z-order, or activate us, we should probably let it go through. if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) | SWP_FRAMECHANGED)) && (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) { // Just sizing/moving the window; ignore. window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW; window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW); } } else if (!GetParent(hwnd())) { CRect window_rect; HMONITOR monitor; gfx::Rect monitor_rect, work_area; if (GetWindowRect(hwnd(), &window_rect) && GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) { bool work_area_changed = (monitor_rect == last_monitor_rect_) && (work_area != last_work_area_); if (monitor && (monitor == last_monitor_) && ((fullscreen_handler_->fullscreen() && !fullscreen_handler_->metro_snap()) || work_area_changed)) { // A rect for the monitor we're on changed. Normally Windows notifies // us about this (and thus we're reaching here due to the SetWindowPos() // call in OnSettingChange() above), but with some software (e.g. // nVidia's nView desktop manager) the work area can change asynchronous // to any notification, and we're just sent a SetWindowPos() call with a // new (frequently incorrect) position/size. In either case, the best // response is to throw away the existing position/size information in // |window_pos| and recalculate it based on the new work rect. gfx::Rect new_window_rect; if (fullscreen_handler_->fullscreen()) { new_window_rect = monitor_rect; } else if (IsMaximized()) { new_window_rect = work_area; int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME); new_window_rect.Inset(-border_thickness, -border_thickness); } else { new_window_rect = gfx::Rect(window_rect); new_window_rect.AdjustToFit(work_area); } window_pos->x = new_window_rect.x(); window_pos->y = new_window_rect.y(); window_pos->cx = new_window_rect.width(); window_pos->cy = new_window_rect.height(); // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child // HWNDs for some reason. window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW); window_pos->flags |= SWP_NOCOPYBITS; // Now ignore all immediately-following SetWindowPos() changes. Windows // likes to (incorrectly) recalculate what our position/size should be // and send us further updates. ignore_window_pos_changes_ = true; DCHECK(!ignore_pos_changes_factory_.HasWeakPtrs()); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges, ignore_pos_changes_factory_.GetWeakPtr())); } last_monitor_ = monitor; last_monitor_rect_ = monitor_rect; last_work_area_ = work_area; } } if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) { // Prevent the window from being made visible if we've been asked to do so. // See comment in header as to why we might want this. window_pos->flags &= ~SWP_SHOWWINDOW; } SetMsgHandled(FALSE); } void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) { if (DidClientAreaSizeChange(window_pos)) ClientAreaSizeChanged(); if (remove_standard_frame_ && window_pos->flags & SWP_FRAMECHANGED && ui::win::IsAeroGlassEnabled()) { MARGINS m = {10, 10, 10, 10}; DwmExtendFrameIntoClientArea(hwnd(), &m); } if (window_pos->flags & SWP_SHOWWINDOW) delegate_->HandleVisibilityChanged(true); else if (window_pos->flags & SWP_HIDEWINDOW) delegate_->HandleVisibilityChanged(false); SetMsgHandled(FALSE); } } // namespace views
37.510628
80
0.686626
[ "render", "object", "vector" ]
7ded1ce92b4c593a3e21892bbcec0e47f6cb25a4
4,942
cpp
C++
src/device.cpp
cxrdevelop/usb_enumerator
ef70468ae6ba42619016780ffe83817c9f6e0b03
[ "MIT" ]
null
null
null
src/device.cpp
cxrdevelop/usb_enumerator
ef70468ae6ba42619016780ffe83817c9f6e0b03
[ "MIT" ]
null
null
null
src/device.cpp
cxrdevelop/usb_enumerator
ef70468ae6ba42619016780ffe83817c9f6e0b03
[ "MIT" ]
null
null
null
/* * Copyright (C) 2012, Anthony Clay, ZarthCode LLC, all rights reserved. * Copyright (C) 2016, Stephan Linz, Li-Pro.Net, all rights reserved. * * This file is part of the LibUSB C++ wrapper library (libusbpp). * * libusbpp is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * libusbpp 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libusbpp. If not, see <http://www.gnu.org/licenses/>. */ #include <libusb-cpp/device.hpp> #include "deviceImpl.hpp" LibUSB::Device::Device( std::shared_ptr<DeviceImpl> pInit ) { m_pDeviceImpl_ = pInit; // Obtain the descriptor m_pDeviceImpl_->getDeviceDescriptor(); } LibUSB::Device::~Device() { } uint16_t LibUSB::Device::USBSpecification() { return m_pDeviceImpl_->getDeviceDescriptor()->bcdUSB; } uint8_t LibUSB::Device::DeviceClass() { return m_pDeviceImpl_->getDeviceDescriptor()->bDeviceClass; } uint8_t LibUSB::Device::DeviceSubclass() { return m_pDeviceImpl_->getDeviceDescriptor()->bDeviceSubClass; } uint8_t LibUSB::Device::DeviceProtocol() { return m_pDeviceImpl_->getDeviceDescriptor()->bDeviceProtocol; } uint16_t LibUSB::Device::vendorID() { return m_pDeviceImpl_->getDeviceDescriptor()->idVendor; } uint16_t LibUSB::Device::productID() { return m_pDeviceImpl_->getDeviceDescriptor()->idProduct; } uint8_t LibUSB::Device::NumConfigurations() { return m_pDeviceImpl_->getDeviceDescriptor()->bNumConfigurations; } std::wstring LibUSB::Device::ProductString() { // Device must be open if (!isOpen()) { throw std::runtime_error("LibUSB::Device::ProductString(): Device must be open!"); } // Validate the descriptor index if(m_pDeviceImpl_->getDeviceDescriptor()->iProduct == 0) { // throw std::runtime_error("Product string is not supported on this device."); return L"Not supported."; } // Return an product string. return m_pDeviceImpl_->getStringDescriptorW(m_pDeviceImpl_->getDeviceDescriptor()->iProduct); } std::wstring LibUSB::Device::ManufacturerString() { // Device must be open if (!isOpen()) { throw std::runtime_error("LibUSB::Device::ManufacturerString(): Device must be open!"); } // Validate the descriptor index if(m_pDeviceImpl_->getDeviceDescriptor()->iManufacturer == 0) { // throw std::runtime_error("Manufacturer string is not supported on this device."); return L"Not supported."; } // Return a manufacturer string. std::wstring resultStr = m_pDeviceImpl_->getStringDescriptorW(m_pDeviceImpl_->getDeviceDescriptor()->iManufacturer); return resultStr; } std::wstring LibUSB::Device::SerialString() { // Device must be open if (!isOpen()) { throw std::runtime_error("LibUSB::Device::SerialString(): Device must be open!"); } // Validate the descriptor index if(m_pDeviceImpl_->getDeviceDescriptor()->iSerialNumber == 0) { // throw std::runtime_error("Serial number is not supported on this device."); return L"Not supported."; } // Return a serial string. return m_pDeviceImpl_->getStringDescriptorW(m_pDeviceImpl_->getDeviceDescriptor()->iSerialNumber); } void LibUSB::Device::Open() { m_pDeviceImpl_->Open(); } bool LibUSB::Device::isOpen() { return m_pDeviceImpl_->isOpen(); } std::shared_ptr<LibUSB::Configuration> LibUSB::Device::getConfiguration( uint8_t ConfigValue ) { // Check the active configuration object if ((m_pActiveConfiguration.get() != nullptr) && (m_pActiveConfiguration->Value() == ConfigValue)) { return m_pActiveConfiguration; } // Create a configuration object return m_pDeviceImpl_->getConfiguration(ConfigValue); } std::shared_ptr<LibUSB::Configuration> LibUSB::Device::getActiveConfiguration() { // Get the index of the active configuration uint8_t index = 0; if (m_pDeviceImpl_->getActiveConfiguration(index)) { // Check the active configuration object if ((m_pActiveConfiguration.get() == nullptr) || (m_pActiveConfiguration->Value() != index)) { // Create a new object m_pActiveConfiguration = m_pDeviceImpl_->getConfiguration(index); } } else { // The device is unconfigured - return a nullptr. m_pActiveConfiguration.reset(); } return m_pActiveConfiguration; } void LibUSB::Device::TransferEventNotification( std::shared_ptr<Transfer> pCompletedTransfer ) { // By default: Do nothing. } void LibUSB::Device::Init() { m_pDeviceImpl_->setParentDevice(shared_from_this()); } std::shared_ptr<LibUSB::Endpoint> LibUSB::Device::getControlEndpoint() { return m_pDeviceImpl_->getControlEndpoint(); }
21.867257
117
0.736342
[ "object" ]
7df6a625b0805fe61eb9dc949bc45f680d964f49
8,688
cpp
C++
node/v8_inspector/platform/v8_inspector/protocol/Console.cpp
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
node/v8_inspector/platform/v8_inspector/protocol/Console.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
node/v8_inspector/platform/v8_inspector/protocol/Console.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// This file is generated // Copyright (c) 2016 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 "platform\v8_inspector\protocol/Console.h" #include "platform/inspector_protocol/DispatcherBase.h" #include "platform/inspector_protocol/Parser.h" namespace blink { namespace protocol { namespace Console { // ------------- Enum values from types. const char Metainfo::domainName[] = "Console"; const char Metainfo::commandPrefix[] = "Console."; const char* ConsoleMessage::SourceEnum::Xml = "xml"; const char* ConsoleMessage::SourceEnum::Javascript = "javascript"; const char* ConsoleMessage::SourceEnum::Network = "network"; const char* ConsoleMessage::SourceEnum::ConsoleApi = "console-api"; const char* ConsoleMessage::SourceEnum::Storage = "storage"; const char* ConsoleMessage::SourceEnum::Appcache = "appcache"; const char* ConsoleMessage::SourceEnum::Rendering = "rendering"; const char* ConsoleMessage::SourceEnum::Security = "security"; const char* ConsoleMessage::SourceEnum::Other = "other"; const char* ConsoleMessage::SourceEnum::Deprecation = "deprecation"; const char* ConsoleMessage::SourceEnum::Worker = "worker"; const char* ConsoleMessage::LevelEnum::Log = "log"; const char* ConsoleMessage::LevelEnum::Warning = "warning"; const char* ConsoleMessage::LevelEnum::Error = "error"; const char* ConsoleMessage::LevelEnum::Debug = "debug"; const char* ConsoleMessage::LevelEnum::Info = "info"; std::unique_ptr<ConsoleMessage> ConsoleMessage::parse(protocol::Value* value, ErrorSupport* errors) { if (!value || value->type() != protocol::Value::TypeObject) { errors->addError("object expected"); return nullptr; } std::unique_ptr<ConsoleMessage> result(new ConsoleMessage()); protocol::DictionaryValue* object = DictionaryValue::cast(value); errors->push(); protocol::Value* sourceValue = object->get("source"); errors->setName("source"); result->m_source = ValueConversions<String16>::parse(sourceValue, errors); protocol::Value* levelValue = object->get("level"); errors->setName("level"); result->m_level = ValueConversions<String16>::parse(levelValue, errors); protocol::Value* textValue = object->get("text"); errors->setName("text"); result->m_text = ValueConversions<String16>::parse(textValue, errors); protocol::Value* urlValue = object->get("url"); if (urlValue) { errors->setName("url"); result->m_url = ValueConversions<String16>::parse(urlValue, errors); } protocol::Value* lineValue = object->get("line"); if (lineValue) { errors->setName("line"); result->m_line = ValueConversions<int>::parse(lineValue, errors); } protocol::Value* columnValue = object->get("column"); if (columnValue) { errors->setName("column"); result->m_column = ValueConversions<int>::parse(columnValue, errors); } errors->pop(); if (errors->hasErrors()) return nullptr; return result; } std::unique_ptr<protocol::DictionaryValue> ConsoleMessage::serialize() const { std::unique_ptr<protocol::DictionaryValue> result = DictionaryValue::create(); result->setValue("source", ValueConversions<String16>::serialize(m_source)); result->setValue("level", ValueConversions<String16>::serialize(m_level)); result->setValue("text", ValueConversions<String16>::serialize(m_text)); if (m_url.isJust()) result->setValue("url", ValueConversions<String16>::serialize(m_url.fromJust())); if (m_line.isJust()) result->setValue("line", ValueConversions<int>::serialize(m_line.fromJust())); if (m_column.isJust()) result->setValue("column", ValueConversions<int>::serialize(m_column.fromJust())); return result; } std::unique_ptr<ConsoleMessage> ConsoleMessage::clone() const { ErrorSupport errors; return parse(serialize().get(), &errors); } // ------------- Enum values from params. // ------------- Frontend notifications. void Frontend::messageAdded(std::unique_ptr<protocol::Console::ConsoleMessage> message) { std::unique_ptr<protocol::DictionaryValue> jsonMessage = DictionaryValue::create(); jsonMessage->setString("method", "Console.messageAdded"); std::unique_ptr<protocol::DictionaryValue> paramsObject = DictionaryValue::create(); paramsObject->setValue("message", ValueConversions<protocol::Console::ConsoleMessage>::serialize(message.get())); jsonMessage->setObject("params", std::move(paramsObject)); if (m_frontendChannel) m_frontendChannel->sendProtocolNotification(jsonMessage->toJSONString()); } void Frontend::messageRepeatCountUpdated(int count, double timestamp) { std::unique_ptr<protocol::DictionaryValue> jsonMessage = DictionaryValue::create(); jsonMessage->setString("method", "Console.messageRepeatCountUpdated"); std::unique_ptr<protocol::DictionaryValue> paramsObject = DictionaryValue::create(); paramsObject->setValue("count", ValueConversions<int>::serialize(count)); paramsObject->setValue("timestamp", ValueConversions<double>::serialize(timestamp)); jsonMessage->setObject("params", std::move(paramsObject)); if (m_frontendChannel) m_frontendChannel->sendProtocolNotification(jsonMessage->toJSONString()); } void Frontend::messagesCleared() { std::unique_ptr<protocol::DictionaryValue> jsonMessage = DictionaryValue::create(); jsonMessage->setString("method", "Console.messagesCleared"); std::unique_ptr<protocol::DictionaryValue> paramsObject = DictionaryValue::create(); jsonMessage->setObject("params", std::move(paramsObject)); if (m_frontendChannel) m_frontendChannel->sendProtocolNotification(jsonMessage->toJSONString()); } // --------------------- Dispatcher. class DispatcherImpl : public protocol::DispatcherBase { public: DispatcherImpl(FrontendChannel* frontendChannel, Backend* backend) : DispatcherBase(frontendChannel) , m_backend(backend) { m_dispatchMap["Console.enable"] = &DispatcherImpl::enable; m_dispatchMap["Console.disable"] = &DispatcherImpl::disable; m_dispatchMap["Console.clearMessages"] = &DispatcherImpl::clearMessages; } ~DispatcherImpl() override { } void dispatch(int callId, const String16& method, std::unique_ptr<protocol::DictionaryValue> messageObject) override; protected: using CallHandler = void (DispatcherImpl::*)(int callId, std::unique_ptr<DictionaryValue> messageObject, ErrorSupport* errors); using DispatchMap = protocol::HashMap<String16, CallHandler>; DispatchMap m_dispatchMap; void enable(int callId, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*); void disable(int callId, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*); void clearMessages(int callId, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport*); Backend* m_backend; }; void DispatcherImpl::dispatch(int callId, const String16& method, std::unique_ptr<protocol::DictionaryValue> messageObject) { protocol::HashMap<String16, CallHandler>::iterator it = m_dispatchMap.find(method); if (it == m_dispatchMap.end()) { reportProtocolError(callId, MethodNotFound, "'" + method + "' wasn't found", nullptr); return; } protocol::ErrorSupport errors; (this->*(it->second))(callId, std::move(messageObject), &errors); } void DispatcherImpl::enable(int callId, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors) { std::unique_ptr<DispatcherBase::WeakPtr> weak = weakPtr(); ErrorString error; m_backend->enable(&error); if (weak->get()) weak->get()->sendResponse(callId, error); } void DispatcherImpl::disable(int callId, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors) { std::unique_ptr<DispatcherBase::WeakPtr> weak = weakPtr(); ErrorString error; m_backend->disable(&error); if (weak->get()) weak->get()->sendResponse(callId, error); } void DispatcherImpl::clearMessages(int callId, std::unique_ptr<DictionaryValue> requestMessageObject, ErrorSupport* errors) { std::unique_ptr<DispatcherBase::WeakPtr> weak = weakPtr(); ErrorString error; m_backend->clearMessages(&error); if (weak->get()) weak->get()->sendResponse(callId, error); } // static void Dispatcher::wire(UberDispatcher* dispatcher, Backend* backend) { dispatcher->registerBackend("Console", wrapUnique(new DispatcherImpl(dispatcher->channel(), backend))); } } // Console } // namespace protocol } // namespace blink
40.222222
131
0.719153
[ "object" ]
7dfbbd30db72e23ccc06782127874b9d073761f2
6,831
cpp
C++
unique_paths_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
unique_paths_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
unique_paths_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
// Problem: https://leetcode.com/problems/unique-paths-ii/ #include <vector> #include "utils.h" namespace unique_paths_2 { // Note: All solutions return int as required by the initial problem, but // 32-bit signed integer can hold the result for at most the 17x18 grid. // The straightforward solution, recursively counting paths from the start // cell to the target class Solution1 { public: // Time: O(C(n + m, m)), Space: O(n + m), Recursion depth <= n + m // n - number of rows, m - number of columns, // C(n + m, m) - binomial coefficient (n + m)! / (m! * n!) // // Note: The grid must be a rectangle. // // Note: Time complexity is estimated by the number of paths for a grid // without obstacles, which is the binomial coefficient as shown in // unique_paths. Space complexity depends on the recursion depth, which // is determined by the path length n + m - 1. // int run(std::vector<std::vector<int>>& grid) { return getPathsCount(grid, 0, 0); } private: int getPathsCount(std::vector<std::vector<int>>& grid, int r, int c) { if (!grid.size() || r >= grid.size() || c >= grid[0].size() || grid[r][c] == 1) return 0; if (r == grid.size() - 1 && c == grid[0].size() - 1) return 1; // Go right + go down return getPathsCount(grid, r, c + 1) + getPathsCount(grid, r + 1, c); } }; // Non-recursive solution, counting paths from the target cell to the start class Solution2 { public: // Time: O(n * m), Space: O(1), n - number of rows, m - number of columns // // Note: The grid must be a rectangle. // int run(std::vector<std::vector<int>>& grid) { // Idea: // Count paths in reverse order, moving the start from the target cell to (0, 0): // 1. Put the start to the target cell (t = rows_count - 1, l = cols_count - 1). // Then there is only 1 path, i.e. the cell itself, or no path if it contains // an obstacle. // 2. Go to the outer rectangle, which top-left corner is (t - 1, l - 1) if this // is a square. // 3. Calculate counts for the top and left borders of the outer rectangle. For // each cell (r, c), the count is a sum of counts for (r + 1, c) and (r, c + 1), // because we can step only right or down. If the cell contains an obstacle, // the count is 0. // 4. Repeat 2 and 3 until we reach (0, 0). // // 0 * 0 0 * 0 2 0 1 // 0 0 0 -> 0 2 1 -> 2 2 1 // * 0 1 * 1 1 0 1 1 if (!grid.size() || !grid[0].size()) return 0; const int rows_count = grid.size(); const int cols_count = grid[0].size(); // Start from the target cell int t = rows_count - 1; int l = cols_count - 1; int b = t; int r = l; if (grid[t][l] == 1) return 0; if (rows_count == 1 && cols_count == 1) return 1; grid[t][l] = 1; do { // Go up and left. If not possible, decrease the right/bottom border // because everything at the right/bottom is already counted. if (t > 0) { t -= 1; } else { r = l - 1; } if (l > 0) { l -= 1; } else { b = t - 1; } // Count top border of the outer rectangle for (int ci = r, ri = t; ci > l; ci--) { calculateCount(grid, ri, ci); } // Count left border of the outer rectangle for (int ri = b, ci = l; ri > t; ri--) { calculateCount(grid, ri, ci); } // Count top-left corner of the outer rectangle calculateCount(grid, t, l); } while (t != 0 || l != 0); return grid[0][0]; } private: inline void calculateCount(std::vector<std::vector<int>>& grid, int r, int c) const { int& cell = grid[r][c]; // Empty cell if (cell == 0) { if (r < grid.size() - 1) cell += grid[r + 1][c]; if (c < grid[r].size() - 1) cell += grid[r][c + 1]; // Obstacle } else { cell = 0; } } }; template <typename Solution> void test() { std::vector<std::vector<int>> grid; ASSERT(( Solution().run(grid = {}) == 0 )); ASSERT(( Solution().run(grid = {{}}) == 0 )); ASSERT(( Solution().run(grid = {{0}}) == 1 )); ASSERT(( Solution().run(grid = {{1}}) == 0 )); ASSERT(( Solution().run(grid = {{0, 0}}) == 1 )); ASSERT(( Solution().run(grid = {{0, 0}, {0, 0}}) == 2 )); ASSERT(( Solution().run(grid = {{1, 0}, {0, 0}}) == 0 )); ASSERT(( Solution().run(grid = {{0, 0}, {0, 1}}) == 0 )); ASSERT(( Solution().run(grid = {{0, 1}, {1, 0}}) == 0 )); ASSERT(( Solution().run(grid = {{0, 1}, {0, 0}}) == 1 )); ASSERT(( Solution().run(grid = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}) == 6 )); ASSERT(( Solution().run(grid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}) == 2 )); ASSERT(( Solution().run(grid = {{0, 1, 0}, {0, 0, 0}, {0, 1, 0}}) == 1 )); ASSERT(( Solution().run(grid = {{0, 1, 0}, {0, 0, 1}, {0, 1, 0}}) == 0 )); ASSERT(( Solution().run(grid = {{0, 0, 1}, {0, 1, 0}, {1, 0, 0}}) == 0 )); ASSERT(( Solution().run(grid = {{0, 1, 1}, {0, 0, 0}, {1, 1, 0}}) == 1 )); ASSERT(( Solution().run(grid = {{0, 0, 1, 0}, {1, 0, 1, 0}, {0, 0, 1, 0}, {0, 1, 1, 0}, {0, 0, 0, 0}}) == 0 )); ASSERT(( Solution().run(grid = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 0, 0, 0, 0}}) == 6 )); ASSERT(( Solution().run(grid = {{0, 0, 1, 0, 0}, {1, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}}) == 20 )); ASSERT(( Solution().run(grid = {{0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}}) == 70 )); } int main() { test<Solution1>(); test<Solution2>(); return 0; } }
28.701681
91
0.428049
[ "vector" ]
7dfc031702aa8e05c8b27679a8f39af43bbd541b
2,463
hpp
C++
include/range/v3/view/unique.hpp
Bhaskers-Blu-Org2/Range-V3-VS2015
423bcae5cf18948591361329784d3b12ef41711b
[ "MIT" ]
125
2016-08-23T03:43:08.000Z
2019-04-27T22:50:04.000Z
include/range/v3/view/unique.hpp
Bhaskers-Blu-Org2/Range-V3-VS2015
423bcae5cf18948591361329784d3b12ef41711b
[ "MIT" ]
28
2016-08-23T04:37:19.000Z
2018-04-11T16:06:52.000Z
include/range/v3/view/unique.hpp
Microsoft/Range-V3-VS2015
423bcae5cf18948591361329784d3b12ef41711b
[ "MIT" ]
19
2016-08-23T03:57:32.000Z
2018-10-18T12:31:50.000Z
/// \file // Range v3 library // // Copyright Eric Niebler 2013-2014 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_VIEW_UNIQUE_HPP #define RANGES_V3_VIEW_UNIQUE_HPP #include <utility> #include <meta/meta.hpp> #include <range/v3/range_fwd.hpp> #include <range/v3/utility/functional.hpp> #include <range/v3/utility/static_const.hpp> #include <range/v3/view/adjacent_remove_if.hpp> #include <range/v3/view/view.hpp> #include <range/v3/view/all.hpp> namespace ranges { inline namespace v3 { /// \addtogroup group-views /// @{ namespace view { struct unique_fn { template<typename Rng> using Concept = meta::and_< ForwardRange<Rng>, EqualityComparable<range_value_t<Rng>>>; #ifdef RANGES_WORKAROUND_MSVC_SFINAE_CONSTEXPR template<typename Rng, CONCEPT_REQUIRES_(Concept<Rng>::value)> #else template<typename Rng, CONCEPT_REQUIRES_(Concept<Rng>())> #endif unique_view<all_t<Rng>> operator()(Rng && rng) const { return {all(std::forward<Rng>(rng)), equal_to{}}; } #ifndef RANGES_DOXYGEN_INVOKED template<typename Rng, #ifdef RANGES_WORKAROUND_MSVC_SFINAE_CONSTEXPR CONCEPT_REQUIRES_(!Concept<Rng>::value)> #else CONCEPT_REQUIRES_(!Concept<Rng>())> #endif void operator()(Rng &&) const { CONCEPT_ASSERT_MSG(ForwardRange<Rng>(), "The object on which view::unique operates must be a model the " "ForwardRange concept."); CONCEPT_ASSERT_MSG(EqualityComparable<range_value_t<Rng>>(), "The value type of the range passed to view::unique must be " "EqualityComparable."); } #endif }; /// \relates unique_fn /// \ingroup group-views namespace { constexpr auto&& unique = static_const<view<unique_fn>>::value; } } /// @} } } #endif
30.407407
88
0.566788
[ "object", "model" ]
b401bcd24a338203ca6684fcd71b1d044c6105c3
21,103
cc
C++
third_party/mojo/src/mojo/edk/system/master_connection_manager.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5
2015-04-30T00:13:21.000Z
2019-07-10T02:17:24.000Z
third_party/mojo/src/mojo/edk/system/master_connection_manager.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/mojo/src/mojo/edk/system/master_connection_manager.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/edk/system/master_connection_manager.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/location.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/synchronization/waitable_event.h" #include "mojo/edk/embedder/master_process_delegate.h" #include "mojo/edk/embedder/platform_channel_pair.h" #include "mojo/edk/embedder/platform_handle_vector.h" #include "mojo/edk/system/message_in_transit.h" #include "mojo/edk/system/raw_channel.h" #include "mojo/edk/system/transport_data.h" namespace mojo { namespace system { const ProcessIdentifier kFirstSlaveProcessIdentifier = 2; static_assert(kMasterProcessIdentifier != kInvalidProcessIdentifier, "Bad master process identifier"); static_assert(kFirstSlaveProcessIdentifier != kInvalidProcessIdentifier, "Bad first slave process identifier"); static_assert(kMasterProcessIdentifier != kFirstSlaveProcessIdentifier, "Master and first slave process identifiers are the same"); // MasterConnectionManager::Helper --------------------------------------------- // |MasterConnectionManager::Helper| is not thread-safe, and must only be used // on its |owner_|'s private thread. class MasterConnectionManager::Helper : public RawChannel::Delegate { public: Helper(MasterConnectionManager* owner, ProcessIdentifier process_identifier, scoped_ptr<embedder::SlaveInfo> slave_info, embedder::ScopedPlatformHandle platform_handle); ~Helper() override; void Init(); scoped_ptr<embedder::SlaveInfo> Shutdown(); private: // |RawChannel::Delegate| methods: void OnReadMessage( const MessageInTransit::View& message_view, embedder::ScopedPlatformHandleVectorPtr platform_handles) override; void OnError(Error error) override; // Handles an error that's fatal to this object. Note that this probably // results in |Shutdown()| being called (in the nested context) and then this // object being destroyed. void FatalError(); MasterConnectionManager* const owner_; const ProcessIdentifier process_identifier_; scoped_ptr<embedder::SlaveInfo> slave_info_; scoped_ptr<RawChannel> raw_channel_; DISALLOW_COPY_AND_ASSIGN(Helper); }; MasterConnectionManager::Helper::Helper( MasterConnectionManager* owner, ProcessIdentifier process_identifier, scoped_ptr<embedder::SlaveInfo> slave_info, embedder::ScopedPlatformHandle platform_handle) : owner_(owner), process_identifier_(process_identifier), slave_info_(slave_info.Pass()), raw_channel_(RawChannel::Create(platform_handle.Pass())) { } MasterConnectionManager::Helper::~Helper() { DCHECK(!slave_info_); } void MasterConnectionManager::Helper::Init() { raw_channel_->Init(this); } scoped_ptr<embedder::SlaveInfo> MasterConnectionManager::Helper::Shutdown() { raw_channel_->Shutdown(); raw_channel_.reset(); return slave_info_.Pass(); } void MasterConnectionManager::Helper::OnReadMessage( const MessageInTransit::View& message_view, embedder::ScopedPlatformHandleVectorPtr platform_handles) { if (message_view.type() != MessageInTransit::kTypeConnectionManager) { LOG(ERROR) << "Invalid message type " << message_view.type(); FatalError(); // WARNING: This destroys us. return; } // Currently, all the messages simply have a |ConnectionIdentifier| as data. if (message_view.num_bytes() != sizeof(ConnectionIdentifier)) { LOG(ERROR) << "Invalid message size " << message_view.num_bytes(); FatalError(); // WARNING: This destroys us. return; } // And none of them should have any platform handles attached. if (message_view.transport_data_buffer()) { LOG(ERROR) << "Invalid message with transport data"; FatalError(); // WARNING: This destroys us. return; } const ConnectionIdentifier* connection_id = reinterpret_cast<const ConnectionIdentifier*>(message_view.bytes()); bool result; ProcessIdentifier peer_process_identifier = kInvalidProcessIdentifier; embedder::ScopedPlatformHandle platform_handle; uint32_t num_bytes = 0; const void* bytes = nullptr; switch (message_view.subtype()) { case MessageInTransit::kSubtypeConnectionManagerAllowConnect: result = owner_->AllowConnectImpl(process_identifier_, *connection_id); break; case MessageInTransit::kSubtypeConnectionManagerCancelConnect: result = owner_->CancelConnectImpl(process_identifier_, *connection_id); break; case MessageInTransit::kSubtypeConnectionManagerConnect: result = owner_->ConnectImpl(process_identifier_, *connection_id, &peer_process_identifier, &platform_handle); // Success acks for "connect" have the peer process identifier as data // (and maybe also a platform handle). if (result) { num_bytes = static_cast<uint32_t>(sizeof(peer_process_identifier)); bytes = &peer_process_identifier; } break; default: LOG(ERROR) << "Invalid message subtype " << message_view.subtype(); FatalError(); // WARNING: This destroys us. return; } scoped_ptr<MessageInTransit> response(new MessageInTransit( MessageInTransit::kTypeConnectionManagerAck, result ? MessageInTransit::kSubtypeConnectionManagerAckSuccess : MessageInTransit::kSubtypeConnectionManagerAckFailure, num_bytes, bytes)); if (platform_handle.is_valid()) { // Only success acks for "connect" *may* have a platform handle attached. DCHECK(result); DCHECK_EQ(message_view.subtype(), MessageInTransit::kSubtypeConnectionManagerConnect); embedder::ScopedPlatformHandleVectorPtr platform_handles( new embedder::PlatformHandleVector()); platform_handles->push_back(platform_handle.release()); response->SetTransportData( make_scoped_ptr(new TransportData(platform_handles.Pass()))); } if (!raw_channel_->WriteMessage(response.Pass())) { LOG(ERROR) << "WriteMessage failed"; FatalError(); // WARNING: This destroys us. return; } } void MasterConnectionManager::Helper::OnError(Error /*error*/) { // Every error (read or write) is fatal (for that particular connection). Read // errors are fatal since no more commands will be received from that // connection. Write errors are fatal since it is no longer possible to send // responses. FatalError(); // WARNING: This destroys us. } void MasterConnectionManager::Helper::FatalError() { owner_->OnError(process_identifier_); // WARNING: This destroys us. } // MasterConnectionManager::PendingConnectionInfo ------------------------------ struct MasterConnectionManager::PendingConnectionInfo { // States: // - This is created upon a first "allow connect" (with |first| set // immediately). We then wait for a second "allow connect". // - After the second "allow connect" (and |second| is set), we wait for // "connects" from both |first| and |second|. // - We may then receive "connect" from either |first| or |second|, at which // which point it remains to wait for "connect" from the other. // I.e., the valid state transitions are: // AWAITING_SECOND_ALLOW_CONNECT -> AWAITING_CONNECTS_FROM_BOTH // -> {AWAITING_CONNECT_FROM_FIRST,AWAITING_CONNECT_FROM_SECOND} enum State { AWAITING_SECOND_ALLOW_CONNECT, AWAITING_CONNECTS_FROM_BOTH, AWAITING_CONNECT_FROM_FIRST, AWAITING_CONNECT_FROM_SECOND }; explicit PendingConnectionInfo(ProcessIdentifier first) : state(AWAITING_SECOND_ALLOW_CONNECT), first(first), second(kInvalidProcessIdentifier) { DCHECK_NE(first, kInvalidProcessIdentifier); } ~PendingConnectionInfo() {} State state; ProcessIdentifier first; ProcessIdentifier second; // Valid in AWAITING_CONNECT_FROM_{FIRST, SECOND} states. embedder::ScopedPlatformHandle remaining_handle; }; // MasterConnectionManager ----------------------------------------------------- MasterConnectionManager::MasterConnectionManager() : master_process_delegate_(), private_thread_("MasterConnectionManagerPrivateThread"), next_process_identifier_(kFirstSlaveProcessIdentifier) { } MasterConnectionManager::~MasterConnectionManager() { DCHECK(!delegate_thread_task_runner_); DCHECK(!master_process_delegate_); DCHECK(!private_thread_.message_loop()); DCHECK(helpers_.empty()); DCHECK(pending_connections_.empty()); } void MasterConnectionManager::Init( scoped_refptr<base::TaskRunner> delegate_thread_task_runner, embedder::MasterProcessDelegate* master_process_delegate) { DCHECK(delegate_thread_task_runner); DCHECK(master_process_delegate); DCHECK(!delegate_thread_task_runner_); DCHECK(!master_process_delegate_); DCHECK(!private_thread_.message_loop()); delegate_thread_task_runner_ = delegate_thread_task_runner; AssertOnDelegateThread(); master_process_delegate_ = master_process_delegate; CHECK(private_thread_.StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0))); } void MasterConnectionManager::Shutdown() { AssertOnDelegateThread(); DCHECK(master_process_delegate_); DCHECK(private_thread_.message_loop()); // The |Stop()| will actually finish all posted tasks. private_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&MasterConnectionManager::ShutdownOnPrivateThread, base::Unretained(this))); private_thread_.Stop(); DCHECK(helpers_.empty()); DCHECK(pending_connections_.empty()); master_process_delegate_ = nullptr; delegate_thread_task_runner_ = nullptr; } void MasterConnectionManager::AddSlave( scoped_ptr<embedder::SlaveInfo> slave_info, embedder::ScopedPlatformHandle platform_handle) { // We don't really care if |slave_info| is non-null or not. DCHECK(platform_handle.is_valid()); AssertNotOnPrivateThread(); // We have to wait for the task to be executed, in case someone calls // |AddSlave()| followed immediately by |Shutdown()|. base::WaitableEvent event(false, false); private_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&MasterConnectionManager::AddSlaveOnPrivateThread, base::Unretained(this), base::Passed(&slave_info), base::Passed(&platform_handle), base::Unretained(&event))); event.Wait(); } bool MasterConnectionManager::AllowConnect( const ConnectionIdentifier& connection_id) { AssertNotOnPrivateThread(); return AllowConnectImpl(kMasterProcessIdentifier, connection_id); } bool MasterConnectionManager::CancelConnect( const ConnectionIdentifier& connection_id) { AssertNotOnPrivateThread(); return CancelConnectImpl(kMasterProcessIdentifier, connection_id); } bool MasterConnectionManager::Connect( const ConnectionIdentifier& connection_id, ProcessIdentifier* peer_process_identifier, embedder::ScopedPlatformHandle* platform_handle) { AssertNotOnPrivateThread(); return ConnectImpl(kMasterProcessIdentifier, connection_id, peer_process_identifier, platform_handle); } bool MasterConnectionManager::AllowConnectImpl( ProcessIdentifier process_identifier, const ConnectionIdentifier& connection_id) { DCHECK_NE(process_identifier, kInvalidProcessIdentifier); base::AutoLock locker(lock_); auto it = pending_connections_.find(connection_id); if (it == pending_connections_.end()) { pending_connections_[connection_id] = new PendingConnectionInfo(process_identifier); // TODO(vtl): Track process identifier -> pending connections also (so these // can be removed efficiently if that process disconnects). DVLOG(1) << "New pending connection ID " << connection_id << ": AllowConnect() from first process identifier " << process_identifier; return true; } PendingConnectionInfo* info = it->second; if (info->state == PendingConnectionInfo::AWAITING_SECOND_ALLOW_CONNECT) { info->state = PendingConnectionInfo::AWAITING_CONNECTS_FROM_BOTH; info->second = process_identifier; DVLOG(1) << "Pending connection ID " << connection_id << ": AllowConnect() from second process identifier " << process_identifier; return true; } // Someone's behaving badly, but we don't know who (it might not be the // caller). LOG(ERROR) << "AllowConnect() from process " << process_identifier << " for connection ID " << connection_id << " already in state " << info->state; pending_connections_.erase(it); delete info; return false; } bool MasterConnectionManager::CancelConnectImpl( ProcessIdentifier process_identifier, const ConnectionIdentifier& connection_id) { DCHECK_NE(process_identifier, kInvalidProcessIdentifier); base::AutoLock locker(lock_); auto it = pending_connections_.find(connection_id); if (it == pending_connections_.end()) { // Not necessarily the caller's fault, and not necessarily an error. DVLOG(1) << "CancelConnect() from process " << process_identifier << " for connection ID " << connection_id << " which is not (or no longer) pending"; return true; } PendingConnectionInfo* info = it->second; if (process_identifier != info->first && process_identifier != info->second) { LOG(ERROR) << "CancelConnect() from process " << process_identifier << " for connection ID " << connection_id << " which is neither connectee"; return false; } // Just erase it. The other side may also try to cancel, in which case it'll // "fail" in the first if statement above (we assume that connection IDs never // collide, so there's no need to carefully track both sides). pending_connections_.erase(it); delete info; return true; } bool MasterConnectionManager::ConnectImpl( ProcessIdentifier process_identifier, const ConnectionIdentifier& connection_id, ProcessIdentifier* peer_process_identifier, embedder::ScopedPlatformHandle* platform_handle) { DCHECK_NE(process_identifier, kInvalidProcessIdentifier); DCHECK(peer_process_identifier); DCHECK(platform_handle); DCHECK(!platform_handle->is_valid()); // Not technically wrong, but unlikely. base::AutoLock locker(lock_); auto it = pending_connections_.find(connection_id); if (it == pending_connections_.end()) { // Not necessarily the caller's fault. LOG(ERROR) << "Connect() from process " << process_identifier << " for connection ID " << connection_id << " which is not pending"; return false; } PendingConnectionInfo* info = it->second; if (info->state == PendingConnectionInfo::AWAITING_CONNECTS_FROM_BOTH) { DCHECK(!info->remaining_handle.is_valid()); if (process_identifier == info->first) { info->state = PendingConnectionInfo::AWAITING_CONNECT_FROM_SECOND; *peer_process_identifier = info->second; } else if (process_identifier == info->second) { info->state = PendingConnectionInfo::AWAITING_CONNECT_FROM_FIRST; *peer_process_identifier = info->first; } else { LOG(ERROR) << "Connect() from process " << process_identifier << " for connection ID " << connection_id << " which is neither connectee"; return false; } if (info->first == info->second) { platform_handle->reset(); DCHECK(!info->remaining_handle.is_valid()); } else { embedder::PlatformChannelPair platform_channel_pair; *platform_handle = platform_channel_pair.PassServerHandle(); DCHECK(platform_handle->is_valid()); info->remaining_handle = platform_channel_pair.PassClientHandle(); DCHECK(info->remaining_handle.is_valid()); } DVLOG(1) << "Connection ID " << connection_id << ": first Connect() from process identifier " << process_identifier; return true; } ProcessIdentifier remaining_connectee; ProcessIdentifier peer; if (info->state == PendingConnectionInfo::AWAITING_CONNECT_FROM_FIRST) { remaining_connectee = info->first; peer = info->second; } else if (info->state == PendingConnectionInfo::AWAITING_CONNECT_FROM_SECOND) { remaining_connectee = info->second; peer = info->first; } else { // Someone's behaving badly, but we don't know who (it might not be the // caller). LOG(ERROR) << "Connect() from process " << process_identifier << " for connection ID " << connection_id << " in state " << info->state; pending_connections_.erase(it); delete info; return false; } if (process_identifier != remaining_connectee) { LOG(ERROR) << "Connect() from process " << process_identifier << " for connection ID " << connection_id << " which is not the remaining connectee"; pending_connections_.erase(it); delete info; return false; } *peer_process_identifier = peer; *platform_handle = info->remaining_handle.Pass(); DCHECK((info->first == info->second) ^ platform_handle->is_valid()); pending_connections_.erase(it); delete info; DVLOG(1) << "Connection ID " << connection_id << ": second Connect() from process identifier " << process_identifier; return true; } void MasterConnectionManager::ShutdownOnPrivateThread() { AssertOnPrivateThread(); if (!pending_connections_.empty()) { DVLOG(1) << "Shutting down with connections pending"; for (auto& p : pending_connections_) delete p.second; pending_connections_.clear(); } if (!helpers_.empty()) { DVLOG(1) << "Shutting down with slaves still connected"; for (auto& p : helpers_) { scoped_ptr<embedder::SlaveInfo> slave_info = p.second->Shutdown(); delete p.second; CallOnSlaveDisconnect(slave_info.Pass()); } helpers_.clear(); } } void MasterConnectionManager::AddSlaveOnPrivateThread( scoped_ptr<embedder::SlaveInfo> slave_info, embedder::ScopedPlatformHandle platform_handle, base::WaitableEvent* event) { DCHECK(platform_handle.is_valid()); DCHECK(event); AssertOnPrivateThread(); CHECK_NE(next_process_identifier_, kMasterProcessIdentifier); ProcessIdentifier process_identifier = next_process_identifier_; next_process_identifier_++; scoped_ptr<Helper> helper(new Helper( this, process_identifier, slave_info.Pass(), platform_handle.Pass())); helper->Init(); DCHECK(helpers_.find(process_identifier) == helpers_.end()); helpers_[process_identifier] = helper.release(); DVLOG(1) << "Added process identifier " << process_identifier; event->Signal(); } void MasterConnectionManager::OnError(ProcessIdentifier process_identifier) { DCHECK_NE(process_identifier, kInvalidProcessIdentifier); AssertOnPrivateThread(); auto it = helpers_.find(process_identifier); DCHECK(it != helpers_.end()); Helper* helper = it->second; scoped_ptr<embedder::SlaveInfo> slave_info = helper->Shutdown(); helpers_.erase(it); delete helper; { base::AutoLock locker(lock_); // TODO(vtl): This isn't very efficient. for (auto it = pending_connections_.begin(); it != pending_connections_.end();) { if (it->second->first == process_identifier || it->second->second == process_identifier) { auto it_to_erase = it; ++it; delete it_to_erase->second; pending_connections_.erase(it_to_erase); } else { ++it; } } } CallOnSlaveDisconnect(slave_info.Pass()); } void MasterConnectionManager::CallOnSlaveDisconnect( scoped_ptr<embedder::SlaveInfo> slave_info) { AssertOnPrivateThread(); DCHECK(master_process_delegate_); delegate_thread_task_runner_->PostTask( FROM_HERE, base::Bind(&embedder::MasterProcessDelegate::OnSlaveDisconnect, base::Unretained(master_process_delegate_), base::Passed(&slave_info))); } void MasterConnectionManager::AssertOnDelegateThread() const { DCHECK(base::MessageLoop::current()); DCHECK_EQ(base::MessageLoop::current()->task_runner(), delegate_thread_task_runner_); } void MasterConnectionManager::AssertNotOnPrivateThread() const { // This should only be called after |Init()| and before |Shutdown()|. (If not, // the subsequent |DCHECK_NE()| is invalid, since the current thread may not // have a message loop.) DCHECK(private_thread_.message_loop()); DCHECK_NE(base::MessageLoop::current(), private_thread_.message_loop()); } void MasterConnectionManager::AssertOnPrivateThread() const { // This should only be called after |Init()| and before |Shutdown()|. DCHECK(private_thread_.message_loop()); DCHECK_EQ(base::MessageLoop::current(), private_thread_.message_loop()); } } // namespace system } // namespace mojo
36.384483
80
0.714022
[ "object" ]
b403c05257c4599bfa14ad635e89018fa26a47bc
2,456
cpp
C++
c_src/lib/wm_timetable.cpp
skyworkflows/swm-core
5e5de1bdb1740d773a5285b352976c5f64a30688
[ "BSD-3-Clause" ]
4
2021-04-04T18:34:47.000Z
2021-08-25T13:26:45.000Z
c_src/lib/wm_timetable.cpp
skyworkflows/swm-core
5e5de1bdb1740d773a5285b352976c5f64a30688
[ "BSD-3-Clause" ]
null
null
null
c_src/lib/wm_timetable.cpp
skyworkflows/swm-core
5e5de1bdb1740d773a5285b352976c5f64a30688
[ "BSD-3-Clause" ]
1
2021-08-25T13:26:49.000Z
2021-08-25T13:26:49.000Z
#include "wm_entity_utils.h" #include <iostream> #include "wm_timetable.h" #include <erl_interface.h> #include <ei.h> using namespace swm; SwmTimetable::SwmTimetable() { } SwmTimetable::SwmTimetable(ETERM *term) { if(!term) { std::cerr << "Cannot convert ETERM to SwmTimetable: empty" << std::endl; return; } if(eterm_to_uint64_t(term, 2, start_time)) { std::cerr << "Could not initialize timetable paremeter at position 2" << std::endl; erl_print_term(stderr, term); return; } if(eterm_to_str(term, 3, job_id)) { std::cerr << "Could not initialize timetable paremeter at position 3" << std::endl; erl_print_term(stderr, term); return; } if(eterm_to_str(term, 4, job_nodes)) { std::cerr << "Could not initialize timetable paremeter at position 4" << std::endl; erl_print_term(stderr, term); return; } } void SwmTimetable::set_start_time(const uint64_t &new_val) { start_time = new_val; } void SwmTimetable::set_job_id(const std::string &new_val) { job_id = new_val; } void SwmTimetable::set_job_nodes(const std::vector<std::string> &new_val) { job_nodes = new_val; } uint64_t SwmTimetable::get_start_time() const { return start_time; } std::string SwmTimetable::get_job_id() const { return job_id; } std::vector<std::string> SwmTimetable::get_job_nodes() const { return job_nodes; } int swm::eterm_to_timetable(ETERM* term, int pos, std::vector<SwmTimetable> &array) { ETERM* elist = erl_element(pos, term); if(!ERL_IS_LIST(elist)) { std::cerr << "Could not parse eterm: not a timetable list" << std::endl; return -1; } if(ERL_IS_EMPTY_LIST(elist)) { return 0; } const size_t sz = erl_length(elist); array.reserve(sz); for(size_t i=0; i<sz; ++i) { ETERM* e = erl_hd(elist); array.push_back(SwmTimetable(e)); elist = erl_tl(elist); } return 0; } int swm::eterm_to_timetable(ETERM* eterm, SwmTimetable &obj) { obj = SwmTimetable(eterm); return 0; } void SwmTimetable::print(const std::string &prefix, const char separator) const { std::cerr << prefix << start_time << separator; std::cerr << prefix << job_id << separator; if(job_nodes.empty()) { std::cerr << prefix << "job_nodes: []" << separator; } else { std::cerr << prefix << "job_nodes" << ": ["; for(const auto &q: job_nodes) { std::cerr << q << ","; } std::cerr << "]" << separator; } std::cerr << std::endl; }
22.327273
87
0.65513
[ "vector" ]
b405b55c198ecfd38a2f959e669a8f4b6239f1bc
8,137
cpp
C++
tools/stf_count_multi_process/stf_count_multi_process.cpp
sparcians/stf_tools
a963a34bf9ce39d99b6255a8c0fa75b2c894b8f2
[ "MIT" ]
1
2022-02-17T00:49:09.000Z
2022-02-17T00:49:09.000Z
tools/stf_count_multi_process/stf_count_multi_process.cpp
sparcians/stf_tools
a963a34bf9ce39d99b6255a8c0fa75b2c894b8f2
[ "MIT" ]
null
null
null
tools/stf_count_multi_process/stf_count_multi_process.cpp
sparcians/stf_tools
a963a34bf9ce39d99b6255a8c0fa75b2c894b8f2
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include <rapidjson/document.h> #include <rapidjson/ostreamwrapper.h> #include <rapidjson/writer.h> #include "command_line_parser.hpp" #include "filesystem.hpp" #include "print_utils.hpp" #include "stf_reader.hpp" #include "stf_record_types.hpp" #include "tools_util.hpp" static void parseCommandLine (int argc, char **argv, std::map<size_t, std::string>& traces, bool& print_all, bool& verbose, bool& format_json) { trace_tools::CommandLineParser parser("stf_count_multi_process"); parser.addFlag('a', "Print counts for instructions before the first user process"); parser.addFlag('v', "Print which traces contain each process"); parser.addFlag('j', "Output in JSON format"); parser.addPositionalArgument("trace", "trace in STF format", true); parser.parseArguments(argc, argv); print_all = parser.hasArgument('a'); verbose = parser.hasArgument('v'); format_json = parser.hasArgument('j'); const auto& trace_list = parser.getMultipleValuePositionalArgument(0); for(size_t i = 0; i < trace_list.size(); ++i) { traces.emplace(i, trace_list[i]); } } int main(int argc, char* argv[]) { std::map<size_t, std::string> traces; bool print_all = false; bool verbose = false; bool format_json = false; try { parseCommandLine(argc, argv, traces, print_all, verbose, format_json); } catch(const trace_tools::CommandLineParser::EarlyExitException& e) { std::cerr << e.what() << std::endl; return e.getCode(); } std::map<uint64_t, std::map<size_t, uint64_t>> process_instruction_counts; uint64_t num_insts = 0; for(const auto& trace_pair: traces) { const auto trace_id = trace_pair.first; const auto& trace = trace_pair.second; stf::STFReader reader(trace); process_instruction_counts[0][trace_id] = 0; try { stf::STFRecord::UniqueHandle rec; uint64_t num_context_switches = 0; uint64_t cur_satp = 0; while(reader >> rec) { if(STF_EXPECT_FALSE(rec->getDescriptor() == stf::descriptors::internal::Descriptor::STF_INST_REG)) { const auto& reg_rec = rec->as<stf::InstRegRecord>(); if(STF_EXPECT_FALSE((reg_rec.getOperandType() == stf::Registers::STF_REG_OPERAND_TYPE::REG_DEST) && (reg_rec.getReg() == stf::Registers::STF_REG::STF_REG_CSR_SATP))) { const uint64_t new_satp_value = reg_rec.getScalarData(); // Ignore the initial zeroing out of the satp register process_instruction_counts[new_satp_value].try_emplace(trace_id, 0); cur_satp = new_satp_value; } } else if(STF_EXPECT_FALSE(rec->getDescriptor() == stf::descriptors::internal::Descriptor::STF_EVENT)) { const auto& event_rec = rec->as<stf::EventRecord>(); if(event_rec.isModeChange()) { const auto new_mode = static_cast<stf::EXECUTION_MODE>(event_rec.getData().front()); if(new_mode == stf::EXECUTION_MODE::USER_MODE) { ++num_context_switches; } } } else if(STF_EXPECT_FALSE(rec->isInstructionRecord())) { ++process_instruction_counts[cur_satp][trace_id]; ++num_insts; } } } catch(const stf::EOFException&) { } } std::ostringstream ss; if(format_json) { rapidjson::Document d(rapidjson::kObjectType); auto& d_alloc = d.GetAllocator(); rapidjson::Value object(rapidjson::kObjectType); object.AddMember("num_traces", traces.size(), d_alloc); object.AddMember("num_processes", process_instruction_counts.size() - 1, d_alloc); object.AddMember("num_insts", num_insts, d_alloc); rapidjson::Value processes_json(rapidjson::kObjectType); for(const auto& p: process_instruction_counts) { if(STF_EXPECT_FALSE(!print_all && p.first == 0)) { continue; } uint64_t process_num_insts = 0; rapidjson::Value process_json(rapidjson::kObjectType); rapidjson::Value traces_json(rapidjson::kArrayType); for(const auto& pp: p.second) { process_num_insts += pp.second; traces_json.PushBack(rapidjson::Value(fs::path(traces[pp.first]).filename().c_str(), d_alloc).Move(), d_alloc); } process_json.AddMember("num_insts", process_num_insts, d_alloc); process_json.AddMember("traces", traces_json, d_alloc); ss << std::hex << p.first; processes_json.AddMember(rapidjson::Value(ss.str().c_str(), d_alloc).Move(), process_json, d_alloc); ss.str(""); } object.AddMember("processes", processes_json, d_alloc); rapidjson::OStreamWrapper osw(std::cout); rapidjson::Writer<rapidjson::OStreamWrapper> writer(osw); object.Accept(writer); std::cout << std::endl; } else { static constexpr int PROCESS_ID_COLUMN_WIDTH = 18; static constexpr int INSTRUCTION_COUNT_COLUMN_WIDTH = 17; static constexpr int TRACE_COUNT_COLUMN_WIDTH = 11; static constexpr int COLUMN_SEPARATOR_WIDTH = 4; std::cout << "Number of traces: " << traces.size() << std::endl << "Number of processes: " << process_instruction_counts.size() - 1 << std::endl << "Number of instructions: " << num_insts << std::endl; stf::print_utils::printLeft("Process", PROCESS_ID_COLUMN_WIDTH); stf::print_utils::printSpaces(COLUMN_SEPARATOR_WIDTH); stf::print_utils::printLeft("Instruction Count"); stf::print_utils::printSpaces(COLUMN_SEPARATOR_WIDTH); if(verbose) { stf::print_utils::printLeft("Traces"); } else { stf::print_utils::printLeft("Trace Count"); } std::cout << std::endl; for(const auto& p: process_instruction_counts) { if(STF_EXPECT_FALSE(!print_all && p.first == 0)) { continue; } stf::print_utils::printHex(p.first, PROCESS_ID_COLUMN_WIDTH); stf::print_utils::printSpaces(COLUMN_SEPARATOR_WIDTH); uint64_t process_num_insts = 0; bool first = true; for(const auto& pp: p.second) { process_num_insts += pp.second; if(verbose) { if(STF_EXPECT_FALSE(first)) { first = false; } else { stf::format_utils::formatSpaces(ss, PROCESS_ID_COLUMN_WIDTH + COLUMN_SEPARATOR_WIDTH + INSTRUCTION_COUNT_COLUMN_WIDTH + COLUMN_SEPARATOR_WIDTH); } ss << fs::path(traces[pp.first]).filename().c_str() << std::endl; } } stf::print_utils::printDec(process_num_insts, INSTRUCTION_COUNT_COLUMN_WIDTH, ' '); stf::print_utils::printSpaces(COLUMN_SEPARATOR_WIDTH); if(verbose) { std::cout << ss.str(); ss.str(""); } else { stf::print_utils::printDec(p.second.size(), TRACE_COUNT_COLUMN_WIDTH, ' '); } std::cout << std::endl; } } return 0; }
41.09596
119
0.550694
[ "object" ]
b405f54ab28ed1996526cd1795d6004bb84c48a0
2,137
hpp
C++
HugeCTR/include/cpu/layers/reduce_sum_layer_cpu.hpp
quinnrong94/HugeCTR
1068dc48b05a1219b393144dd3b61a1749f232df
[ "Apache-2.0" ]
1
2021-06-04T04:03:54.000Z
2021-06-04T04:03:54.000Z
HugeCTR/include/cpu/layers/reduce_sum_layer_cpu.hpp
quinnrong94/HugeCTR
1068dc48b05a1219b393144dd3b61a1749f232df
[ "Apache-2.0" ]
null
null
null
HugeCTR/include/cpu/layers/reduce_sum_layer_cpu.hpp
quinnrong94/HugeCTR
1068dc48b05a1219b393144dd3b61a1749f232df
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020, NVIDIA 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. */ #pragma once #include <cpu/layer_cpu.hpp> #include <vector> namespace HugeCTR { /** * Layer which does reduce-sum operation by input tensor. * The reduced axis(dimention) can be selected. The output * tensor will keep the reduced dimention. */ template <typename T> class ReduceSumLayerCPU : public LayerCPU { /* * stores the weight tensors of this layer. */ Tensors2<T> weights_; /* * stores the weight gradient tensors of this layer. */ Tensors2<T> wgrad_; /* * stores the references to the input tensors of this layer. */ Tensors2<T> in_tensors_; /* * stores the references to the output tensors of this layer. */ Tensors2<T> out_tensors_; public: /** * Ctor of ReduceSumLayer. * @param in_tensor the input tensor, could be 2D or 3D * @param out_tensor the resulting output tensor * @param axis the reduced dimention, could be 0,1,2 * @param device_id the id of GPU where this layer belongs */ ReduceSumLayerCPU(const Tensor2<T>& in_tensors, Tensor2<T>& out_tensor, const std::shared_ptr<GeneralBuffer2<HostAllocator>>& blobs_buff, int axis); ~ReduceSumLayerCPU(){}; /** * ReduceSumLayer's foward propagation * @param stream CUDA stream where the foward propagation is executed */ void fprop(bool is_train) override; /** * ReduceSumLayer's backward propagation * @param stream CUDA stream where the foward propagation is executed */ void bprop() override; private: int axis_; }; } // namespace HugeCTR
28.118421
93
0.705194
[ "vector", "3d" ]
b4064c08173c16af35d36319a3fda98941b53a12
9,948
hpp
C++
RobWork/src/rw/proximity/ProximityStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/proximity/ProximityStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/proximity/ProximityStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef RW_PROXIMITY_PROXIMITYSTRATEGY_HPP #define RW_PROXIMITY_PROXIMITYSTRATEGY_HPP /** * @file rw/proximity/ProximityStrategy.hpp */ #if !defined(SWIG) #include "ProximityModel.hpp" #include <rw/core/ExtensionPoint.hpp> #include <rw/kinematics/FrameMap.hpp> #include <string> #endif namespace rw { namespace geometry { class Geometry; }} // namespace rw::geometry namespace rw { namespace kinematics { class Frame; }} // namespace rw::kinematics namespace rw { namespace models { class Object; }} // namespace rw::models namespace rw { namespace proximity { /** @addtogroup proximity */ /*@{*/ /** * @brief The ProximityStrategy interface is a clean interface * for defining methods that are common for different proximity * strategy classes. Specifically adding of geometric models and * relating them to frames. */ class ProximityStrategy { public: //! @brief smart pointer type to this class typedef rw::core::Ptr< ProximityStrategy > Ptr; /** * @brief Destructor. */ virtual ~ProximityStrategy (); /** * @brief Adds a Proximity model of a frame to this strategy. * * The Proximity model is the one specified in the frames property * * @param object [in] the frame on which the Proximity model is to be * created. * * @return true if a Proximity model was succesfully created and linked * with the frame; false otherwise. */ // virtual bool addModel(const kinematics::Frame* frame); virtual bool addModel (rw::core::Ptr< rw::models::Object > object); /** * @brief Adds a Proximity model to a frame where the geometry is copied * in the underlying proximity strategy. * * The Proximity model is constructed from the list of faces * * @param frame [in] the frame to which the Proximity model should associate * @param faces [in] list of faces from which to construct the Proximity model * @return true if a Proximity model was succesfully created and linked * with the frame; false otherwise. */ virtual bool addModel (const rw::kinematics::Frame* frame, const rw::geometry::Geometry& faces); /** * @brief Adds a Proximity model to a frame. * * The Proximity model is constructed from the list of faces * * @param frame [in] the frame to which the Proximity model should associate * @param faces [in] list of faces from which to construct the Proximity model * @param forceCopy [in] force the strategy to copy the geometry data, if false the * strategy may choose to store the geometry reference or not. * @return true if a Proximity model was succesfully created and linked * with the frame; false otherwise. */ virtual bool addModel (const rw::kinematics::Frame* frame, rw::core::Ptr< rw::geometry::Geometry > faces, bool forceCopy = false); /** * @brief Tells whether the frame has a proximity model in the strategy * * To have a proximity model does not means that it is loaded. If a \b GeoID string from * which a model can be loaded it returns true as well * * @param frame [in] the frame to check for1.0/ * @return true if a model exists or can be created */ virtual bool hasModel (const rw::kinematics::Frame* frame); /** @brief Clear (remove all) model information for frame \b frame. */ virtual void clearFrame (const rw::kinematics::Frame* frame); /** @brief Clear (remove all) model information for all frames. */ virtual void clearFrames (); //// new functions added to support old interface /** * @brief get the proximitymodel associated to \b frame. If no model * has been associated to frame then NULL is returned. * @param frame [in] frame for which an proximitymodel is associated */ ProximityModel::Ptr getModel (const rw::kinematics::Frame* frame); //// this is the new interface based on CollisionModelInfo /** * @brief creates an empty ProximityModel */ virtual ProximityModel::Ptr createModel () = 0; /** * @brief deallocates the memory used for \b model * @param model */ virtual void destroyModel (ProximityModel* model) = 0; /** * @brief adds geometry to a specific proximity model. The proximity strategy copies all * data of the geometry. * @param model [in] the proximity model to add data to * @param geom [in] the geometry that is to be added */ virtual bool addGeometry (ProximityModel* model, const rw::geometry::Geometry& geom) = 0; /** * @brief adds geometry to a specific model. Depending on the option \b forceCopy the * proximity strategy may choose to copy the geometry data or use it directly. * @param model * @param geom * @param forceCopy * @return */ virtual bool addGeometry (ProximityModel* model, rw::core::Ptr< rw::geometry::Geometry > geom, bool forceCopy = false) = 0; /** * @brief removes a geometry from a specific proximity model */ virtual bool removeGeometry (ProximityModel* model, const std::string& geomId) = 0; /** * @brief the list of all geometry ids that are associated to * the proximity model \b model is returned * @param model [in] the model containing the geometries * @return all geometry ids associated to the proximity model */ virtual std::vector< std::string > getGeometryIDs (ProximityModel* model) = 0; /** * @brief the list of all geometry that are associated to * the proximity model \b model is returned * @param model [in] the model containing the geometries * @return all geometry associated to the proximity model */ virtual std::vector< rw::core::Ptr< rw::geometry::Geometry > > getGeometrys (rw::proximity::ProximityModel* model); /** * @brief Clears any stored model information */ virtual void clear () = 0; /** * @addtogroup extensionpoints * @extensionpoint{rw::proximity::ProximityStrategy::Factory,rw::proximity::ProximityStrategy,rw.proximity.ProximityStrategy} */ /** * @brief A factory for a ProximityStrategy. This factory also defines an ExtensionPoint. * * Extensions providing a ProximityStrategy implementation can extend this factory by * registering the extension using the id "rw.proximity.ProximityStrategy". * * Typically one or more of the following ProximityStrategy types will be available: * - RW - rw::proximity::ProximityStrategyRW - Internal RobWork proximity strategy * - Bullet - rwlibs::proximitystrategies::ProximityStrategyBullet - Bullet Physics * - PQP - rwlibs::proximitystrategies::ProximityStrategyPQP - Proximity Query Package * - FCL - rwlibs::proximitystrategies::ProximityStrategyFCL - Flexible Collision Library * - Yaobi - rwlibs::proximitystrategies::ProximityStrategyYaobi - Yaobi */ class Factory : public rw::core::ExtensionPoint< ProximityStrategy > { public: /** * @brief Get the available strategies. * @return a vector of identifiers for strategies. */ static std::vector< std::string > getStrategies (); /** * @brief Check if strategy is available. * @param strategy [in] the name of the strategy. * @return true if available, false otherwise. */ static bool hasStrategy (const std::string& strategy); /** * @brief Create a new strategy. * @param strategy [in] the name of the strategy. * @return a pointer to a new CollisionStrategy. */ static ProximityStrategy::Ptr makeStrategy (const std::string& strategy); private: Factory (); }; private: ProximityStrategy (const ProximityStrategy&); ProximityStrategy& operator= (const ProximityStrategy&); rw::kinematics::FrameMap< ProximityModel::Ptr > _frameToModel; protected: /** * @brief Creates object */ ProximityStrategy (); }; /*@}*/ }} // namespace rw::proximity #endif // end include guard
38.261538
133
0.602232
[ "geometry", "object", "vector", "model" ]
b41071a63973ab91c412d946523b579282e9267b
3,729
hh
C++
src/renderer/program.hh
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
4
2015-10-01T20:10:20.000Z
2021-08-28T23:43:33.000Z
src/renderer/program.hh
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
null
null
null
src/renderer/program.hh
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
null
null
null
/* program.hh -- Copyright (c) 2013 Noel Cower. All rights reserved. See COPYING under the project root for the source code license. If this file is not present, refer to <https://raw.github.com/nilium/snow/master/COPYING>. */ #ifndef __SNOW__PROGRAM_HH__ #define __SNOW__PROGRAM_HH__ #include "../config.hh" #include "sgl.hh" #include <map> #include <set> namespace snow { struct rshader_t; struct S_EXPORT rprogram_t { using name_set_t = std::set<string>; using uniform_loc_t = std::pair<GLint, name_set_t::const_iterator>; using uniforms_t = std::map<int, uniform_loc_t>; rprogram_t(); rprogram_t(rprogram_t &&shader); rprogram_t &operator = (rprogram_t &&shader); ~rprogram_t(); rprogram_t(const rprogram_t &) = delete; rprogram_t &operator = (const rprogram_t &) = delete; // equiv. to glUseProgram // Will s_throw(std::runtime_error if usable, ) returns false. void use(); // Binds the key to the uniform name. This can be done either before or after // linking, attaching shaders, or any other stage of the program provided // valid() returns true. If valid() returns false, throws std::runtime_error. void bind_uniform(int key, const string &name); // Returns the location of a previously-bound uniform's location. Returns -1 // if no uniform location is found or the program is not linked. GLint uniform_location(int key) const; // Slower alternative: looks for the uniform location based on its actual name. GLint uniform_location(const string &name) const; void bind_frag_out(GLuint colorNumber, const string &name); #if GL_VERSION_3_3 || GL_ARB_blend_func_extended void bind_frag_out(GLuint colorNumber, GLuint index, const string &name); #endif // Binds a named attribute to a given location (the attribute index). // Attributes aren't bound until link is called. If an attribute is bound // after link is called, link must be called again. This is simply an error- // checked wrapped on top of glBindAttribLocation. void bind_attrib(GLuint location, const string &name); inline bool valid() const { return program_ != 0; } inline bool linked() const { return linked_; } // Synonym for combined compiled() and linked() calls inline bool usable() const { return valid() && linked(); } void attach_shader(const rshader_t &shader); void detach_shader(const rshader_t &shader); bool link(); // Probably shouldn't be used in release builds - will set the error string // with the program's info log if validation fails. bool validate(); // Deletes the shader program (if compiled), any intermediate data, and all // uniform bindings associated with this shader. void unload(); inline bool has_error() const { return error_str_.size() != 0; } inline string error_string() const { return error_str_; } const uniforms_t &bound_uniforms() const { return uniforms_; } private: S_HIDDEN void zero(); S_HIDDEN void load_uniforms(); S_HIDDEN void load_uniform(uniform_loc_t &loc); S_HIDDEN void load_attribs(); // Program object name GLuint program_; // Whether the program has been linked yet bool linked_; // Set of uniforms, their locations, and names iters uniforms_t uniforms_; // Set of name strings for the program (TODO: use global name set) name_set_t names_; // Error string, set after either link() or validate() string error_str_; }; } // namespace snow #endif /* end __SNOW__PROGRAM_HH__ include guard */
33.594595
86
0.678198
[ "object" ]
b411f6b0c29b52505129b13765921c668a22e4b3
15,859
cpp
C++
blades/xbmc/xbmc/addons/GUIDialogAddonInfo.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/xbmc/xbmc/addons/GUIDialogAddonInfo.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/xbmc/xbmc/addons/GUIDialogAddonInfo.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "GUIDialogAddonInfo.h" #include "addons/AddonInstaller.h" #include "addons/AddonManager.h" #include "AddonDatabase.h" #include "FileItem.h" #include "filesystem/Directory.h" #include "GUIDialogAddonSettings.h" #include "cores/AudioEngine/DSPAddons/ActiveAEDSP.h" #include "dialogs/GUIDialogContextMenu.h" #include "dialogs/GUIDialogTextViewer.h" #include "dialogs/GUIDialogOK.h" #include "dialogs/GUIDialogSelect.h" #include "dialogs/GUIDialogYesNo.h" #include "GUIUserMessages.h" #include "guilib/GUIWindowManager.h" #include "input/Key.h" #include "settings/Settings.h" #include "utils/JobManager.h" #include "utils/FileOperationJob.h" #include "utils/StringUtils.h" #include "utils/URIUtils.h" #include "utils/log.h" #include "utils/Variant.h" #include "Util.h" #include "interfaces/builtins/Builtins.h" #include <utility> #define CONTROL_BTN_INSTALL 6 #define CONTROL_BTN_ENABLE 7 #define CONTROL_BTN_UPDATE 8 #define CONTROL_BTN_SETTINGS 9 #define CONTROL_BTN_CHANGELOG 10 #define CONTROL_BTN_SELECT 12 #define CONTROL_BTN_AUTOUPDATE 13 using namespace ADDON; using namespace XFILE; CGUIDialogAddonInfo::CGUIDialogAddonInfo(void) : CGUIDialog(WINDOW_DIALOG_ADDON_INFO, "DialogAddonInfo.xml"), m_jobid(0), m_changelog(false) { m_item = CFileItemPtr(new CFileItem); m_loadType = KEEP_IN_MEMORY; } CGUIDialogAddonInfo::~CGUIDialogAddonInfo(void) { } bool CGUIDialogAddonInfo::OnMessage(CGUIMessage& message) { switch ( message.GetMessage() ) { case GUI_MSG_WINDOW_DEINIT: { if (m_jobid) CJobManager::GetInstance().CancelJob(m_jobid); } break; case GUI_MSG_CLICKED: { int iControl = message.GetSenderId(); if (iControl == CONTROL_BTN_UPDATE) { OnUpdate(); return true; } if (iControl == CONTROL_BTN_INSTALL) { if (m_localAddon) { if (m_localAddon->Type() == ADDON_ADSPDLL && ActiveAE::CActiveAEDSP::GetInstance().IsProcessing()) { CGUIDialogOK::ShowAndGetInput(24137, 0, 24138, 0); return true; } } if (!m_localAddon) { OnInstall(); return true; } else { OnUninstall(); return true; } } else if (iControl == CONTROL_BTN_SELECT) { OnSelect(); return true; } else if (iControl == CONTROL_BTN_ENABLE) { if (m_localAddon) { if (m_localAddon->Type() == ADDON_ADSPDLL && ActiveAE::CActiveAEDSP::GetInstance().IsProcessing()) { CGUIDialogOK::ShowAndGetInput(24137, 0, 24138, 0); return true; } } OnEnable(!m_item->GetProperty("Addon.Enabled").asBoolean()); return true; } else if (iControl == CONTROL_BTN_SETTINGS) { OnSettings(); return true; } else if (iControl == CONTROL_BTN_CHANGELOG) { OnChangeLog(); return true; } else if (iControl == CONTROL_BTN_AUTOUPDATE) { OnToggleAutoUpdates(); return true; } } break; default: break; } return CGUIDialog::OnMessage(message); } bool CGUIDialogAddonInfo::OnAction(const CAction &action) { if (action.GetID() == ACTION_SHOW_INFO) { Close(); return true; } return CGUIDialog::OnAction(action); } void CGUIDialogAddonInfo::OnInitWindow() { UpdateControls(); CGUIDialog::OnInitWindow(); m_changelog = false; } void CGUIDialogAddonInfo::UpdateControls() { bool isInstalled = NULL != m_localAddon.get(); bool isEnabled = isInstalled && m_item->GetProperty("Addon.Enabled").asBoolean(); bool canDisable = isInstalled && CAddonMgr::GetInstance().CanAddonBeDisabled(m_localAddon->ID()); bool canInstall = !isInstalled && m_item->GetProperty("Addon.Broken").empty(); bool isRepo = (isInstalled && m_localAddon->Type() == ADDON_REPOSITORY) || (m_addon && m_addon->Type() == ADDON_REPOSITORY); CONTROL_ENABLE_ON_CONDITION(CONTROL_BTN_INSTALL, canDisable || canInstall); SET_CONTROL_LABEL(CONTROL_BTN_INSTALL, isInstalled ? 24037 : 24038); CONTROL_ENABLE_ON_CONDITION(CONTROL_BTN_ENABLE, canDisable); SET_CONTROL_LABEL(CONTROL_BTN_ENABLE, isEnabled ? 24021 : 24022); CONTROL_ENABLE_ON_CONDITION(CONTROL_BTN_UPDATE, isInstalled); bool autoUpdatesOn = CSettings::GetInstance().GetInt(CSettings::SETTING_GENERAL_ADDONUPDATES) == AUTO_UPDATES_ON; CONTROL_ENABLE_ON_CONDITION(CONTROL_BTN_AUTOUPDATE, isInstalled && autoUpdatesOn); SET_CONTROL_SELECTED(GetID(), CONTROL_BTN_AUTOUPDATE, isInstalled && autoUpdatesOn && !CAddonMgr::GetInstance().IsBlacklisted(m_localAddon->ID())); SET_CONTROL_LABEL(CONTROL_BTN_AUTOUPDATE, 21340); CONTROL_ENABLE_ON_CONDITION(CONTROL_BTN_SELECT, isEnabled && (CanOpen() || CanRun() || (CanUse() && !m_localAddon->IsInUse()))); SET_CONTROL_LABEL(CONTROL_BTN_SELECT, CanUse() ? 21480 : (CanOpen() ? 21478 : 21479)); CONTROL_ENABLE_ON_CONDITION(CONTROL_BTN_SETTINGS, isInstalled && m_localAddon->HasSettings()); CONTROL_ENABLE_ON_CONDITION(CONTROL_BTN_CHANGELOG, !isRepo); } static const std::string LOCAL_CACHE = "special_local_cache"; static bool CompareVersion(const std::pair<AddonVersion, std::string>& lhs, const std::pair<AddonVersion, std::string>& rhs) { return lhs.first > rhs.first; }; void CGUIDialogAddonInfo::OnUpdate() { if (!m_localAddon) return; CAddonDatabase database; if (!database.Open()) return; std::vector<std::pair<AddonVersion, std::string>> versions; if (!database.GetAvailableVersions(m_localAddon->ID(), versions)) return; CFileItemList items; if (XFILE::CDirectory::GetDirectory("special://home/addons/packages/", items, ".zip", DIR_FLAG_NO_FILE_DIRS)) { for (int i = 0; i < items.Size(); ++i) { std::string packageId; std::string versionString; if (AddonVersion::SplitFileName(packageId, versionString, items[i]->GetLabel())) { if (packageId == m_localAddon->ID()) { std::string hash; std::string path(items[i]->GetPath()); if (database.GetPackageHash(m_localAddon->ID(), items[i]->GetPath(), hash)) { std::string md5 = CUtil::GetFileMD5(path); if (md5 == hash) versions.push_back(std::make_pair(AddonVersion(versionString), LOCAL_CACHE)); } } } } } auto* dialog = static_cast<CGUIDialogSelect*>(g_windowManager.GetWindow(WINDOW_DIALOG_SELECT)); dialog->Reset(); dialog->SetHeading(CVariant{21338}); dialog->SetUseDetails(true); std::stable_sort(versions.begin(), versions.end(), CompareVersion); for (const auto& versionInfo : versions) { CFileItem item(StringUtils::Format(g_localizeStrings.Get(21339).c_str(), versionInfo.first.asString().c_str())); if (versionInfo.first == m_localAddon->Version()) item.Select(true); AddonPtr repo; if (versionInfo.second == LOCAL_CACHE) { item.SetProperty("Addon.Summary", g_localizeStrings.Get(24095)); item.SetIconImage("DefaultAddonRepository.png"); dialog->Add(item); } else if (CAddonMgr::GetInstance().GetAddon(versionInfo.second, repo, ADDON_REPOSITORY)) { item.SetProperty("Addon.Summary", repo->Name()); item.SetIconImage(repo->Icon()); dialog->Add(item); } } dialog->Open(); if (dialog->IsConfirmed()) { Close(); auto selected = versions.at(dialog->GetSelectedLabel()); //turn auto updating off if downgrading if (selected.first < m_localAddon->Version()) CAddonMgr::GetInstance().AddToUpdateBlacklist(m_localAddon->ID()); if (selected.second == LOCAL_CACHE) CAddonInstaller::GetInstance().InstallFromZip(StringUtils::Format("special://home/addons/packages/%s-%s.zip", m_localAddon->ID().c_str(), selected.first.asString().c_str())); else CAddonInstaller::GetInstance().Install(m_addon->ID(), selected.first, selected.second); } } void CGUIDialogAddonInfo::OnToggleAutoUpdates() { CGUIMessage msg(GUI_MSG_IS_SELECTED, GetID(), CONTROL_BTN_AUTOUPDATE); if (OnMessage(msg)) { bool selected = msg.GetParam1() == 1; if (selected) CAddonMgr::GetInstance().RemoveFromUpdateBlacklist(m_localAddon->ID()); else CAddonMgr::GetInstance().AddToUpdateBlacklist(m_localAddon->ID()); } } void CGUIDialogAddonInfo::OnInstall() { if (!g_passwordManager.CheckMenuLock(WINDOW_ADDON_BROWSER)) return; CAddonInstaller::GetInstance().InstallOrUpdate(m_addon->ID()); Close(); } void CGUIDialogAddonInfo::OnSelect() { if (!m_localAddon) return; Close(); if (CanOpen() || CanRun()) CBuiltins::GetInstance().Execute("RunAddon(" + m_localAddon->ID() + ")"); else if (CanUse()) CAddonMgr::GetInstance().SetDefault(m_localAddon->Type(), m_localAddon->ID()); } bool CGUIDialogAddonInfo::CanOpen() const { return m_localAddon && m_localAddon->Type() == ADDON_PLUGIN; } bool CGUIDialogAddonInfo::CanRun() const { return m_localAddon && m_localAddon->Type() == ADDON_SCRIPT; } bool CGUIDialogAddonInfo::CanUse() const { return m_localAddon && ( m_localAddon->Type() == ADDON_SKIN || m_localAddon->Type() == ADDON_SCREENSAVER || m_localAddon->Type() == ADDON_VIZ || m_localAddon->Type() == ADDON_SCRIPT_WEATHER || m_localAddon->Type() == ADDON_RESOURCE_LANGUAGE || m_localAddon->Type() == ADDON_RESOURCE_UISOUNDS); } bool CGUIDialogAddonInfo::PromptIfDependency(int heading, int line2) { if (!m_localAddon) return false; VECADDONS addons; std::vector<std::string> deps; CAddonMgr::GetInstance().GetAllAddons(addons); for (VECADDONS::const_iterator it = addons.begin(); it != addons.end();++it) { ADDONDEPS::const_iterator i = (*it)->GetDeps().find(m_localAddon->ID()); if (i != (*it)->GetDeps().end() && !i->second.second) // non-optional dependency deps.push_back((*it)->Name()); } if (!deps.empty()) { std::string line0 = StringUtils::Format(g_localizeStrings.Get(24046).c_str(), m_localAddon->Name().c_str()); std::string line1 = StringUtils::Join(deps, ", "); CGUIDialogOK::ShowAndGetInput(CVariant{heading}, CVariant{std::move(line0)}, CVariant{std::move(line1)}, CVariant{line2}); return true; } return false; } void CGUIDialogAddonInfo::OnUninstall() { if (!m_localAddon.get()) return; if (!g_passwordManager.CheckMenuLock(WINDOW_ADDON_BROWSER)) return; // ensure the addon is not a dependency of other installed addons if (PromptIfDependency(24037, 24047)) return; // prompt user to be sure if (!CGUIDialogYesNo::ShowAndGetInput(CVariant{24037}, CVariant{750})) return; CJobManager::GetInstance().AddJob(new CAddonUnInstallJob(m_localAddon), &CAddonInstaller::GetInstance()); Close(); } void CGUIDialogAddonInfo::OnEnable(bool enable) { if (!m_localAddon.get()) return; if (!g_passwordManager.CheckMenuLock(WINDOW_ADDON_BROWSER)) return; if (!enable && PromptIfDependency(24075, 24091)) return; if (enable) CAddonMgr::GetInstance().EnableAddon(m_localAddon->ID()); else CAddonMgr::GetInstance().DisableAddon(m_localAddon->ID()); SetItem(m_item); UpdateControls(); g_windowManager.SendMessage(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE); } void CGUIDialogAddonInfo::OnSettings() { CGUIDialogAddonSettings::ShowAndGetInput(m_localAddon); } void CGUIDialogAddonInfo::OnChangeLog() { CGUIDialogTextViewer* pDlgInfo = (CGUIDialogTextViewer*)g_windowManager.GetWindow(WINDOW_DIALOG_TEXT_VIEWER); std::string name; if (m_addon) name = m_addon->Name(); else if (m_localAddon) name = m_localAddon->Name(); pDlgInfo->SetHeading(g_localizeStrings.Get(24054)+" - "+name); if (m_item->GetProperty("Addon.Changelog").empty()) { pDlgInfo->SetText(g_localizeStrings.Get(13413)); CFileItemList items; if (m_localAddon && !m_item->GetProperty("Addon.UpdateAvail").asBoolean()) { items.Add(CFileItemPtr(new CFileItem(m_localAddon->ChangeLog(),false))); } else items.Add(CFileItemPtr(new CFileItem(m_addon->ChangeLog(),false))); items[0]->Select(true); m_jobid = CJobManager::GetInstance().AddJob( new CFileOperationJob(CFileOperationJob::ActionCopy,items, "special://temp/"),this); } else pDlgInfo->SetText(m_item->GetProperty("Addon.Changelog").asString()); m_changelog = true; pDlgInfo->Open(); m_changelog = false; } bool CGUIDialogAddonInfo::ShowForItem(const CFileItemPtr& item) { CGUIDialogAddonInfo* dialog = (CGUIDialogAddonInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_ADDON_INFO); if (!dialog) return false; if (!dialog->SetItem(item)) return false; dialog->Open(); return true; } bool CGUIDialogAddonInfo::SetItem(const CFileItemPtr& item) { *m_item = *item; // grab the local addon, if it's available m_localAddon.reset(); m_addon.reset(); if (CAddonMgr::GetInstance().GetAddon(item->GetProperty("Addon.ID").asString(), m_localAddon)) // sets m_localAddon if installed regardless of enabled state m_item->SetProperty("Addon.Enabled", "true"); else m_item->SetProperty("Addon.Enabled", "false"); m_item->SetProperty("Addon.Installed", m_localAddon ? "true" : "false"); CAddonDatabase database; database.Open(); database.GetAddon(item->GetProperty("Addon.ID").asString(),m_addon); if (TranslateType(item->GetProperty("Addon.intType").asString()) == ADDON_REPOSITORY) { CAddonDatabase database; database.Open(); VECADDONS addons; if (m_addon) database.GetRepositoryContent(m_addon->ID(), addons); else if (m_localAddon) // sanity database.GetRepositoryContent(m_localAddon->ID(), addons); int tot=0; for (int i = ADDON_UNKNOWN+1;i<ADDON_MAX;++i) { int num=0; for (unsigned int j=0;j<addons.size();++j) { if (addons[j]->Type() == (TYPE)i) ++num; } m_item->SetProperty("Repo." + TranslateType((TYPE)i), num); tot += num; } m_item->SetProperty("Repo.Addons", tot); } return true; } void CGUIDialogAddonInfo::OnJobComplete(unsigned int jobID, bool success, CJob* job) { if (!m_changelog) return; CGUIDialogTextViewer* pDlgInfo = (CGUIDialogTextViewer*)g_windowManager.GetWindow(WINDOW_DIALOG_TEXT_VIEWER); m_jobid = 0; if (!success) { pDlgInfo->SetText(g_localizeStrings.Get(195)); } else { CFile file; XFILE::auto_buffer buf; if (file.LoadFile("special://temp/" + URIUtils::GetFileName(((CFileOperationJob*)job)->GetItems()[0]->GetPath()), buf) > 0) { std::string str(buf.get(), buf.length()); m_item->SetProperty("Addon.Changelog", str); pDlgInfo->SetText(str); } } CGUIMessage msg(GUI_MSG_NOTIFY_ALL, WINDOW_DIALOG_TEXT_VIEWER, 0, GUI_MSG_UPDATE); g_windowManager.SendThreadMessage(msg); }
29.368519
158
0.676714
[ "vector" ]
b41233d2b654b60b50c9cbf394c537d0c58046a8
2,532
cpp
C++
src/Etterna/Models/Misc/RandomSample.cpp
mattbox/etterna
0a7bd768cffd6f39a3d84d76964097e43011ce33
[ "MIT" ]
551
2017-06-02T05:14:54.000Z
2022-03-31T03:43:51.000Z
src/Etterna/Models/Misc/RandomSample.cpp
mattbox/etterna
0a7bd768cffd6f39a3d84d76964097e43011ce33
[ "MIT" ]
799
2017-06-11T12:30:26.000Z
2022-03-31T23:56:48.000Z
src/Etterna/Models/Misc/RandomSample.cpp
bluebandit21/etterna
995deaacd430c8ea8d68635b906568117454d4cc
[ "MIT" ]
177
2017-06-02T03:41:39.000Z
2022-03-14T06:22:08.000Z
#include "Etterna/Globals/global.h" #include "RageUtil/Misc/RageLog.h" #include "RageUtil/Sound/RageSound.h" #include "RageUtil/Utils/RageUtil.h" #include "RandomSample.h" #include "Etterna/Globals/rngthing.h" #include <algorithm> RandomSample::RandomSample() { m_iIndexLastPlayed = -1; } RandomSample::~RandomSample() { UnloadAll(); } bool RandomSample::Load(const std::string& sFilePath, int iMaxToLoad) { if (GetExtension(sFilePath).empty()) return LoadSoundDir(sFilePath, iMaxToLoad); return LoadSound(sFilePath); } void RandomSample::UnloadAll() { for (auto& m_pSample : m_pSamples) delete m_pSample; m_pSamples.clear(); } bool RandomSample::LoadSoundDir(std::string sDir, int iMaxToLoad) { if (sDir.empty()) return true; // make sure there's a slash at the end of this path ensure_slash_at_end(sDir); std::vector<std::string> arraySoundFiles; GetDirListing(sDir + "*.mp3", arraySoundFiles); GetDirListing(sDir + "*.oga", arraySoundFiles); GetDirListing(sDir + "*.ogg", arraySoundFiles); GetDirListing(sDir + "*.wav", arraySoundFiles); std::shuffle( arraySoundFiles.begin(), arraySoundFiles.end(), g_RandomNumberGenerator); arraySoundFiles.resize( std::min(arraySoundFiles.size(), static_cast<size_t>(iMaxToLoad))); for (auto& arraySoundFile : arraySoundFiles) LoadSound(sDir + arraySoundFile); return true; } bool RandomSample::LoadSound(const std::string& sSoundFilePath) { LOG->Trace("RandomSample::LoadSound( %s )", sSoundFilePath.c_str()); auto* pSS = new RageSound; if (!pSS->Load(sSoundFilePath)) { LOG->Trace("Error loading \"%s\": %s", sSoundFilePath.c_str(), pSS->GetError().c_str()); delete pSS; return false; } m_pSamples.push_back(pSS); return true; } int RandomSample::GetNextToPlay() { // play one of the samples if (m_pSamples.empty()) return -1; auto iIndexToPlay = 0; for (auto i = 0; i < 5; i++) { iIndexToPlay = RandomInt(m_pSamples.size()); if (iIndexToPlay != m_iIndexLastPlayed) break; } m_iIndexLastPlayed = iIndexToPlay; return iIndexToPlay; } void RandomSample::PlayRandom() { const auto iIndexToPlay = GetNextToPlay(); if (iIndexToPlay == -1) return; m_pSamples[iIndexToPlay]->Play(true); } void RandomSample::PlayCopyOfRandom() { const auto iIndexToPlay = GetNextToPlay(); if (iIndexToPlay == -1) return; m_pSamples[iIndexToPlay]->PlayCopy(true); } void RandomSample::Stop() { if (m_iIndexLastPlayed == -1) // nothing is currently playing return; m_pSamples[m_iIndexLastPlayed]->Stop(); }
20.256
76
0.717615
[ "vector" ]
b4135c24384cf76234a403ded462e2e8c46413a3
19,502
hh
C++
extern/glow-extras/camera/glow-extras/camera/legacy/GenericCamera.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/glow-extras/camera/glow-extras/camera/legacy/GenericCamera.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/glow-extras/camera/glow-extras/camera/legacy/GenericCamera.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <typed-geometry/feature/quat.hh> #include <typed-geometry/tg-lean.hh> #include <glow/math/transform.hh> #include "../CameraBase.hh" /* * What you definitly want to set: * - a position in 3D space (a vec3) * - a viewing direction, this can be defined by: * - roll/pitch/jaw rotations * - up/left/forward vectors * - the aspect ratio (width/height) * * What you maybe want to change: * - a lookAtDistance, this is internaly only used for the orthographic * projection, can be be used externaly e.g. for field of view effects * (if no focal distance is given, a default will be used, but often this * value is not used at all), also a lookAt point can be calculated with this * - Stereo settings: * - the eyedistance * - the StereoMode * - Horizontal/Vertical FoV * - near- and far-clipping plane * * A Camera can calculate: * - a ViewMatrix * - a ProjectionMatrix for Mono view * - ProjectionMatrices for Stereo view * - etc. * * * Note: To get from world to camera space, the translation is applied first, then the * rotation. getViewMatrix() provides one matrix for this. * Other camera models rotate first and translate later (e.g. bundler)! The rotation * is the same, the translation differs. * * TODO: support more stereo modes! */ namespace glow { namespace camera { GLOW_SHARED(class, GenericCamera); class [[deprecated]] GenericCamera : public CameraBase { public: /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Helping enums: // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// use the DX reverse mode with: /// * an infinite far plane /// * a float z-buffer /// * glClearDepth(0.0) /// * glDepthFunc(GL_GREATER) /// * either: /// * glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE) (DX style mapping of the Z values) /// or: /// * glDepthRangedNV(-1.0, 1.0) /// /// this way near will get mapped to 1.0 and infinite to 0.0 enum ProjectionMode { IsometricProjection = 0, PerspectiveProjectionOpenGL, // maps to -1..1 PerspectiveProjectionDXReverse // maps to 1..0 }; enum StereoMode { Mono = 0, ParallelShift, OffAxis, ToeIn }; enum Eye { EyeLeft = 0, EyeRight }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Constructor / Destructor / save&store // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Default Constructor of a camera. */ GenericCamera(); /** * Constructs a camera from a string which holds all camera parameters. Note that this sets the viewport which * might not fit the correct screen! */ GenericCamera(const std::string& _state); /** * Destructor of a camera. */ ~GenericCamera() {} /// Writes all internal state to one string std::string storeStateToString() const; /// Sets all internal state from a string void setStateFromString(const std::string& _state); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Set / Get basic camera properties: // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Set the distance between the pupils (only needed for stereo rendering). * @param _interpupillaryDistance Inter pupil distance in meter(!) (distance between the centers of the eyes) */ void setInterpupillaryDistance(float _interpupillaryDistance) { mInterpupillaryDistance = _interpupillaryDistance; } float getInterpupillaryDistance() const { return mInterpupillaryDistance; } /** * Set the projection mode of the camera. * @param _projection New projection mode of the camera. */ void setProjectionMode(ProjectionMode _projection) { mProjectionMode = _projection; } ProjectionMode getProjectionMode() const { return mProjectionMode; } /** * Set the stereo mode of the camera. In mode MONO the set eye will get ignored (see below). * @param _stereoMode New stereo mode of the camera. */ void setStereoMode(StereoMode _stereoMode) { mStereoMode = _stereoMode; } StereoMode getStereoMode() const { return mStereoMode; } /** * Sets the currently active eye. In stereo mode MONO this setting is ignored. * In the stereo modes (PARALLEL_SHIFT, OFF_AXIS, TOE_IN) it is used to * define the default eye that is assumed for the generic get*Matrix() functions. * (Matrices for specific eyes can still get queried directly without setting the * eye explicitly before each call). */ void setEye(Eye _eye) { mCurrentEye = _eye; } Eye getEye() const { return mCurrentEye; } /** * Set the horizontal field of view of the camera in degree. * vertical FoV will get (implicitly) changed! * @param _fovh New horizontal field of view of the camera. */ void setHorizontalFieldOfView(tg::angle _fovh); tg::angle getHorizontalFieldOfView() const override { return mHorizontalFieldOfView; } /** * Set the vertical field of view of the camera in degree. * Horizontal FoV will get changed! * @param _fovv New vertical field of view of the camera. */ void setVerticalFieldOfView(tg::angle _fovv); tg::angle getVerticalFieldOfView() const override; /** * Set the aspect ratio of the camera. The horizontal FoV stays the same, the * vertical FoV gets updated. * @param aspectRatio New aspect ratio (width/height) */ void setAspectRatio(float _aspectRatio) { mAspectRatio = _aspectRatio; } float getAspectRatio() const { return mAspectRatio; } /** * Set the near clipping plane of the camera. * The plane is defined only by a distance from the camera. * @param _plane New near clipping plane of the camera. */ void setNearClippingPlane(float _plane); /// Gets the near clip distance virtual float getNearClippingPlane() const override { return mNearClippingPlane; } /** * Set the far clipping plane of the camera. * The plane is defined only by a distance from the camera. * This distance might be inf! * @param _plane New far clipping plane of the camera. */ void setFarClippingPlane(float _plane); /// Gets the far clip distance virtual float getFarClippingPlane() const override { return mFarClippingPlane; } /// Gets size of the viewport virtual tg::isize2 getViewportSize() const override { return mViewportSize; } /// Gets width of the viewport unsigned int getViewportWidth() const { return mViewportSize.width; } /// Gets height of the viewport unsigned int getViewportHeight() const { return mViewportSize.height; } /// Sets size of the viewport. NOTE: DOES NOT CHANGE THE ASPECT RATIO! Use resize() if you want to change that as /// well! void setViewportSize(tg::isize2 _size) { mViewportSize = _size; } /// Sets size of the viewport. NOTE: DOES NOT CHANGE THE ASPECT RATIO! Use resize() if you want to change that as /// well! void setViewportSize(unsigned int _width, unsigned int _height) { setViewportSize(tg::isize2(_width, _height)); } /// Sets new viewport size and calculates new aspect ratio void resize(int _newWidth, int _newHeight) { setViewportSize(_newWidth, _newHeight); setAspectRatio(_newWidth / (float)_newHeight); } /// The focal length is coupled to the sensor size in real cameras. As this camera does not model a /// sensor size in mm, the focal length is given in pixels and is in relation to the viewports resolution. /// This model is also used by bundler. /// Note that this gives only useful results if the viewports aspect ratio is the same as the /// projections aspect ratio! float getFocalLenghtInPixel() const; /// Sets the focal length in pixel relative to the viewport dimension. This will change the FoV. /// See getFocalLenghtInPixel() for more information. void setFocalLengthInPixel(float _focalLengthInPixel); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Set / Get the matrices: // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // // Generic view and projection matrices. These obey the set stereo/eye settings. // (When in doubt, use these!) // /// Gets the currently active view matrix (depends on stereo mode and current eye) virtual tg::mat4 getViewMatrix() const override; /// Gets the currently active view matrix (depends on stereo mode and current eye) tg::mat4 getInverseViewMatrix() const; /// Gets the currently active projection matrix (depends on stereo mode and current eye) virtual tg::mat4 getProjectionMatrix() const override; /////////////////////////////////////////////////////////////////////////////////////////// // // Explicit view and projection matrices. These DON'T obey the set stereo/eye settings. // /// Gets the view matrix for non-stereo rendering EVEN IF A STEREO MODE IS SET! tg::mat4 getMonoViewMatrix() const; tg::mat4 getMonoInverseViewMatrix() const; /** * Compute a camera view matrix for stereo rendering. * In stereo mode, the view matrix is the mono view matrix but also the shift * by half the eye distance to the left/right and a small rotation inwards in * case of toe in mode. * * These methods get the stereo matrix independent of the set mode for this camera. */ tg::mat4 getStereoViewMatrix(bool _leftEye, StereoMode _stereoMode = OffAxis) const; tg::mat4 getLeftStereoViewMatrix() const { return getStereoViewMatrix(true, mStereoMode); } tg::mat4 getRightStereoViewMatrix() const { return getStereoViewMatrix(false, mStereoMode); } tg::mat4 getLeftParallelShiftStereoViewMatrix() const { return getStereoViewMatrix(true, ParallelShift); } tg::mat4 getRightParallelShiftStereoViewMatrix() const { return getStereoViewMatrix(false, ParallelShift); } tg::mat4 getLeftOffAxisStereoViewMatrix() const { return getStereoViewMatrix(true, OffAxis); } tg::mat4 getRightOffAxisStereoViewMatrix() const { return getStereoViewMatrix(false, OffAxis); } tg::mat4 getLeftToeInStereoViewMatrix() const { return getStereoViewMatrix(true, ToeIn); } tg::mat4 getRightToeInStereoViewMatrix() const { return getStereoViewMatrix(false, ToeIn); } /// Gets the projection matrix for non-stereo rendering EVEN IF A STEREO MODE IS SET! tg::mat4 getMonoProjectionMatrix() const; /** * Compute a camera projection matrix for stereo rendering. * In stereo mode, the Cameras position is the point in the middle between the two eyes. * So we just need one additional info to calculate two matrices: */ tg::mat4 getStereoProjectionMatrix(bool _leftEye, StereoMode _stereoMode = OffAxis) const; tg::mat4 getLeftStereoProjectionMatrix() const { return getStereoProjectionMatrix(true, mStereoMode); } tg::mat4 getRightStereoProjectionMatrix() const { return getStereoProjectionMatrix(false, mStereoMode); } tg::mat4 getLeftParallelShiftStereoProjectionMatrix() const { return getStereoProjectionMatrix(true, ParallelShift); } tg::mat4 getRightParallelShiftStereoProjectionMatrix() const { return getStereoProjectionMatrix(false, ParallelShift); } tg::mat4 getLeftOffAxisStereoProjectionMatrix() const { return getStereoProjectionMatrix(true, OffAxis); } tg::mat4 getRightOffAxisStereoProjectionMatrix() const { return getStereoProjectionMatrix(false, OffAxis); } tg::mat4 getLeftToeInStereoProjectionMatrix() const { return getStereoProjectionMatrix(true, ToeIn); } tg::mat4 getRightToeInStereoProjectionMatrix() const { return getStereoProjectionMatrix(false, ToeIn); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Set / Get properties that move the camera around (or rotate etc.) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Look around with a mouse, works like a FPS camera: * No roll possible. * Up/down is limited to 90 degree. * This method assumes there is no roll in the current camera rotation, if * there is a roll component, it will get destroyed -> don't mix this * way to stear with other, more flexible methods! * @param _deltaX How much the mouse moved on the viewport (0..1, 1 = full viewport width) * @param _deltaY How much the mouse moved on the viewport (0..1, 1 = full viewport height) */ void FPSstyleLookAround(float _deltaX, float _deltaY); // rotate around the target, x,y,z are angles to rotate by IN RADIANCE // the rotation is around the global goordinate system (1,0,0 / 0,1,0 / 0,0,1) // "turntable style" rotation if _x is set and _y,_z == 0 void rotateAroundTarget_GlobalAxes(tg::angle _x, tg::angle _y, tg::angle _z); // rotate around the current coordinate system void rotateAroundTarget_LocalAxes(tg::angle _x, tg::angle _y, tg::angle _z); /////////////////////////////////////////////////////////////////////////////////////////// // // Generic rotation and translation matrices. // /// Gets the orthonormal rotation matrix (mat3) const tg::mat3& getRotationMatrix3() const { return mRotationMatrix; } /// Gets the inverse orthonormal rotation matrix (mat3) tg::mat3 getInverseRotationMatrix3() const { return tg::transpose(mRotationMatrix); } /// Gets the orthonormal rotation matrix as a mat4 tg::mat4 getRotationMatrix4() const { return tg::mat4(mRotationMatrix); } /// Sets the rotation matrix (mat3) void setRotationMatrix(tg::mat3 _matrix); /// Sets the rotation matrix (mat3-part of a mat4) void setRotationMatrix(tg::mat4 _matrix); /// Sets the complete lookat (position and rotation) void setLookAtMatrix(const tg::pos3& _position, const tg::pos3& _target, const tg::vec3& _up = glow::transform::Up()); /// Gets the translation matrix of this object (no rotational element) tg::mat4 getTranslationMatrix4() const; /////////////////////////////////////////////////////////////////////////////////////////// // // Generic model matrices. // /// Gets the currently active view matrix (depends on stereo mode and current eye) tg::mat4 getModelMatrix() const; /// Gets the currently active view matrix (depends on stereo mode and current eye) tg::mat4 getInverseModelMatrix() const; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Set / Get properties that move the object around (or rotate etc.) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Set the position of the camera. * @param _position New position of the object. */ void setPosition(const tg::pos3& _position) { mPosition = _position; } tg::pos3 getPosition() const override { return mPosition; } /// Moves the object by a given vector (relative to own orientation) void move(const tg::vec3& _vector); void moveRight(float _distance) { move(tg::vec3(_distance, 0, 0)); } void moveBack(float _distance) { move(tg::vec3(0, 0, _distance)); } void moveUp(float _distance) { move(tg::vec3(0, _distance, 0)); } void moveLeft(float _distance) { move(tg::vec3(-_distance, 0, 0)); } void moveForward(float _distance) { move(tg::vec3(0, 0, -_distance)); } void moveDown(float _distance) { move(tg::vec3(0, -_distance, 0)); } /** * Set the distance of the object to the object it's looking at. * Will change the target! * @param _distance New distance of the object this is pointed at. */ void setLookAtDistance(float _distance); /// Gets the look-at distance float getLookAtDistance() const { return mLookAtDistance; } /// Will change the look at distance! /// Will change the rotation! /// Uses stored up-vector as reference /// CAUTION: if you want to set position AND target, ALWAYS set position first! void setTarget(const tg::pos3& _target) { setTarget(_target, getUpDirection()); } /// Will change the look at distance! /// Will change the rotation! /// Uses given up-vector as reference /// CAUTION: if you want to set position AND target, ALWAYS set position first! void setTarget(const tg::pos3& _target, const tg::vec3& _up); /// Gets the reconstructed target tg::pos3 getTarget() const { return mPosition + getForwardDirection() * getLookAtDistance(); } /// Get the unit up direction tg::dir3 getUpDirection() const; /// Get the unit right direction tg::dir3 getRightDirection() const; /// Get the unit forward direction tg::dir3 getForwardDirection() const; /// Returns the world space ray (pos -> dir) for a given mouse position /// Mouse position must be in (0,0) .. (1,1) /// Note that mousePosition (0,0) is top-left (and not bottom-left) void getViewRay(tg::pos2 mousePosition, tg::pos3 * pos, tg::dir3 * dir) const; private: /// /// States: update the storeStateToString() & setStateFromString() functions whenever adding a new state! /// /// Current camera projection mode ProjectionMode mProjectionMode = PerspectiveProjectionOpenGL; /// stereo view mode StereoMode mStereoMode = Mono; /// Current eye Eye mCurrentEye = EyeLeft; /// Current camera horizontal field of view tg::angle mHorizontalFieldOfView = 75_deg; /// Current aspect ratio: width/height. float mAspectRatio = 4.f / 3.f; /// Distance of the eyes for stereo projection. In that case, the left eye is 0.5*InterpupillaryDistance /// shifted to the left of position and the right eye is 0.5*InterpupillaryDistance to the right shifted. /// We assume that 1 unit equals 1 meter. The mean eye distance is 6.5 cm == 0.065 units float mInterpupillaryDistance = 0.064f; // 0.064 m = 6.4 cm - mean human eye distance: 6.47cm (male), 6.23cm (female) /// Current camera near clipping plane float mNearClippingPlane = .1f; // 10cm /// Current camera far clipping plane float mFarClippingPlane = 5000.; // 5000m /// viewport in pixel: tg::isize2 mViewportSize; /// Current position tg::pos3 mPosition; /// Current rotation tg::mat3 mRotationMatrix; /// might be used later to rotate around this position: float mLookAtDistance = 500.0; // helper: void rotateAroundTarget_helper(tg::angle _x, tg::angle _y, tg::angle _z, const tg::mat3& _rotationAxes); }; } }
44.322727
124
0.625269
[ "geometry", "object", "vector", "model", "transform", "3d" ]
b4143de1a74ae378499fe87bd257503490e4409d
8,393
cpp
C++
quantitative_finance/L3/tests/BinomialTree/xf_fintech_binomialtree_exe.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2020-10-27T07:37:10.000Z
2020-10-27T07:37:10.000Z
quantitative_finance/L3/tests/BinomialTree/xf_fintech_binomialtree_exe.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
quantitative_finance/L3/tests/BinomialTree/xf_fintech_binomialtree_exe.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-04-28T05:58:38.000Z
2021-04-28T05:58:38.000Z
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <string.h> #include <chrono> #include <vector> #include "xf_fintech_api.hpp" using namespace xf::fintech; static float tolerance = 0.001; static int check(float actual, float expected, float tol) { int ret = 1; // assume pass if (std::abs(actual - expected) > tol) { printf("ERROR: expected %0.6f, got %0.6f\n", expected, actual); ret = 0; } return ret; } int main(int argc, char** argv) { // binomial tree fintech model... std::string path = std::string(argv[1]); BinomialTree bt(path); std::string device = TOSTRING(DEVICE_PART); if (argc == 3) { device = std::string(argv[2]); } int retval = XLNX_OK; std::chrono::time_point<std::chrono::high_resolution_clock> start; std::chrono::time_point<std::chrono::high_resolution_clock> end; std::vector<Device*> deviceList; Device* pChosenDevice; // device passed in via compile deviceList = DeviceManager::getDeviceList(device); if (deviceList.size() == 0) { printf("No matching devices found\n"); exit(0); } printf("Found %zu matching devices\n", deviceList.size()); // we'll just pick the first device in the... pChosenDevice = deviceList[0]; if (retval == XLNX_OK) { // turn off trace output...turn it on here if you want extra debug output... Trace::setEnabled(true); } printf("\n\n\n"); printf("[XF_FINTECH] BinomialTree trying to claim device...\n"); double stockPrice = 110.0; double strikePrice = 100.0; double timeToMaturity = 1.0; double riskFreeInterest = 0.05; double volatilityOfVolatility = 0.2; double dividendYield = 0.0; int numberNodes = 1024 - 1; // 0 to 1023 if (retval == XLNX_OK) { printf("\n"); printf("\n"); printf("[XF_FINTECH] ==========\n"); printf("[XF_FINTECH] Parameters\n"); printf("[XF_FINTECH] ==========\n"); printf("[XF_FINTECH] stockPrice = %f\n", stockPrice); printf("[XF_FINTECH] strikePrice = %f\n", strikePrice); printf("[XF_FINTECH] timeToMaturity = %f\n", timeToMaturity); printf("[XF_FINTECH] riskFreeInterest = %f\n", riskFreeInterest); printf("[XF_FINTECH] volatilityOfVolatility = %f\n", volatilityOfVolatility); printf("[XF_FINTECH] dividendYield = %f\n", dividendYield); printf("[XF_FINTECH] numberNodes = %d\n", numberNodes); printf("\n"); } start = std::chrono::high_resolution_clock::now(); retval = bt.claimDevice(pChosenDevice); end = std::chrono::high_resolution_clock::now(); if (retval == XLNX_OK) { printf("[XF_FINTECH] Device setup time = %lld microseconds\n", (long long int)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()); } else { printf("[XF_FINTECH] Failed to claim device - error = %d\n", retval); } // quick fix to get pass/fail criteria int ret = 0; // assume pass double expectedPut[] = {2.987749, 3.271813, 3.573721, 3.896820, 4.238249, 4.598072, 4.976364, 5.377398}; double expectedCall[] = {17.66420, 16.97225, 16.29594, 15.63922, 14.99773, 14.37137, 13.76001, 13.16996}; static const int numberOptions = 8; // 64; std::string mode = "hw"; if (std::getenv("XCL_EMULATION_MODE") != nullptr) { mode = std::getenv("XCL_EMULATION_MODE"); } if (mode == "sw_emu" || mode == "hw_emu") { // value of N reduced so tolerance also reduced tolerance = 0.05; } std::cout << "Running in " << mode << " mode" << std::endl; if (retval == XLNX_OK) { printf("[XF_FINTECH] Multiple Options American Put [%d]\n", numberOptions); xf::fintech::BinomialTreeInputDataType<double> inputData[numberOptions]; double outputData[numberOptions]; start = std::chrono::high_resolution_clock::now(); double S = 110; double K = 100; double T = 1; double rf = 0.05; double V = 0.2; double q = 0; // populate some data for (int i = 0; i < numberOptions; i++) { inputData[i].S = S; inputData[i].K = K + i; inputData[i].T = T; inputData[i].rf = rf; inputData[i].V = V; inputData[i].q = q; if (mode == "sw_emu" || mode == "hw_emu") { inputData[i].N = 128; } else { inputData[i].N = 1024; } if (i == 63) { S = 80; K = 85; } else if (i == 127) { S = 32; K = 33; } else if (i == 191) { S = 55; K = 60; } } retval = bt.run(inputData, outputData, xf::fintech::BinomialTreeAmericanPut, numberOptions); end = std::chrono::high_resolution_clock::now(); if (retval == XLNX_OK) { for (int i = 0; i < numberOptions; i++) { printf("[XF_FINTECH] [%02u] OptionPrice = %f\n", i, outputData[i]); if (!check(outputData[i], expectedPut[i], tolerance)) { ret = 1; } } long long int executionTime = (long long int)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count(); printf( "[XF_FINTECH] ExecutionTime = %lld microseconds (average %lld " "microseconds)\n", executionTime, executionTime / numberOptions); } } if (retval == XLNX_OK) { printf("[XF_FINTECH] Multiple Options American Call [%d]\n", numberOptions); xf::fintech::BinomialTreeInputDataType<double> inputData[numberOptions]; double outputData[numberOptions]; start = std::chrono::high_resolution_clock::now(); double S = 110; double K = 100; double T = 1; double rf = 0.05; double V = 0.2; double q = 0; // populate some data for (int i = 0; i < numberOptions; i++) { inputData[i].S = S; inputData[i].K = K + i; inputData[i].T = T; inputData[i].rf = rf; inputData[i].V = V; inputData[i].q = q; if (mode == "sw_emu" || mode == "hw_emu") { inputData[i].N = 128; } else { inputData[i].N = 1024; } if (i == 63) { S = 80; K = 85; } else if (i == 127) { S = 32; K = 33; } else if (i == 191) { S = 55; K = 60; } } retval = bt.run(inputData, outputData, xf::fintech::BinomialTreeAmericanCall, numberOptions); end = std::chrono::high_resolution_clock::now(); if (retval == XLNX_OK) { for (int i = 0; i < numberOptions; i++) { printf("[XF_FINTECH] [%02u] OptionPrice = %f\n", i, outputData[i]); if (!check(outputData[i], expectedCall[i], tolerance)) { ret = 1; } } long long int executionTime = (long long int)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count(); printf( "[XF_FINTECH] ExecutionTime = %lld microseconds (average %lld " "microseconds)\n", executionTime, executionTime / numberOptions); } } printf("[XF_FINTECH] BinomialTree releasing device...\n"); retval = bt.releaseDevice(); if (!ret) { printf("PASS\n"); } else { printf("FAIL\n"); } return ret; }
32.157088
109
0.544859
[ "vector", "model" ]
b4170b426e721c253c4b88b444a021479beb8f90
21,383
cpp
C++
src/utils/hlmv/viewersettings.cpp
hampta/csso-src
82969d43c831e4f199b2a918c6d745bc8a00a31d
[ "Unlicense" ]
3
2021-07-13T21:53:23.000Z
2022-01-07T23:11:14.000Z
src/utils/hlmv/viewersettings.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/utils/hlmv/viewersettings.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
2
2021-07-14T11:03:04.000Z
2021-11-08T08:32:17.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// // // Half-Life Model Viewer (c) 1999 by Mete Ciragan // // file: ViewerSettings.cpp // last modified: May 29 1999, Mete Ciragan // copyright: The programs and associated files contained in this // distribution were developed by Mete Ciragan. The programs // are not in the public domain, but they are freely // distributable without licensing fees. These programs are // provided without guarantee or warrantee expressed or // implied. // // version: 1.2 // // email: mete@swissquake.ch // web: http://www.swissquake.ch/chumbalum-soft/ // #include "ViewerSettings.h" #include "studiomodel.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "windows.h" ViewerSettings g_viewerSettings; ViewerSettings::ViewerSettings() { Q_memset( this, 0, sizeof( *this ) ); } void InitViewerSettings ( const char *subkey ) { ViewerSettings save = g_viewerSettings; memset (&g_viewerSettings, 0, sizeof (ViewerSettings)); // Some values should survive. This is a crappy way to do settings in general. Sigh. { g_viewerSettings.faceposerToolsDriveMouth = save.faceposerToolsDriveMouth; g_viewerSettings.showHidden = save.showHidden; g_viewerSettings.showActivities = save.showActivities; g_viewerSettings.sortSequences = save.sortSequences; g_viewerSettings.guessModelFOV = save.guessModelFOV; } g_viewerSettings.showOrbitCircle = false; g_viewerSettings.allowOrbitYaw = false; g_viewerSettings.guessModelFOV = true; strcpy( g_viewerSettings.registrysubkey, subkey ); g_pStudioModel->m_angles.Init( -90.0f, 0.0f, 0.0f ); g_pStudioModel->m_origin.Init( 0.0f, 0.0f, 50.0f ); g_viewerSettings.renderMode = RM_TEXTURED; g_viewerSettings.fov = 65.0f; g_viewerSettings.enableNormalMapping = true; g_viewerSettings.enableParallaxMapping = false; g_viewerSettings.showNormals = false; g_viewerSettings.showTangentFrame = false; g_viewerSettings.overlayWireframe = false; g_viewerSettings.enableSpecular = true; g_viewerSettings.playSounds = true; g_viewerSettings.enableJiggleBones = true; g_viewerSettings.bgColor[0] = 0.25f; g_viewerSettings.bgColor[1] = 0.25f; g_viewerSettings.bgColor[2] = 0.25f; g_viewerSettings.gColor[0] = 0.85f; g_viewerSettings.gColor[1] = 0.85f; g_viewerSettings.gColor[2] = 0.69f; g_viewerSettings.lColor[0] = 1.0f; g_viewerSettings.lColor[1] = 1.0f; g_viewerSettings.lColor[2] = 1.0f; g_viewerSettings.aColor[0] = 0.3f; g_viewerSettings.aColor[1] = 0.3f; g_viewerSettings.aColor[2] = 0.3f; g_viewerSettings.lightrot[0] = 0.0f; g_viewerSettings.lightrot[1] = 180.0f; g_viewerSettings.lightrot[2] = 0.0f; g_viewerSettings.speedScale = 1.0f; g_viewerSettings.application_mode = 0; g_viewerSettings.thumbnailsize = 128; g_viewerSettings.thumbnailsizeanim = 128; g_viewerSettings.m_iEditAttachment = -1; g_viewerSettings.highlightHitbox = -1; g_viewerSettings.highlightBone = -1; g_viewerSettings.speechapiindex = 0; g_viewerSettings.cclanguageid = 0; // default hlmv settings g_viewerSettings.xpos = 20; g_viewerSettings.ypos = 20; g_viewerSettings.width = 640; g_viewerSettings.height = 700; g_viewerSettings.originAxisLength = 10.0f; } bool RegReadVector( HKEY hKey, const char *szSubKey, Vector& value ) { LONG lResult; // Registry function result code char szBuff[128]; // Temp. buffer DWORD dwType; // Type of key DWORD dwSize; // Size of element data dwSize = sizeof( szBuff ); lResult = RegQueryValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved &dwType, // type buffer (LPBYTE)szBuff, // data buffer &dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; if (sscanf( szBuff, "(%f %f %f)", &value[0], &value[1], &value[2] ) != 3) return false; return true; } bool RegReadQAngle( HKEY hKey, const char *szSubKey, QAngle& value ) { Vector tmp; if (RegReadVector( hKey, szSubKey, tmp )) { value.Init( tmp.x, tmp.y, tmp.z ); return true; } return false; } bool RegReadColor( HKEY hKey, const char *szSubKey, float value[4] ) { LONG lResult; // Registry function result code char szBuff[128]; // Temp. buffer DWORD dwType; // Type of key DWORD dwSize; // Size of element data dwSize = sizeof( szBuff ); lResult = RegQueryValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved &dwType, // type buffer (LPBYTE)szBuff, // data buffer &dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; if (sscanf( szBuff, "(%f %f %f %f)", &value[0], &value[1], &value[2], &value[3] ) != 4) return false; return true; } bool RegWriteVector( HKEY hKey, const char *szSubKey, Vector& value ) { LONG lResult; // Registry function result code char szBuff[128]; // Temp. buffer DWORD dwSize; // Size of element data sprintf( szBuff, "(%f %f %f)", value[0], value[1], value[2] ); dwSize = strlen( szBuff ); lResult = RegSetValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved REG_SZ, // type buffer (LPBYTE)szBuff, // data buffer dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; return true; } bool RegWriteQAngle( HKEY hKey, const char *szSubKey, QAngle& value ) { Vector tmp; tmp.Init( value.x, value.y, value.z ); return RegWriteVector( hKey, szSubKey, tmp ); } bool RegWriteColor( HKEY hKey, const char *szSubKey, float value[4] ) { LONG lResult; // Registry function result code char szBuff[128]; // Temp. buffer DWORD dwSize; // Size of element data sprintf( szBuff, "(%f %f %f %f)", value[0], value[1], value[2], value[3] ); dwSize = strlen( szBuff ); lResult = RegSetValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved REG_SZ, // type buffer (LPBYTE)szBuff, // data buffer dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; return true; } bool RegReadBool( HKEY hKey, const char *szSubKey, bool *value ) { LONG lResult; // Registry function result code DWORD dwType; // Type of key DWORD dwSize; // Size of element data DWORD dwTemp; dwSize = sizeof( dwTemp ); lResult = RegQueryValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved &dwType, // type buffer (LPBYTE)&dwTemp, // data buffer &dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; if (dwType != REG_DWORD) return false; *value = (dwTemp != 0); return true; } bool RegReadInt( HKEY hKey, const char *szSubKey, int *value ) { LONG lResult; // Registry function result code DWORD dwType; // Type of key DWORD dwSize; // Size of element data dwSize = sizeof( DWORD ); lResult = RegQueryValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved &dwType, // type buffer (LPBYTE)value, // data buffer &dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; if (dwType != REG_DWORD) return false; return true; } bool RegWriteInt( HKEY hKey, const char *szSubKey, int value ) { LONG lResult; // Registry function result code DWORD dwSize; // Size of element data dwSize = sizeof( DWORD ); lResult = RegSetValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved REG_DWORD, // type buffer (LPBYTE)&value, // data buffer dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; return true; } bool RegReadFloat( HKEY hKey, const char *szSubKey, float *value ) { LONG lResult; // Registry function result code char szBuff[128]; // Temp. buffer DWORD dwType; // Type of key DWORD dwSize; // Size of element data dwSize = sizeof( szBuff ); lResult = RegQueryValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved &dwType, // type buffer (LPBYTE)szBuff, // data buffer &dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; *value = atof( szBuff ); return true; } bool RegWriteFloat( HKEY hKey, const char *szSubKey, float value ) { LONG lResult; // Registry function result code char szBuff[128]; // Temp. buffer DWORD dwSize; // Size of element data sprintf( szBuff, "%f", value ); dwSize = strlen( szBuff ); lResult = RegSetValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved REG_SZ, // type buffer (LPBYTE)szBuff, // data buffer dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; return true; } bool RegReadString( HKEY hKey, const char *szSubKey, char *string, int size ) { LONG lResult; // Registry function result code DWORD dwType; // Type of key DWORD dwSize; // Size of element data dwSize = size; lResult = RegQueryValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved &dwType, // type buffer (LPBYTE)string, // data buffer &dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; if (dwType != REG_SZ) return false; return true; } bool RegWriteString( HKEY hKey, const char *szSubKey, char *string ) { LONG lResult; // Registry function result code DWORD dwSize; // Size of element data dwSize = strlen( string ); lResult = RegSetValueEx( hKey, // handle to key szSubKey, // value name 0, // reserved REG_SZ, // type buffer (LPBYTE)string, // data buffer dwSize ); // size of data buffer if (lResult != ERROR_SUCCESS) // Failure return false; return true; } LONG RegViewerSettingsKey( const char *filename, PHKEY phKey, LPDWORD lpdwDisposition ) { if (strlen( filename ) == 0) return ERROR_KEY_DELETED; char szFileName[1024]; strcpy( szFileName, filename ); // strip out bogus characters for (char *cp = szFileName; *cp; cp++) { if (*cp == '\\' || *cp == '/' || *cp == ':') *cp = '.'; } char szModelKey[1024]; sprintf( szModelKey, "Software\\Valve\\%s\\%s", g_viewerSettings.registrysubkey, szFileName ); return RegCreateKeyEx( HKEY_CURRENT_USER, // handle of open key szModelKey, // address of name of subkey to open 0, // DWORD ulOptions, // reserved NULL, // Type of value REG_OPTION_NON_VOLATILE, // Store permanently in reg. KEY_ALL_ACCESS, // REGSAM samDesired, // security access mask NULL, phKey, // Key we are creating lpdwDisposition); // Type of creation } LONG RegViewerRootKey( PHKEY phKey, LPDWORD lpdwDisposition ) { char szRootKey[1024]; sprintf( szRootKey, "Software\\Valve\\%s", g_viewerSettings.registrysubkey ); return RegCreateKeyEx( HKEY_CURRENT_USER, // handle of open key szRootKey, // address of name of subkey to open 0, // DWORD ulOptions, // reserved NULL, // Type of value REG_OPTION_NON_VOLATILE, // Store permanently in reg. KEY_ALL_ACCESS, // REGSAM samDesired, // security access mask NULL, phKey, // Key we are creating lpdwDisposition); // Type of creation } bool LoadViewerSettingsInt( char const *keyname, int *value ) { LONG lResult; // Registry function result code DWORD dwDisposition; // Type of key opening event HKEY hModelKey; lResult = RegViewerSettingsKey( "hlfaceposer", &hModelKey, &dwDisposition); if (lResult != ERROR_SUCCESS) // Failure return false; // First time, just set to Valve default if (dwDisposition == REG_CREATED_NEW_KEY) { return false; } *value = 0; RegReadInt( hModelKey, keyname, value ); return true; } bool SaveViewerSettingsInt ( const char *keyname, int value ) { LONG lResult; // Registry function result code DWORD dwDisposition; // Type of key opening event HKEY hModelKey; lResult = RegViewerSettingsKey( "hlfaceposer", &hModelKey, &dwDisposition); if (lResult != ERROR_SUCCESS) // Failure return false; RegWriteInt( hModelKey, keyname, value ); return true; } bool LoadViewerSettings (const char *filename, StudioModel *pModel ) { LONG lResult; // Registry function result code DWORD dwDisposition; // Type of key opening event HKEY hModelKey; if (filename == NULL || pModel == NULL) return false; lResult = RegViewerSettingsKey( filename, &hModelKey, &dwDisposition); if (lResult != ERROR_SUCCESS) // Failure return false; // First time, just set to Valve default if (dwDisposition == REG_CREATED_NEW_KEY) { return false; } RegReadQAngle( hModelKey, "Rot", pModel->m_angles ); RegReadVector( hModelKey, "Trans", pModel->m_origin ); RegReadColor( hModelKey, "bgColor", g_viewerSettings.bgColor ); RegReadColor( hModelKey, "gColor", g_viewerSettings.gColor ); RegReadColor( hModelKey, "lColor", g_viewerSettings.lColor ); RegReadColor( hModelKey, "aColor", g_viewerSettings.aColor ); RegReadQAngle( hModelKey, "lightrot", g_viewerSettings.lightrot ); int iTemp; float flTemp; char szTemp[256]; RegReadString( hModelKey, "sequence", szTemp, sizeof( szTemp ) ); iTemp = pModel->LookupSequence( szTemp ); pModel->SetSequence( iTemp ); RegReadString( hModelKey, "overlaySequence0", szTemp, sizeof( szTemp ) ); iTemp = pModel->LookupSequence( szTemp ); RegReadFloat( hModelKey, "overlayWeight0", &flTemp ); pModel->SetOverlaySequence( 0, iTemp, flTemp ); RegReadString( hModelKey, "overlaySequence1", szTemp, sizeof( szTemp ) ); iTemp = pModel->LookupSequence( szTemp ); RegReadFloat( hModelKey, "overlayWeight1", &flTemp ); pModel->SetOverlaySequence( 1, iTemp, flTemp ); RegReadString( hModelKey, "overlaySequence2", szTemp, sizeof( szTemp ) ); iTemp = pModel->LookupSequence( szTemp ); RegReadFloat( hModelKey, "overlayWeight2", &flTemp ); pModel->SetOverlaySequence( 2, iTemp, flTemp ); RegReadString( hModelKey, "overlaySequence3", szTemp, sizeof( szTemp ) ); iTemp = pModel->LookupSequence( szTemp ); RegReadFloat( hModelKey, "overlayWeight3",&flTemp ); pModel->SetOverlaySequence( 3, iTemp, flTemp ); RegReadFloat( hModelKey, "speedscale", &g_viewerSettings.speedScale ); if (g_viewerSettings.speedScale > 1.0) g_viewerSettings.speedScale = 1.0; RegReadInt( hModelKey, "viewermode", &g_viewerSettings.application_mode ); RegReadInt( hModelKey, "thumbnailsize", &g_viewerSettings.thumbnailsize ); RegReadInt( hModelKey, "thumbnailsizeanim", &g_viewerSettings.thumbnailsizeanim ); if ( g_viewerSettings.thumbnailsize == 0 ) { g_viewerSettings.thumbnailsize = 128; } if ( g_viewerSettings.thumbnailsizeanim == 0 ) { g_viewerSettings.thumbnailsizeanim = 128; } RegReadInt( hModelKey, "speechapiindex", &g_viewerSettings.speechapiindex ); RegReadInt( hModelKey, "cclanguageid", &g_viewerSettings.cclanguageid ); RegReadBool( hModelKey, "showground", &g_viewerSettings.showGround ); RegReadBool( hModelKey, "showbackground", &g_viewerSettings.showBackground ); RegReadBool( hModelKey, "showshadow", &g_viewerSettings.showShadow ); RegReadBool( hModelKey, "showillumpos", &g_viewerSettings.showIllumPosition ); RegReadBool( hModelKey, "enablenormalmapping", &g_viewerSettings.enableNormalMapping ); RegReadBool( hModelKey, "playsounds", &g_viewerSettings.playSounds ); RegReadBool( hModelKey, "showoriginaxis", &g_viewerSettings.showOriginAxis ); RegReadFloat( hModelKey, "originaxislength", &g_viewerSettings.originAxisLength ); char merge_buffer[32]; for ( int i = 0; i < HLMV_MAX_MERGED_MODELS; i++ ) { Q_snprintf( merge_buffer, sizeof( merge_buffer ), "merge%d", i + 1 ); RegReadString( hModelKey, merge_buffer, g_viewerSettings.mergeModelFile[i], sizeof( g_viewerSettings.mergeModelFile[i] ) ); } return true; } bool LoadViewerRootSettings( void ) { LONG lResult; // Registry function result code DWORD dwDisposition; // Type of key opening event HKEY hRootKey; lResult = RegViewerRootKey( &hRootKey, &dwDisposition); if (lResult != ERROR_SUCCESS) // Failure return false; RegReadInt( hRootKey, "renderxpos", &g_viewerSettings.xpos ); RegReadInt( hRootKey, "renderypos", &g_viewerSettings.ypos ); RegReadInt( hRootKey, "renderwidth", &g_viewerSettings.width ); RegReadInt( hRootKey, "renderheight", &g_viewerSettings.height ); RegReadBool( hRootKey, "faceposerToolsDriveMouth", &g_viewerSettings.faceposerToolsDriveMouth ); RegReadBool( hRootKey, "showHidden", &g_viewerSettings.showHidden ); RegReadBool( hRootKey, "showActivities", &g_viewerSettings.showActivities ); RegReadBool( hRootKey, "sortSequences", &g_viewerSettings.sortSequences ); RegReadBool( hRootKey, "guessModelFOV", &g_viewerSettings.guessModelFOV ); return true; } bool SaveViewerSettings (const char *filename, StudioModel *pModel ) { LONG lResult; // Registry function result code DWORD dwDisposition; // Type of key opening event if (filename == NULL || pModel == NULL) return false; HKEY hModelKey; lResult = RegViewerSettingsKey( filename, &hModelKey, &dwDisposition); if (lResult != ERROR_SUCCESS) // Failure return false; MDLCACHE_CRITICAL_SECTION_( g_pMDLCache ); CStudioHdr *hdr = pModel->GetStudioHdr(); if ( !hdr ) return false; RegWriteQAngle( hModelKey, "Rot", pModel->m_angles ); RegWriteVector( hModelKey, "Trans", pModel->m_origin ); RegWriteColor( hModelKey, "bgColor", g_viewerSettings.bgColor ); RegWriteColor( hModelKey, "gColor", g_viewerSettings.gColor ); RegWriteColor( hModelKey, "lColor", g_viewerSettings.lColor ); RegWriteColor( hModelKey, "aColor", g_viewerSettings.aColor ); RegWriteQAngle( hModelKey, "lightrot", g_viewerSettings.lightrot ); RegWriteString( hModelKey, "sequence", hdr->pSeqdesc( pModel->GetSequence() ).pszLabel() ); RegWriteString( hModelKey, "overlaySequence0", hdr->pSeqdesc( pModel->GetOverlaySequence( 0 ) ).pszLabel() ); RegWriteFloat( hModelKey, "overlayWeight0", pModel->GetOverlaySequenceWeight( 0 ) ); RegWriteString( hModelKey, "overlaySequence1", hdr->pSeqdesc( pModel->GetOverlaySequence( 1 ) ).pszLabel() ); RegWriteFloat( hModelKey, "overlayWeight1", pModel->GetOverlaySequenceWeight( 1 ) ); RegWriteString( hModelKey, "overlaySequence2", hdr->pSeqdesc( pModel->GetOverlaySequence( 2 ) ).pszLabel() ); RegWriteFloat( hModelKey, "overlayWeight2", pModel->GetOverlaySequenceWeight( 2 ) ); RegWriteString( hModelKey, "overlaySequence3", hdr->pSeqdesc( pModel->GetOverlaySequence( 3 ) ).pszLabel() ); RegWriteFloat( hModelKey, "overlayWeight3", pModel->GetOverlaySequenceWeight( 3 ) ); RegWriteFloat( hModelKey, "speedscale", g_viewerSettings.speedScale ); RegWriteInt( hModelKey, "viewermode", g_viewerSettings.application_mode ); RegWriteInt( hModelKey, "thumbnailsize", g_viewerSettings.thumbnailsize ); RegWriteInt( hModelKey, "thumbnailsizeanim", g_viewerSettings.thumbnailsizeanim ); RegWriteInt( hModelKey, "speechapiindex", g_viewerSettings.speechapiindex ); RegWriteInt( hModelKey, "cclanguageid", g_viewerSettings.cclanguageid ); RegWriteInt( hModelKey, "showground", g_viewerSettings.showGround ); RegWriteInt( hModelKey, "showbackground", g_viewerSettings.showBackground ); RegWriteInt( hModelKey, "showshadow", g_viewerSettings.showShadow ); RegWriteInt( hModelKey, "showillumpos", g_viewerSettings.showIllumPosition ); RegWriteInt( hModelKey, "enablenormalmapping", g_viewerSettings.enableNormalMapping ); RegWriteInt( hModelKey, "playsounds", g_viewerSettings.playSounds ); RegWriteInt( hModelKey, "showoriginaxis", g_viewerSettings.showOriginAxis ); RegWriteFloat( hModelKey, "originaxislength", g_viewerSettings.originAxisLength ); char merge_buffer[32]; for ( int i = 0; i < HLMV_MAX_MERGED_MODELS; i++ ) { Q_snprintf( merge_buffer, sizeof( merge_buffer ), "merge%d", i + 1 ); RegWriteString( hModelKey, merge_buffer, g_viewerSettings.mergeModelFile[i] ); } return true; } bool SaveViewerRootSettings( void ) { LONG lResult; // Registry function result code DWORD dwDisposition; // Type of key opening event HKEY hRootKey; lResult = RegViewerRootKey( &hRootKey, &dwDisposition); if (lResult != ERROR_SUCCESS) // Failure return false; RegWriteInt( hRootKey, "renderxpos", g_viewerSettings.xpos ); RegWriteInt( hRootKey, "renderypos", g_viewerSettings.ypos ); RegWriteInt( hRootKey, "renderwidth", g_viewerSettings.width ); RegWriteInt( hRootKey, "renderheight", g_viewerSettings.height ); RegWriteInt( hRootKey, "faceposerToolsDriveMouth", g_viewerSettings.faceposerToolsDriveMouth ? 1 : 0 ); RegWriteInt( hRootKey, "showHidden", g_viewerSettings.showHidden ? 1 : 0 ); RegWriteInt( hRootKey, "showActivities", g_viewerSettings.showActivities ? 1 : 0 ); RegWriteInt( hRootKey, "sortSequences", g_viewerSettings.sortSequences ? 1 : 0 ); RegWriteInt( hRootKey, "guessModelFOV", g_viewerSettings.guessModelFOV ? 1 : 0 ); return true; }
29.453168
125
0.698312
[ "vector", "model" ]
b418c5d23b171e85d933b845c67920a067ad17b9
10,233
cc
C++
src/tests/util/test_kdtree.cc
asellappen/atlas
bc8b3376f9b48651726f76db30fc71f598b9a71c
[ "Apache-2.0" ]
3
2021-08-17T03:08:45.000Z
2021-09-09T09:22:54.000Z
src/tests/util/test_kdtree.cc
asellappen/atlas
bc8b3376f9b48651726f76db30fc71f598b9a71c
[ "Apache-2.0" ]
62
2020-10-21T15:27:38.000Z
2022-03-28T12:42:43.000Z
src/tests/util/test_kdtree.cc
JCSDA/atlas
e0b77091009dbc3281796b9e4b9d2a023fe28a5e
[ "Apache-2.0" ]
1
2021-03-10T19:19:08.000Z
2021-03-10T19:19:08.000Z
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include <array> #include <cmath> #include <limits> #include <numeric> #include <vector> #include "atlas/grid.h" #include "atlas/util/KDTree.h" #include "tests/AtlasTestEnvironment.h" using namespace atlas::util; namespace atlas { namespace test { //------------------------------------------------------------------------------------------------ namespace { // helpers template <typename T> std::string to_string( const std::vector<T>& vector ) { std::stringstream s; s << vector; return s.str(); } template <typename T> std::string to_string( const T& v ) { return std::to_string( v ); } class PayloadGenerator { public: class iterator { friend class PayloadGenerator; public: long int operator*() const { return i_; } const iterator& operator++() { ++i_; return *this; } /* // unused iterator operator++( int ) { iterator copy( *this ); ++i_; return copy; }*/ bool operator==( const iterator& other ) const { return i_ == other.i_; } bool operator!=( const iterator& other ) const { return i_ != other.i_; } protected: iterator( long int start ) : i_( start ) {} private: unsigned long i_; }; iterator begin() const { return begin_; } iterator end() const { return end_; } PayloadGenerator( long int end ) : begin_( 0 ), end_( end ) {} template <typename Container, typename Value = typename Container::value_type> void fill( Container& container ) { std::iota( container.begin(), container.end(), Value( *begin_ ) ); } template <typename Value, size_t size> std::array<Value, size> make_array() { std::array<Value, size> array; fill( array ); return array; } private: iterator begin_; iterator end_; }; static double radius() { return util::Earth::radius(); } static Geometry& geometry() { static Geometry _geometry( radius() ); return _geometry; } static PointXYZ make_xyz( const PointLonLat& lonlat ) { return geometry().xyz( lonlat ); } static std::array<double, 7>& test_lon() { static std::array<double, 7> lon = {0., 30., 60., 90., 120., 150., 180.}; return lon; } static std::array<double, 7>& test_lat() { static std::array<double, 7> lat = {90., 60., 30., 0., -30., -60., -90.}; return lat; } static std::array<PointLonLat, 7>& test_lonlat() { static std::array<PointLonLat, 7> lonlat{PointLonLat{0., 90.}, PointLonLat{30., 60.}, PointLonLat{60., 30.}, PointLonLat{90., 0.}, PointLonLat{120., -30.}, PointLonLat{150., -60.}, PointLonLat{180., -90.}}; return lonlat; } static std::array<PointXYZ, 7>& test_xyz() { static std::array<PointXYZ, 7> xyz{make_xyz( PointLonLat{0., 90.} ), make_xyz( PointLonLat{30., 60.} ), make_xyz( PointLonLat{60., 30.} ), make_xyz( PointLonLat{90., 0.} ), make_xyz( PointLonLat{120., -30.} ), make_xyz( PointLonLat{150., -60.} ), make_xyz( PointLonLat{180., -90.} )}; return xyz; } static std::array<idx_t, 7>& test_payloads() { static auto payloads = PayloadGenerator( 7 ).make_array<idx_t, 7>(); EXPECT_EQ( std::distance( payloads.begin(), payloads.end() ), 7 ); return payloads; } void validate( const KDTree<idx_t>& tree ) { EXPECT_NO_THROW( tree.closestPoint( PointLonLat{180., 45.} ) ); // Search 4 nearest neighbours (k=4), sorted by shortest distance auto neighbours = tree.closestPoints( PointLonLat{89.9, 44.9}, 4 ); auto expected_payloads = std::vector<idx_t>{2, 1, 3, 0}; EXPECT_EQ( neighbours.payloads(), expected_payloads ); } static const IndexKDTree& search() { static IndexKDTree kdtree = []() { IndexKDTree kdtree( geometry() ); auto grid = Grid{"O32"}; kdtree.build( grid.lonlat(), PayloadGenerator( grid.size() ) ); return kdtree; }(); return kdtree; } } // namespace //------------------------------------------------------------------------------------------------ CASE( "test kdtree" ) { auto grid = Grid{"O32"}; IndexKDTree search( geometry() ); search.reserve( grid.size() ); idx_t n{0}; for ( auto& point : grid.lonlat() ) { search.insert( point, n++ ); } search.build(); EXPECT_NO_THROW( search.closestPoint( PointLonLat{180., 45.} ) ); // ... // Search 4 nearest neighbours (k=4), sorted by shortest distance auto neighbours = search.closestPoints( PointLonLat{180., 45.}, 4 ).payloads(); auto expected_neighbours = std::vector<idx_t>{760, 842, 759, 761}; EXPECT_EQ( neighbours, expected_neighbours ); } CASE( "test assertion" ) { auto grid = Grid{"O32"}; IndexKDTree search( geometry() ); search.reserve( grid.size() ); idx_t n{0}; for ( auto& point : grid.lonlat() ) { search.insert( point, n++ ); } // Forgot to call search.build() --> assertion thrown when trying to access EXPECT_THROWS_AS( search.closestPoint( PointLonLat{180., 45.} ), eckit::AssertionFailed ); } CASE( "test no assertion" ) { // Like case "test assertion", but without reserving size auto grid = Grid{"O32"}; IndexKDTree search( geometry() ); // No search.reserve() --> build() will not be necessary. idx_t n{0}; for ( auto& point : grid.lonlat() ) { search.insert( point, n++ ); } // search.build() Not required EXPECT_NO_THROW( search.closestPoint( PointLonLat{180., 45.} ) ); } CASE( "test kdtree building with separate lon and lat and payload arrays" ) { IndexKDTree search( geometry() ); search.build( test_lon(), test_lat(), test_payloads() ); validate( search ); } CASE( "test kdtree building with separate lon and lat and raw payload iterators" ) { IndexKDTree search( geometry() ); auto lon = test_lon(); auto lat = test_lat(); auto payloads_ = test_payloads(); search.build( lon.begin(), lon.end(), lat.begin(), lat.end(), payloads_.begin(), payloads_.end() ); validate( search ); } CASE( "test kdtree building with separate PointLonLat and payload containers" ) { IndexKDTree search( geometry() ); search.build( test_lonlat(), test_payloads() ); validate( search ); } CASE( "test kdtree building with separate PointXYZ and payload containers" ) { IndexKDTree search( geometry() ); search.build( test_xyz(), test_payloads() ); validate( search ); } CASE( "test assignment" ) { IndexKDTree search; search = IndexKDTree(); search.build( test_lonlat(), test_payloads() ); validate( search ); } CASE( "test closestPoint" ) { auto neighbour = search().closestPoint( PointLonLat{180., 45.} ).payload(); auto expected_neighbour = 760; EXPECT_EQ( neighbour, expected_neighbour ); } CASE( "test closestPoints" ) { auto neighbours = search().closestPoints( PointLonLat{180., 45.}, 4 ).payloads(); auto expected_neighbours = std::vector<idx_t>{760, 842, 759, 761}; EXPECT_EQ( neighbours, expected_neighbours ); } CASE( "test closestPointsWithinRadius" ) { double km = 1000. * radius() / util::Earth::radius(); auto neighbours = search().closestPointsWithinRadius( PointLonLat{180., 45.}, 500 * km ).payloads(); auto expected_neighbours = std::vector<idx_t>{760, 842, 759, 761, 841, 843, 682}; EXPECT_EQ( neighbours, expected_neighbours ); } CASE( "test compatibility with external eckit KDTree" ) { // External world struct ExternalKDTreeTraits { using Point = Point3; using Payload = size_t; }; using ExternalKDTree = typename eckit::KDTreeMemory<ExternalKDTreeTraits>; auto external_kdtree = std::make_shared<ExternalKDTree>(); // Atlas world IndexKDTree search( external_kdtree, geometry() ); // Construction of tree; could happen in Atlas world or External world separately auto grid = Grid{"O32"}; search.build( grid.lonlat(), PayloadGenerator( grid.size() ) ); // Usage in External world { auto neighbours = external_kdtree->kNearestNeighbours( make_xyz( {180., 45.} ), 4 ); auto payloads = std::vector<ExternalKDTree::Payload>{}; for ( auto& neighbour : neighbours ) { payloads.push_back( neighbour.payload() ); } auto expected_payloads = std::vector<ExternalKDTree::Payload>{760, 842, 759, 761}; EXPECT_EQ( payloads, expected_payloads ); } // Usage in Atlas world { auto payloads = search.closestPoints( PointLonLat{180., 45.}, 4 ).payloads(); auto expected_payloads = std::vector<IndexKDTree::Payload>{760, 842, 759, 761}; EXPECT_EQ( payloads, expected_payloads ); } } CASE( "test IndexKDTree 2D vs 3D" ) { IndexKDTree2D search2d( geometry() ); IndexKDTree3D search3d( geometry() ); search2d.build( test_lonlat(), test_payloads() ); search3d.build( test_lonlat(), test_payloads() ); auto payloads2d = search2d.closestPoints( PointLonLat{89.9, 44.9}, 4 ).payloads(); auto payloads3d = search3d.closestPoints( PointLonLat{89.9, 44.9}, 4 ).payloads(); EXPECT_EQ( payloads2d, ( std::vector<idx_t>{2, 3, 1, 4} ) ); EXPECT_EQ( payloads3d, ( std::vector<idx_t>{2, 1, 3, 0} ) ); // Note that the expected values are different whether 2D search or 3D search is used } //------------------------------------------------------------------------------------------------ } // namespace test } // namespace atlas int main( int argc, char** argv ) { return atlas::test::run( argc, argv ); }
33.009677
118
0.603244
[ "geometry", "vector", "3d" ]
b41977a78a37b1bcf5747c873dfa4a1df7de1502
10,219
cpp
C++
openstudiocore/src/qtwinmigrate/qwinhost.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/qtwinmigrate/qwinhost.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
1
2019-02-04T23:30:45.000Z
2019-02-04T23:30:45.000Z
openstudiocore/src/qtwinmigrate/qwinhost.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) 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 ** 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // Implementation of the QWinHost classes #ifdef QT3_SUPPORT #undef QT3_SUPPORT #endif #include "qwinhost.h" #include <QEvent> #include <qt_windows.h> #if QT_VERSION >= 0x050000 #define QT_WA(unicode, ansi) unicode #endif /*! \class QWinHost qwinhost.h \brief The QWinHost class provides an API to use native Win32 windows in Qt applications. QWinHost exists to provide a QWidget that can act as a parent for any native Win32 control. Since QWinHost is a proper QWidget, it can be used as a toplevel widget (e.g. 0 parent) or as a child of any other QWidget. QWinHost integrates the native control into the Qt user interface, e.g. handles focus switches and laying out. Applications moving to Qt may have custom Win32 controls that will take time to rewrite with Qt. Such applications can use these custom controls as children of QWinHost widgets. This allows the application's user interface to be replaced gradually. When the QWinHost is destroyed, and the Win32 window hasn't been set with setWindow(), the window will also be destroyed. */ /*! Creates an instance of QWinHost. \a parent and \a f are passed on to the QWidget constructor. The widget has by default no background. \warning You cannot change the parent widget of the QWinHost instance after the native window has been created, i.e. do not call QWidget::setParent or move the QWinHost into a different layout. */ QWinHost::QWinHost(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f), wndproc(0),own_hwnd(false), hwnd(0) { setAttribute(Qt::WA_NoBackground); setAttribute(Qt::WA_NoSystemBackground); } /*! Destroys the QWinHost object. If the hosted Win32 window has not been set explicitly using setWindow() the window will be destroyed. */ QWinHost::~QWinHost() { if (wndproc) { #if defined(GWLP_WNDPROC) QT_WA({ SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)wndproc); },{ SetWindowLongPtrA(hwnd, GWLP_WNDPROC, (LONG_PTR)wndproc); }) #else QT_WA({ SetWindowLong(hwnd, GWL_WNDPROC, (LONG)wndproc); },{ SetWindowLongA(hwnd, GWL_WNDPROC, (LONG)wndproc); }) #endif } if (hwnd && own_hwnd) DestroyWindow(hwnd); } /*! Reimplement this virtual function to create and return the native Win32 window. \a parent is the handle to this widget, and \a instance is the handle to the application instance. The returned HWND must be a child of the \a parent HWND. The default implementation returns null. The window returned by a reimplementation of this function is owned by this QWinHost instance and will be destroyed in the destructor. This function is called by the implementation of polish() if no window has been set explicitly using setWindow(). Call polish() to force this function to be called. \sa setWindow() */ HWND QWinHost::createWindow(HWND parent, HINSTANCE instance) { Q_UNUSED(parent); Q_UNUSED(instance); return 0; } /*! Ensures that the window provided a child of this widget, unless it is a WS_OVERLAPPED window. */ void QWinHost::fixParent() { if (!hwnd) return; if (!::IsWindow(hwnd)) { hwnd = 0; return; } if (::GetParent(hwnd) == (HWND)winId()) return; long style = GetWindowLong(hwnd, GWL_STYLE); if (style & WS_OVERLAPPED) return; ::SetParent(hwnd, (HWND)winId()); } /*! Sets the native Win32 window to \a window. If \a window is not a child window of this widget, then it is reparented to become one. If \a window is not a child window (i.e. WS_OVERLAPPED is set), then this function does nothing. The lifetime of the window handle will be managed by Windows, QWinHost does not call DestroyWindow. To verify that the handle is destroyed when expected, handle WM_DESTROY in the window procedure. \sa window(), createWindow() */ void QWinHost::setWindow(HWND window) { if (hwnd && own_hwnd) DestroyWindow(hwnd); hwnd = window; fixParent(); own_hwnd = false; } /*! Returns the handle to the native Win32 window, or null if no window has been set or created yet. \sa setWindow(), createWindow() */ HWND QWinHost::window() const { return hwnd; } void *getWindowProc(QWinHost *host) { return host ? host->wndproc : 0; } LRESULT CALLBACK WinHostProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { QWinHost *widget = qobject_cast<QWinHost*>(QWidget::find((WId)::GetParent(hwnd))); WNDPROC oldproc = (WNDPROC)getWindowProc(widget); if (widget) { switch(msg) { case WM_LBUTTONDOWN: if (::GetFocus() != hwnd && (widget->focusPolicy() & Qt::ClickFocus)) { widget->setFocus(Qt::MouseFocusReason); } break; case WM_SYSKEYDOWN: case WM_SYSKEYUP: QT_WA({ SendMessage((HWND)widget->winId(), msg, wParam, lParam); }, { SendMessageA((HWND)widget->winId(), msg, wParam, lParam); }) break; case WM_KEYDOWN: if (wParam == VK_TAB) { QT_WA({ SendMessage((HWND)widget->winId(), msg, wParam, lParam); }, { SendMessageA((HWND)widget->winId(), msg, wParam, lParam); }) } break; default: break; } } QT_WA({ if (oldproc) return CallWindowProc(oldproc, hwnd, msg, wParam, lParam); return DefWindowProc(hwnd,msg,wParam,lParam); }, { if (oldproc) return CallWindowProcA(oldproc, hwnd, msg, wParam, lParam); return DefWindowProcA(hwnd,msg,wParam,lParam); }) } /*! \reimp */ bool QWinHost::event(QEvent *e) { switch(e->type()) { case QEvent::Polish: if (!hwnd) { hwnd = createWindow((HWND)winId(), qWinAppInst()); fixParent(); own_hwnd = hwnd != 0; } if (hwnd && !wndproc && GetParent(hwnd) == (HWND)winId()) { #if defined(GWLP_WNDPROC) QT_WA({ wndproc = (void*)GetWindowLongPtr(hwnd, GWLP_WNDPROC); SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)WinHostProc); }, { wndproc = (void*)GetWindowLongPtrA(hwnd, GWLP_WNDPROC); SetWindowLongPtrA(hwnd, GWLP_WNDPROC, (LONG_PTR)WinHostProc); }) #else QT_WA({ wndproc = (void*)GetWindowLong(hwnd, GWL_WNDPROC); SetWindowLong(hwnd, GWL_WNDPROC, (LONG)WinHostProc); }, { wndproc = (void*)GetWindowLongA(hwnd, GWL_WNDPROC); SetWindowLongA(hwnd, GWL_WNDPROC, (LONG)WinHostProc); }) #endif LONG style; QT_WA({ style = GetWindowLong(hwnd, GWL_STYLE); }, { style = GetWindowLongA(hwnd, GWL_STYLE); }) if (style & WS_TABSTOP) setFocusPolicy(Qt::FocusPolicy(focusPolicy() | Qt::StrongFocus)); } break; case QEvent::WindowBlocked: if (hwnd) EnableWindow(hwnd, false); break; case QEvent::WindowUnblocked: if (hwnd) EnableWindow(hwnd, true); break; } return QWidget::event(e); } /*! \reimp */ void QWinHost::showEvent(QShowEvent *e) { QWidget::showEvent(e); if (hwnd) SetWindowPos(hwnd, HWND_TOP, 0, 0, width(), height(), SWP_SHOWWINDOW); } /*! \reimp */ void QWinHost::focusInEvent(QFocusEvent *e) { QWidget::focusInEvent(e); if (hwnd) ::SetFocus(hwnd); } /*! \reimp */ void QWinHost::resizeEvent(QResizeEvent *e) { QWidget::resizeEvent(e); if (hwnd) SetWindowPos(hwnd, HWND_TOP, 0, 0, width(), height(), 0); } /*! \reimp */ #if QT_VERSION >= 0x050000 bool QWinHost::nativeEvent(const QByteArray &eventType, void *message, long *result) #else bool QWinHost::winEvent(MSG *msg, long *result) #endif { #if QT_VERSION >= 0x050000 MSG *msg = (MSG *)message; #endif switch (msg->message) { case WM_SETFOCUS: if (hwnd) { ::SetFocus(hwnd); return true; } default: break; } #if QT_VERSION >= 0x050000 return QWidget::nativeEvent(eventType, message, result); #else return QWidget::winEvent(msg, result); #endif }
28.151515
87
0.649966
[ "object" ]
b41a75ef696ee7515847ef011b04e359013b4b9f
17,149
cpp
C++
src/hammer/SearchReplaceDlg.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/hammer/SearchReplaceDlg.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/hammer/SearchReplaceDlg.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "stdafx.h" #include "History.h" #include "GlobalFunctions.h" #include "MapDoc.h" #include "MapWorld.h" #include "SearchReplaceDlg.h" #include "hammer.h" #include "Selection.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> // // Context data for a FindFirstObject/FindNextObject session. // struct FindObject_t { // // Where to look: in the world or in the selection set. // FindReplaceIn_t eFindIn; CMapWorld *pWorld; EnumChildrenPos_t WorldPos; // A position in the world tree for world searches. CUtlVector<CMapClass *> SelectionList; // A copy of the selection list for selection only searches. int nSelectionIndex; // The index into the selection list for iterating the selection list. // // What to look for. // CString strFindText; bool bVisiblesOnly; bool bCaseSensitive; bool bWholeWord; }; CMapClass *FindNextObject(FindObject_t &FindObject); bool FindCheck(CMapClass *pObject, FindObject_t &FindObject); //----------------------------------------------------------------------------- // Purpose: Returns true if the string matches the search criteria, false if not. // Input : pszString - String to check. // FindObject - Search criteria, including string to search for. //----------------------------------------------------------------------------- bool MatchString(const char *pszString, FindObject_t &FindObject) { if (FindObject.bWholeWord) { if (FindObject.bCaseSensitive) { return (!strcmp(pszString, FindObject.strFindText)); } return (!stricmp(pszString, FindObject.strFindText)); } if (FindObject.bCaseSensitive) { return (strstr(pszString, FindObject.strFindText) != NULL); } return (Q_stristr(pszString, FindObject.strFindText) != NULL); } //----------------------------------------------------------------------------- // Purpose: Returns true if the string matches the search criteria, false if not. // Input : pszIn - // pszOut - String to check. // FindObject - Search criteria, including string to search for. //----------------------------------------------------------------------------- bool ReplaceString(char *pszOut, const char *pszIn, FindObject_t &FindObject, const char *pszReplace) { // // Whole matches are simple, just strcpy the replacement string into the out buffer. // if (FindObject.bWholeWord) { if (FindObject.bCaseSensitive && (!strcmp(pszIn, FindObject.strFindText))) { strcpy(pszOut, pszReplace); return true; } if (!stricmp(pszIn, FindObject.strFindText)) { strcpy(pszOut, pszReplace); return true; } } // // Partial matches are a little tougher. // const char *pszStart = NULL; if (FindObject.bCaseSensitive) { pszStart = strstr(pszIn, FindObject.strFindText); } else { pszStart = Q_stristr(pszIn, FindObject.strFindText); } if (pszStart != NULL) { int nOffset = pszStart - pszIn; strncpy(pszOut, pszIn, nOffset); pszOut += nOffset; pszIn += nOffset + strlen(FindObject.strFindText); strcpy(pszOut, pszReplace); pszOut += strlen(pszReplace); strcpy(pszOut, pszIn); return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Begins a Find or Find/Replace operation. //----------------------------------------------------------------------------- CMapClass *FindFirstObject(FindObject_t &FindObject) { CMapClass *pObject = NULL; if (FindObject.eFindIn == FindInWorld) { // Search the entire world. pObject = FindObject.pWorld->GetFirstDescendent(FindObject.WorldPos); } else { // Search the selection only. if (FindObject.SelectionList.Count()) { pObject = FindObject.SelectionList.Element(0); FindObject.nSelectionIndex = 1; } } if (!pObject) { return NULL; } if (FindCheck(pObject, FindObject)) { return pObject; } return FindNextObject(FindObject); } //----------------------------------------------------------------------------- // Purpose: // Input : pObject - //----------------------------------------------------------------------------- CMapClass *FindNextObject(FindObject_t &FindObject) { while (true) { CMapClass *pObject = NULL; if (FindObject.eFindIn == FindInWorld) { // Search the entire world. pObject = FindObject.pWorld->GetNextDescendent(FindObject.WorldPos); } else { // Search the selection only. if (FindObject.nSelectionIndex < FindObject.SelectionList.Count()) { pObject = FindObject.SelectionList.Element(FindObject.nSelectionIndex); FindObject.nSelectionIndex++; } } if ((!pObject) || FindCheck(pObject, FindObject)) { return pObject; } } } //----------------------------------------------------------------------------- // Purpose: // Input : pObject - // FindObject - // Output : Returns true if the object matches the search criteria, false if not. //----------------------------------------------------------------------------- bool FindCheck(CMapClass *pObject, FindObject_t &FindObject) { CMapEntity *pEntity = dynamic_cast <CMapEntity *>(pObject); if (!pEntity) { return false; } if (FindObject.bVisiblesOnly && !pObject->IsVisible()) { return false; } // // Search keyvalues. // for (int i = pEntity->GetFirstKeyValue(); i != pEntity->GetInvalidKeyValue(); i = pEntity->GetNextKeyValue(i)) { const char *pszValue = pEntity->GetKeyValue(i); if (pszValue && MatchString(pszValue, FindObject)) { return true; } } // // Search connections. // int nConnCount = pEntity->Connections_GetCount(); for (int i = 0; i < nConnCount; i++) { CEntityConnection *pConn = pEntity->Connections_Get(i); if (pConn) { if (MatchString(pConn->GetTargetName(), FindObject) || MatchString(pConn->GetParam(), FindObject)) { return true; } } } return false; } //----------------------------------------------------------------------------- // Purpose: // Input : pLastFound - // FindObject - // pszReplaceText - // Output : Returns the number of occurrences of the find text that were replaced. //----------------------------------------------------------------------------- int FindReplace(CMapEntity *pEntity, FindObject_t &FindObject, const char *pszReplace) { int nReplacedCount = 0; // // Replace keyvalues. // for (int i = pEntity->GetFirstKeyValue(); i != pEntity->GetInvalidKeyValue(); i = pEntity->GetNextKeyValue(i)) { const char *pszValue = pEntity->GetKeyValue(i); char szNewValue[MAX_PATH]; if (pszValue && ReplaceString(szNewValue, pszValue, FindObject, pszReplace)) { const char *pszKey = pEntity->GetKey(i); if (pszKey) { pEntity->SetKeyValue(pszKey, szNewValue); nReplacedCount++; } } } // // Replace connections. // int nConnCount = pEntity->Connections_GetCount(); for (int i = 0; i < nConnCount; i++) { CEntityConnection *pConn = pEntity->Connections_Get(i); if (pConn) { char szNewValue[MAX_PATH]; if (ReplaceString(szNewValue, pConn->GetTargetName(), FindObject, pszReplace)) { pConn->SetTargetName(szNewValue); nReplacedCount++; } if (ReplaceString(szNewValue, pConn->GetParam(), FindObject, pszReplace)) { pConn->SetParam(szNewValue); nReplacedCount++; } } } return nReplacedCount; } BEGIN_MESSAGE_MAP(CSearchReplaceDlg, CDialog) //{{AFX_MSG_MAP(CSearchReplaceDlg) ON_WM_SHOWWINDOW() ON_COMMAND_EX(IDC_FIND_NEXT, OnFindReplace) ON_COMMAND_EX(IDC_REPLACE, OnFindReplace) ON_COMMAND_EX(IDC_REPLACE_ALL, OnFindReplace) //}}AFX_MSG_MAP END_MESSAGE_MAP() //----------------------------------------------------------------------------- // Purpose: // Input : pParent - //----------------------------------------------------------------------------- CSearchReplaceDlg::CSearchReplaceDlg(CWnd *pParent) : CDialog(CSearchReplaceDlg::IDD, pParent) { m_bNewSearch = true; //{{AFX_DATA_INIT(CSearchReplaceDlg) m_bVisiblesOnly = FALSE; m_nFindIn = FindInWorld; m_bWholeWord = FALSE; m_bCaseSensitive = FALSE; //}}AFX_DATA_INIT } //----------------------------------------------------------------------------- // Purpose: // Output : Returns TRUE on success, FALSE on failure. //----------------------------------------------------------------------------- BOOL CSearchReplaceDlg::Create(CWnd *pwndParent) { return CDialog::Create(CSearchReplaceDlg::IDD, pwndParent); } //----------------------------------------------------------------------------- // Purpose: // Input : pDX - //----------------------------------------------------------------------------- void CSearchReplaceDlg::DoDataExchange(CDataExchange *pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSearchReplaceDlg) DDX_Check(pDX, IDC_VISIBLES_ONLY, m_bVisiblesOnly); DDX_Check(pDX, IDC_WHOLE_WORD, m_bWholeWord); DDX_Check(pDX, IDC_CASE_SENSITIVE, m_bCaseSensitive); DDX_Text(pDX, IDC_FIND_TEXT, m_strFindText); DDX_Text(pDX, IDC_REPLACE_TEXT, m_strReplaceText); DDX_Radio(pDX, IDC_SELECTION, m_nFindIn); //}}AFX_DATA_MAP } void CSearchReplaceDlg::OnCancel(void) { ShowWindow(SW_HIDE); } //----------------------------------------------------------------------------- // Purpose: Fill out the find criteria from the dialog controls. // Input : FindObject - //----------------------------------------------------------------------------- void CSearchReplaceDlg::GetFindCriteria(FindObject_t &FindObject, CMapDoc *pDoc) { FindObject.pWorld = pDoc->GetMapWorld(); if (m_nFindIn == FindInSelection) { FindObject.eFindIn = FindInSelection; FindObject.SelectionList.RemoveAll(); const CMapObjectList *pSelection = pDoc->GetSelection()->GetList(); for (int i = 0; i < pSelection->Count(); i++) { CMapClass *pObject = pSelection->Element(i); if (pObject->IsGroup()) { // If it's a group, get all the entities in the group. const CMapObjectList *pChildren = pObject->GetChildren(); FOR_EACH_OBJ(*pChildren, pos) { FindObject.SelectionList.AddToTail(pChildren->Element(pos)); } } else { FindObject.SelectionList.AddToTail(pObject); } } } else { FindObject.eFindIn = FindInWorld; } FindObject.strFindText = m_strFindText; FindObject.bVisiblesOnly = (m_bVisiblesOnly == TRUE); FindObject.bWholeWord = (m_bWholeWord == TRUE); FindObject.bCaseSensitive = (m_bCaseSensitive == TRUE); } //----------------------------------------------------------------------------- // Purpose: Called when they hit the Find, the Replace, or the Replace All button. // Input : uCmd - The ID of the button the user hit, IDC_FIND_NEXT or IDC_REPLACE. // Output : Returns TRUE to indicate that the message was handled. //----------------------------------------------------------------------------- BOOL CSearchReplaceDlg::OnFindReplace(UINT uCmd) { CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); if (!pDoc) { return TRUE; } static FindObject_t FindObject; static CMapClass *pLastFound = NULL; static int nReplaceCount = 0; FindObject_t TempFindObject; bool bDone = false; UpdateData(); GetFindCriteria(TempFindObject, pDoc); if (strcmp(TempFindObject.strFindText, FindObject.strFindText) != 0) { m_bNewSearch = true; } do { CMapClass *pObject = NULL; if (m_bNewSearch) { // // New search. Fetch the data from the controls. // UpdateData(); GetFindCriteria(FindObject, pDoc); // // We have to keep track of the last object in the iteration for replacement, // because replacement is done when me advance to the next object. // pLastFound = NULL; nReplaceCount = 0; pObject = FindFirstObject(FindObject); } else { pObject = FindNextObject(FindObject); } // // Replace All is undone as single operation. Mark the undo position the first time // we find a match during a Replace All. // if (m_bNewSearch && (uCmd == IDC_REPLACE_ALL) && pObject) { GetHistory()->MarkUndoPosition(pDoc->GetSelection()->GetList(), "Replace Text"); } // // If we have an object to do the replace on, do the replace. // if (pLastFound && ((uCmd == IDC_REPLACE) || (uCmd == IDC_REPLACE_ALL))) { if (uCmd == IDC_REPLACE) { // Allow for undo each time we do a Replace. GetHistory()->MarkUndoPosition(NULL, "Replace Text"); } // // Do the replace on the last matching object we found. This lets the user see what // object will be modified before it is done. // GetHistory()->Keep(pLastFound); nReplaceCount += FindReplace((CMapEntity *) pLastFound, FindObject, m_strReplaceText); GetDlgItem(IDCANCEL)->SetWindowText("Close"); } if (pObject) { // // We found an object that satisfies our search. // if ((uCmd == IDC_FIND_NEXT) || (uCmd == IDC_REPLACE)) { // // Highlight the match. // pDoc->SelectObject(pObject, scClear | scSelect); pDoc->CenterViewsOnSelection(); } // // Stop after one match unless we are doing a Replace All. // if (uCmd != IDC_REPLACE_ALL) { bDone = true; } m_bNewSearch = false; pLastFound = pObject; } else { // // No more objects in the search set match our criteria. // if ((m_bNewSearch) || (uCmd != IDC_REPLACE_ALL)) { CString str; str.Format("Finished searching for '%s'.", (LPCTSTR) m_strFindText); MessageBox(str, "Find/Replace Text", MB_OK); // TODO: put the old selection back } else if (uCmd == IDC_REPLACE_ALL) { CString str; str.Format("Replaced %d occurrences of the string '%s' with '%s'.", nReplaceCount, (LPCTSTR) m_strFindText, (LPCTSTR) m_strReplaceText); MessageBox(str, "Find/Replace Text", MB_OK); } m_bNewSearch = true; bDone = true; } } while (!bDone); return TRUE; } void CSearchReplaceDlg::OnOK() { } //----------------------------------------------------------------------------- // Purpose: Called any time we are hidden or shown. // Input : bShow - // nStatus - //----------------------------------------------------------------------------- void CSearchReplaceDlg::OnShowWindow(BOOL bShow, UINT nStatus) { if (bShow) { m_bNewSearch = true; GetDlgItem(IDCANCEL)->SetWindowText("Cancel"); m_nFindIn = FindInWorld; CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); if (pDoc) { if (!pDoc->GetSelection()->IsEmpty()) { m_nFindIn = FindInSelection; } } // Populate the controls with the current data. UpdateData(FALSE); } CDialog::OnShowWindow(bShow, nStatus); }
33.170213
119
0.510059
[ "object" ]
b41bd90b9be64529a0fbb4f62d4a2469640c8027
4,961
cpp
C++
src/parser/psisi/BroadcasterInformationTable.cpp
ysan/atpp
46ff6c836778e8cc3f2677d9ab630778253ec796
[ "MIT" ]
4
2021-01-31T02:43:08.000Z
2021-10-06T15:23:29.000Z
src/parser/psisi/BroadcasterInformationTable.cpp
ysan/atpp
46ff6c836778e8cc3f2677d9ab630778253ec796
[ "MIT" ]
1
2020-12-28T17:09:11.000Z
2020-12-28T17:09:11.000Z
src/parser/psisi/BroadcasterInformationTable.cpp
ysan/atpp
46ff6c836778e8cc3f2677d9ab630778253ec796
[ "MIT" ]
1
2019-12-03T03:52:19.000Z
2019-12-03T03:52:19.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include "BroadcasterInformationTable.h" #include "Utils.h" CBroadcasterInformationTable::CBroadcasterInformationTable (void) { mTables.clear(); } CBroadcasterInformationTable::CBroadcasterInformationTable (int fifoNum) :CSectionParser (fifoNum) { mTables.clear(); } CBroadcasterInformationTable::~CBroadcasterInformationTable (void) { clear(); } void CBroadcasterInformationTable::onSectionCompleted (const CSectionInfo *pCompSection) { if (!pCompSection) { return ; } CTable *pTable = new CTable (); if (!parse (pCompSection, pTable)) { delete pTable; pTable = NULL; detachSectionList (pCompSection); return ; } appendTable (pTable); // debug dump if (CUtils::getLogLevel() <= EN_LOG_LEVEL_D) { dumpTable (pTable); } } bool CBroadcasterInformationTable::parse (const CSectionInfo *pCompSection, CTable* pOutTable) { if (!pCompSection || !pOutTable) { return false; } uint8_t *p = NULL; // work CTable* pTable = pOutTable; pTable->header = *(const_cast<CSectionInfo*>(pCompSection)->getHeader()); p = pCompSection->getDataPartAddr(); pTable->reserved_future_use_2 = (*p >> 5) & 0x07; pTable->broadcast_view_propriety = (*p >> 4) & 0x01; pTable->first_descriptors_length = (*p & 0x0f) << 8 | *(p+1); p += BIT_FIX_LEN; int n = (int)pTable->first_descriptors_length; while (n > 0) { CDescriptor desc (p); if (!desc.isValid) { _UTL_LOG_W ("invalid BIT desc"); return false; } pTable->descriptors.push_back (desc); n -= (2 + *(p + 1)); p += (2 + *(p + 1)); } int barodcasterLen = (int) (pTable->header.section_length - SECTION_HEADER_FIX_LEN - SECTION_CRC32_LEN - BIT_FIX_LEN - pTable->first_descriptors_length); if (barodcasterLen <= BIT_BROADCASTER_FIX_LEN) { _UTL_LOG_W ("invalid BIT broadcaster"); return false; } while (barodcasterLen > 0) { CTable::CBroadcaster brd; brd.broadcaster_id = *p; brd.reserved_future_use = (*(p+1) >> 4) & 0x0f; brd.broadcaster_descriptors_length = (*(p+1) & 0xf) << 8 | *(p+2); p += BIT_BROADCASTER_FIX_LEN; int n = (int)brd.broadcaster_descriptors_length; while (n > 0) { CDescriptor desc (p); if (!desc.isValid) { _UTL_LOG_W ("invalid BIT desc2"); return false; } brd.descriptors.push_back (desc); n -= (2 + *(p + 1)); p += (2 + *(p + 1)); } barodcasterLen -= (BIT_BROADCASTER_FIX_LEN + brd.broadcaster_descriptors_length) ; if (barodcasterLen < 0) { _UTL_LOG_W ("invalid BIT broadcaster"); return false; } pTable->broadcasters.push_back (brd); } return true; } void CBroadcasterInformationTable::appendTable (CTable *pTable) { if (!pTable) { return ; } mTables.push_back (pTable); } void CBroadcasterInformationTable::releaseTables (void) { if (mTables.size() == 0) { return; } std::vector<CTable*>::iterator iter = mTables.begin(); for (; iter != mTables.end(); ++ iter) { delete (*iter); (*iter) = NULL; } mTables.clear(); } void CBroadcasterInformationTable::dumpTables (void) { if (mTables.size() == 0) { return; } std::vector<CTable*>::const_iterator iter = mTables.begin(); for (; iter != mTables.end(); ++ iter) { CTable *pTable = *iter; dumpTable (pTable); } } void CBroadcasterInformationTable::dumpTable (const CTable* pTable) const { if (!pTable) { return; } _UTL_LOG_I (__PRETTY_FUNCTION__); pTable->header.dump (); _UTL_LOG_I ("========================================\n"); _UTL_LOG_I ("table_id [0x%02x]\n", pTable->header.table_id); _UTL_LOG_I ("original_network_id [0x%04x]\n", pTable->header.table_id_extension); _UTL_LOG_I ("broadcast_view_propriety [0x%02x]\n", pTable->broadcast_view_propriety); _UTL_LOG_I ("first_descriptors_length [%d]\n", pTable->first_descriptors_length); std::vector<CDescriptor>::const_iterator iter_desc = pTable->descriptors.begin(); for (; iter_desc != pTable->descriptors.end(); ++ iter_desc) { _UTL_LOG_I ("\n-- descriptor --\n"); CDescriptorCommon::dump (iter_desc->tag, *iter_desc); } std::vector<CTable::CBroadcaster>::const_iterator iter_brd = pTable->broadcasters.begin(); for (; iter_brd != pTable->broadcasters.end(); ++ iter_brd) { _UTL_LOG_I ("\n-- broadcaster --\n"); _UTL_LOG_I ("broadcaster_id [0x%02x]\n", iter_brd->broadcaster_id); _UTL_LOG_I ("broadcaster_descriptors_length [%d]\n", iter_brd->broadcaster_descriptors_length); std::vector<CDescriptor>::const_iterator iter_desc = iter_brd->descriptors.begin(); for (; iter_desc != iter_brd->descriptors.end(); ++ iter_desc) { _UTL_LOG_I ("\n-- descriptor --\n"); CDescriptorCommon::dump (iter_desc->tag, *iter_desc); } } _UTL_LOG_I ("\n"); } void CBroadcasterInformationTable::clear (void) { releaseTables (); // detachAllSectionList (); // detachAllSectionList in parser loop asyncDelete (); }
24.681592
154
0.672042
[ "vector" ]
b41f84bcff9b344c93bb3d725decea73559d1af9
4,560
cpp
C++
Raven.CppClient/HttpCache.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-04-24T02:34:53.000Z
2019-08-01T08:22:26.000Z
Raven.CppClient/HttpCache.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
2
2019-03-21T09:00:02.000Z
2021-02-28T23:49:26.000Z
Raven.CppClient/HttpCache.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-03-04T11:58:54.000Z
2021-03-01T00:25:49.000Z
#include "stdafx.h" #include "HttpCache.h" #include <future> namespace ravendb::client::http { HttpCache::ReleaseCacheItem::ReleaseCacheItem(std::shared_ptr<HttpCacheItem> item) : item(item) {} void HttpCache::ReleaseCacheItem::not_modified() { if(item) { item->last_sever_update = std::chrono::steady_clock::now(); } } std::chrono::milliseconds HttpCache::ReleaseCacheItem::get_age() const { if(!item) { #ifdef max #undef max return std::chrono::milliseconds::max(); #else return std::chrono::milliseconds::max(); #endif } return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - item->last_sever_update); } bool HttpCache::ReleaseCacheItem::get_might_have_been_modified() const { return item->generation != item->cache.lock()->generation.load(); } HttpCache::HttpCache(uint64_t max_size) : _max_size(max_size) {} void HttpCache::free_space() { if(_is_free_space_running.test_and_set()) { return; } struct ClearFreeSpaceRunningFlag { HttpCache& _http_cache; ~ClearFreeSpaceRunningFlag() { _http_cache._is_free_space_running.clear(); } } clear_flag{ *this }; auto cleaner_lock = std::lock_guard(_cleaner_mutex); std::size_t size_to_clear{}; std::size_t number_of_cleared_items{ 0 };//for log/debugging uint64_t size_cleared{ 0 }; std::multimap<std::chrono::steady_clock::time_point, decltype(_items)::iterator> items_its{}; { auto gl = std::shared_lock(_global_mutex); if (_items.empty()) { return; } for(auto it = _items.begin(); it != _items.end(); ++it) { items_its.emplace(it->second->last_access, it); size_to_clear += it->second->payload.size() * sizeof(std::string::value_type); } size_to_clear /= 2; } auto gl = std::unique_lock(_global_mutex); const auto start = std::chrono::steady_clock::now(); for(const auto& [timestamp, iterator] : items_its) { if (size_cleared > size_to_clear && std::chrono::duration_cast<std::chrono::minutes>(start - iterator->second->last_sever_update).count() <= 1) { continue; } ++number_of_cleared_items; size_cleared += iterator->second->payload.size() * sizeof(std::string::value_type); _items.erase(iterator); } } std::shared_ptr<HttpCache> HttpCache::create(uint64_t max_size) { auto object = std::shared_ptr<HttpCache>(new HttpCache(max_size)); object->_weak_this = object; return object; } std::size_t HttpCache::get_number_of_items() const { auto lock = std::shared_lock(_global_mutex); return _items.size(); } void HttpCache::set(std::string url, std::string change_vector, std::string result) { if (_total_size += result.size() * sizeof(std::string::value_type) > _max_size) { auto clean = std::async(std::launch::async, [http_cache = _weak_this.lock()]()->void { if (http_cache) { http_cache->free_space(); } }); } auto http_cache_item = std::make_shared<HttpCacheItem>(); http_cache_item->change_vector = std::move(change_vector); http_cache_item->payload = std::move(result); http_cache_item->cache = _weak_this; http_cache_item->generation = generation.load(); { auto gl = std::unique_lock(_global_mutex, std::defer_lock); auto lock = std::scoped_lock(_cleaner_mutex, gl); _items.insert_or_assign(std::move(url), http_cache_item); http_cache_item->last_access = std::chrono::steady_clock::now(); } } void HttpCache::set_not_found(std::string url) { auto http_cache_item = std::make_shared<HttpCacheItem>(); http_cache_item->change_vector = "404 response"; http_cache_item->cache = _weak_this; http_cache_item->generation = generation.load(); { auto gl = std::unique_lock(_global_mutex, std::defer_lock); auto lock = std::scoped_lock(_cleaner_mutex, gl); _items.insert_or_assign(std::move(url), http_cache_item); http_cache_item->last_access = std::chrono::steady_clock::now(); } } HttpCache::ReleaseCacheItem HttpCache::get(const std::string& url, std::optional<std::string>& change_vector_ref, std::optional<std::string>& response_ref) const { { auto lock = std::shared_lock(_global_mutex); if (auto it = _items.find(url); it != _items.end()) { change_vector_ref.emplace(it->second->change_vector); response_ref.emplace(it->second->payload); it->second->last_access = std::chrono::steady_clock::now(); return ReleaseCacheItem(it->second); } } change_vector_ref.reset(); response_ref.reset(); return ReleaseCacheItem({}); } }
25.762712
123
0.695175
[ "object" ]
b4203a372c2a6d993afbcf7c3e31626fa0b8b3e1
21,947
cpp
C++
src/Features/Speedrun/SpeedrunTimer.cpp
Zyntex1/SourceAutoRecord
7e1419183de2b7c9638ad6dc0cbb5701e4a392c0
[ "MIT" ]
2
2021-01-17T00:10:43.000Z
2021-05-31T01:09:42.000Z
src/Features/Speedrun/SpeedrunTimer.cpp
Zyntex1/SourceAutoRecord
7e1419183de2b7c9638ad6dc0cbb5701e4a392c0
[ "MIT" ]
2
2021-01-13T01:18:10.000Z
2021-01-17T00:05:55.000Z
src/Features/Speedrun/SpeedrunTimer.cpp
Zyntex1/SourceAutoRecord
7e1419183de2b7c9638ad6dc0cbb5701e4a392c0
[ "MIT" ]
3
2020-07-13T20:35:23.000Z
2022-01-24T20:02:04.000Z
#include "SpeedrunTimer.hpp" #include <algorithm> #include <cmath> #include <cstdio> #include <cstring> #include <filesystem> #include <string> #include <vector> #ifdef _WIN32 # include <io.h> #endif #include "Event.hpp" #include "Features/Demo/NetworkGhostPlayer.hpp" #include "Features/Hud/Toasts.hpp" #include "Features/NetMessage.hpp" #include "Features/Session.hpp" #include "Features/Stats/Stats.hpp" #include "Features/Timer/PauseTimer.hpp" #include "Modules/Client.hpp" #include "Modules/Engine.hpp" #include "Modules/Server.hpp" #include "Utils.hpp" #define SPEEDRUN_PACKET_TYPE "srtimer" #define SYNC_INTERVAL 60 // Sync every second, just in case enum PacketType { SYNC, START, PAUSE, RESUME, STOP, SPLIT, RESET, }; // TimerAction {{{ enum class TimerAction { NONE, START, RESTART, SPLIT, END, RESET, // The old interface also had Pause and Resume but they were kinda // pointless }; // }}} // TimerInterface {{{ struct TimerInterface { char start[16]; int total; float ipt; TimerAction action; char end[14]; TimerInterface(); }; TimerInterface::TimerInterface() : start("SAR_TIMER_START") , total(0) , ipt(0.0f) , action(TimerAction::NONE) , end("SAR_TIMER_END") { } // }}} // Segment, SplitInfo {{{ struct Segment { std::string name; int ticks; }; struct SplitInfo { std::vector<Segment> segments; std::string name; int ticks; }; // }}} // This really should just be a plain global rather than being // heap-allocated; however, since it was previously heap-allocated, // timers may rely on this for detection, hence we still put it on the // heap for back compat static TimerInterface *g_timerInterface; static struct { bool isRunning; bool isPaused; bool isReset; bool hasSplitLoad; int saved; int base; std::vector<Segment> currentSplit; std::vector<SplitInfo> splits; std::vector<std::string> visitedMaps; std::string lastMap; } g_speedrun; static std::map<std::string, int> g_activeRun; static std::vector<std::map<std::string, int>> g_runs; static void handleCoopPacket(void *data, size_t size); void SpeedrunTimer::Init() { g_timerInterface = new TimerInterface(); SpeedrunTimer::Reset(false); NetMessage::RegisterHandler(SPEEDRUN_PACKET_TYPE, &handleCoopPacket); SpeedrunTimer::InitCategories(); } void SpeedrunTimer::SetIpt(float ipt) { g_timerInterface->ipt = ipt; } // Interface action fuckery {{{ static std::chrono::time_point<std::chrono::steady_clock> g_actionResetTime; static void setTimerAction(TimerAction action) { g_timerInterface->action = action; g_actionResetTime = NOW_STEADY() + std::chrono::milliseconds(50); // Bit of a hack - should be enough time for timers to pick up on it } // }}} // Getting time {{{ // Both Orange and Blue - the tick we synced static int g_coopLastSyncTick; // Orange only - the tick we synced, as reported by the engine static int g_coopLastSyncEngineTick; static void handleCoopPacket(void *data, size_t size) { if (!engine->IsOrange()) return; char *data_ = (char *)data; if (size < 5) return; PacketType t = (PacketType)data_[0]; int tick = *(int *)(data_ + 1); g_coopLastSyncTick = tick; g_coopLastSyncEngineTick = engine->GetTick(); g_timerInterface->total = SpeedrunTimer::GetTotalTicks(); switch (t) { case PacketType::SYNC: break; case PacketType::START: SpeedrunTimer::Start(); break; case PacketType::PAUSE: SpeedrunTimer::Pause(); break; case PacketType::RESUME: SpeedrunTimer::Resume(); break; case PacketType::STOP: SpeedrunTimer::Stop(std::string(data_ + 5, size - 5)); break; case PacketType::SPLIT: if (size < 6) return; SpeedrunTimer::Split(data_[5], std::string(data_ + 6, size - 6)); break; case PacketType::RESET: SpeedrunTimer::Reset(); break; } } static bool g_inDemoLoad = false; ON_EVENT_P(SESSION_START, 1000) { if (engine->demoplayer->IsPlaying()) g_inDemoLoad = true; } ON_EVENT_P(SESSION_START, -1000) { g_inDemoLoad = false; } static int getCurrentTick() { if (engine->IsOrange()) { static int lastEngine; if (session->isRunning) { lastEngine = engine->GetTick(); } int delta = lastEngine - g_coopLastSyncEngineTick; if (delta < 0) delta = 0; return g_coopLastSyncTick + delta; } if (client->GetChallengeStatus() == CMStatus::CHALLENGE) { if (g_inDemoLoad) return 0; // HACKHACK return roundf(server->GetCMTimer() / *engine->interval_per_tick); } return engine->GetTick(); } static void sendCoopPacket(PacketType t, std::string *splitName = NULL, int newSplit = -1) { if (engine->IsOrange()) return; size_t size = 5; if (newSplit != -1) { ++size; } if (splitName) { size += splitName->size(); } char *buf = (char *)malloc(size); buf[0] = (char)t; *(int *)(buf + 1) = getCurrentTick(); char *ptr = buf + 5; if (newSplit != -1) { *(ptr++) = newSplit; } if (splitName) { memcpy(ptr, splitName->c_str(), splitName->size()); } NetMessage::SendMsg(SPEEDRUN_PACKET_TYPE, buf, size); free(buf); } int SpeedrunTimer::GetSegmentTicks() { if (g_speedrun.isReset) { return sar_speedrun_offset.GetInt(); } if (!g_speedrun.isRunning) { return 0; } int ticks = 0; ticks += g_speedrun.saved; if (!g_speedrun.isPaused) { ticks += getCurrentTick() - g_speedrun.base; } if (ticks < 0) { // This can happen for precisely one tick if you // sar_speedrun_start then unpause, because for some dumb // reason, console unpausing makes the engine go back one tick ticks = 0; } return ticks; } int SpeedrunTimer::GetSplitTicks() { int ticks = 0; for (Segment seg : g_speedrun.currentSplit) { ticks += seg.ticks; } ticks += SpeedrunTimer::GetSegmentTicks(); return ticks; } int SpeedrunTimer::GetTotalTicks() { int ticks = 0; for (SplitInfo split : g_speedrun.splits) { ticks += split.ticks; } ticks += SpeedrunTimer::GetSplitTicks(); return ticks; } // }}} static std::string getEffectiveMapName() { std::string map = engine->GetCurrentMapName(); if (map == "") { return "(menu)"; } return map; } void SpeedrunTimer::Update() { if (g_timerInterface->action != TimerAction::NONE && NOW_STEADY() >= g_actionResetTime) { g_timerInterface->action = TimerAction::NONE; } std::string map = getEffectiveMapName(); if (map != g_speedrun.lastMap && SpeedrunTimer::IsRunning() && !engine->IsOrange()) { bool visited = false; for (std::string v : g_speedrun.visitedMaps) { if (map == v) { visited = true; break; } } if (map == "(menu)") { // We're in the menu - we don't want to split here, just // treat it as if we've visited visited = true; } if (!visited) { g_speedrun.visitedMaps.push_back(map); } bool newSplit = !visited || !sar_speedrun_smartsplit.GetBool(); SpeedrunTimer::Split(newSplit, g_speedrun.lastMap); if (newSplit && networkManager.isConnected) { int total = SpeedrunTimer::GetTotalTicks(); int prevTotal = networkManager.splitTicksTotal == -1 ? 0 : networkManager.splitTicksTotal; networkManager.splitTicks = total - prevTotal; networkManager.splitTicksTotal = total; } g_speedrun.hasSplitLoad = true; g_speedrun.lastMap = map; } if (engine->IsCoop() && !engine->IsOrange()) { int tick = getCurrentTick(); if (tick < g_coopLastSyncTick || tick >= g_coopLastSyncTick + SYNC_INTERVAL) { sendCoopPacket(PacketType::SYNC); g_coopLastSyncTick = tick; } } g_timerInterface->total = SpeedrunTimer::GetTotalTicks(); } ON_EVENT(PRE_TICK) { if (!session->isRunning || !pauseTimer->IsActive()) { return; } if (!g_speedrun.isRunning || g_speedrun.isPaused || !sar_speedrun_time_pauses.GetBool()) { return; } if (engine->IsCoop()) { return; } ++g_speedrun.saved; } void SpeedrunTimer::FinishLoad() { if (!g_speedrun.hasSplitLoad && !engine->IsOrange()) { // We went through a load that kept us on the same map; perform // a segment split SpeedrunTimer::Split(false, getEffectiveMapName()); } // Ready for next load g_speedrun.hasSplitLoad = false; } // Timer control {{{ void SpeedrunTimer::Start() { bool wasRunning = g_speedrun.isRunning; SpeedrunTimer::Reset(false); setTimerAction(wasRunning ? TimerAction::RESTART : TimerAction::START); std::string map = getEffectiveMapName(); g_speedrun.isRunning = true; g_speedrun.isReset = false; g_speedrun.base = getCurrentTick(); g_speedrun.saved = sar_speedrun_offset.GetInt(); g_speedrun.lastMap = map; g_speedrun.visitedMaps.push_back(map); sendCoopPacket(PacketType::START); toastHud.AddToast(SPEEDRUN_TOAST_TAG, "Speedrun started!"); } void SpeedrunTimer::Pause() { if (!g_speedrun.isRunning || g_speedrun.isPaused) { return; } // On resume, the base will be replaced, so save the full segment // time so far g_speedrun.saved = SpeedrunTimer::GetSegmentTicks(); g_speedrun.isPaused = true; sendCoopPacket(PacketType::PAUSE); console->Print("Speedrun paused!\n"); } void SpeedrunTimer::Resume() { if (!g_speedrun.isRunning || !g_speedrun.isPaused) { return; } g_speedrun.base = getCurrentTick(); g_speedrun.isPaused = false; sendCoopPacket(PacketType::RESUME); console->Print("Speedrun resumed!\n"); } void SpeedrunTimer::Stop(std::string segName) { if (!g_speedrun.isRunning) { return; } int total = SpeedrunTimer::GetTotalTicks(); stats->Get(0)->statsCounter->IncrementRunFinished(total); SpeedrunTimer::Split(true, segName, false); g_runs.push_back(g_activeRun); setTimerAction(TimerAction::END); g_speedrun.isRunning = false; sendCoopPacket(PacketType::STOP, &segName); if (networkManager.isConnected) { networkManager.NotifySpeedrunFinished(false); } switch (sar_speedrun_autostop.GetInt()) { case 1: EngineDemoRecorder::stop_callback_hook({}); break; case 2: { std::string base = std::string(engine->GetGameDirectory()) + "/" + engine->demorecorder->m_szDemoBaseName; int min_demo_num = engine->demorecorder->autorecordStartNum; int max_demo_num = *engine->demorecorder->m_nDemoNumber; EngineDemoRecorder::stop_callback_hook({}); auto time_str = SpeedrunTimer::Format(total * *engine->interval_per_tick); std::replace(time_str.begin(), time_str.end(), ':', '-'); std::replace(time_str.begin(), time_str.end(), '.', '-'); const char *c_base = base.c_str(); const char *c_time = time_str.c_str(); for (int i = min_demo_num; i <= max_demo_num; ++i) { std::string demo_file = i == 1 ? Utils::ssprintf("%s.dem", c_base) : Utils::ssprintf("%s_%d.dem", c_base, i); std::string new_name = i == 1 ? Utils::ssprintf("%s_%s.dem", c_base, c_time) : Utils::ssprintf("%s_%s_%d.dem", c_base, c_time, i); std::filesystem::rename(demo_file, new_name); } } break; default: break; } } void SpeedrunTimer::Split(bool newSplit, std::string segName, bool requested) { if (!g_speedrun.isRunning) { return; } g_speedrun.currentSplit.push_back(Segment{ segName, SpeedrunTimer::GetSegmentTicks(), }); if (newSplit) { int ticks = 0; for (Segment seg : g_speedrun.currentSplit) { ticks += seg.ticks; } g_speedrun.splits.push_back(SplitInfo{ g_speedrun.currentSplit, segName, ticks, }); g_activeRun[segName] = ticks; g_speedrun.currentSplit.clear(); } g_speedrun.saved = 0; g_speedrun.base = getCurrentTick(); if (requested) { sendCoopPacket(PacketType::SPLIT, &segName, newSplit); } if (newSplit) { setTimerAction(TimerAction::SPLIT); float totalTime = SpeedrunTimer::GetTotalTicks() * *engine->interval_per_tick; float splitTime = g_speedrun.splits.back().ticks * *engine->interval_per_tick; std::string text = Utils::ssprintf("%s\n%s (%s)", segName.c_str(), SpeedrunTimer::Format(totalTime).c_str(), SpeedrunTimer::Format(splitTime).c_str()); toastHud.AddToast(SPEEDRUN_TOAST_TAG, text); } } void SpeedrunTimer::Reset(bool requested) { SpeedrunTimer::ResetCategory(); if (g_speedrun.isRunning) { stats->Get(0)->statsCounter->IncrementReset(SpeedrunTimer::GetTotalTicks()); g_runs.push_back(g_activeRun); } g_activeRun.clear(); g_speedrun.isRunning = false; g_speedrun.isPaused = false; g_speedrun.isReset = true; g_speedrun.hasSplitLoad = false; g_speedrun.saved = 0; g_speedrun.base = 0; g_speedrun.currentSplit.clear(); g_speedrun.splits.clear(); g_speedrun.visitedMaps.clear(); if (networkManager.isConnected) { networkManager.splitTicksTotal = -1; } if (requested) { sendCoopPacket(PacketType::RESET); setTimerAction(TimerAction::RESET); console->Print("Ready for new speedrun!\n"); } } // }}} bool SpeedrunTimer::IsRunning() { return g_speedrun.isRunning; } void SpeedrunTimer::OnLoad() { SpeedrunTimer::TestLoadRules(); if (!sar_speedrun_start_on_load.isRegistered) { return; } if (sar_speedrun_start_on_load.GetInt() == 2) { SpeedrunTimer::Start(); } else if (sar_speedrun_start_on_load.GetInt() == 1 && !SpeedrunTimer::IsRunning()) { SpeedrunTimer::Start(); } } ON_EVENT(SESSION_START) { if (!engine->IsCoop() || (client->GetChallengeStatus() == CMStatus::CHALLENGE && !engine->IsOrange())) { if (!engine->IsOrange()) { SpeedrunTimer::Resume(); } SpeedrunTimer::OnLoad(); } } ON_EVENT(POST_TICK) { if (event.simulating || engine->demoplayer->IsPlaying()) { SpeedrunTimer::TickRules(); } } // Time formatting {{{ std::string SpeedrunTimer::Format(float raw) { char format[32]; auto sec = int(std::floor(raw)); auto ms = int(std::round((raw - sec) * 1000)); if (sec >= 60) { auto min = sec / 60; sec = sec % 60; if (min >= 60) { auto hrs = min / 60; min = min % 60; snprintf(format, sizeof(format), "%i:%02i:%02i.%03i", hrs, min, sec, ms); } else { snprintf(format, sizeof(format), "%i:%02i.%03i", min, sec, ms); } } else { snprintf(format, sizeof(format), "%i.%03i", sec, ms); } return std::string(format); } std::string SpeedrunTimer::SimpleFormat(float raw) { char format[32]; auto sec = int(std::floor(raw)); auto ms = int(std::round((raw - sec) * 1000)); auto min = sec / 60; sec = sec % 60; auto hrs = min / 60; min = min % 60; snprintf(format, sizeof(format), "%i:%02i:%02i.%03i", hrs, min, sec, ms); return std::string(format); } float SpeedrunTimer::UnFormat(std::string &formated_time) { int h, m, s; float ms, total = 0; if (sscanf(formated_time.c_str(), "%d:%d:%d.%f", &h, &m, &s, &ms) >= 2) { total = h * 3600 + m * 60 + s + 0.001 * ms; } return total; } // }}} Variable sar_speedrun_smartsplit("sar_speedrun_smartsplit", "1", "Only split the speedrun timer a maximum of once per map.\n"); Variable sar_speedrun_time_pauses("sar_speedrun_time_pauses", "0", "Include time spent paused in the speedrun timer.\n"); Variable sar_speedrun_stop_in_menu("sar_speedrun_stop_in_menu", "0", "Automatically stop the speedrun timer when the menu is loaded.\n"); Variable sar_speedrun_start_on_load("sar_speedrun_start_on_load", "0", 0, 2, "Automatically start the speedrun timer when a map is loaded. 2 = restart if active.\n"); Variable sar_speedrun_offset("sar_speedrun_offset", "0", 0, "Start speedruns with this many ticks on the timer.\n"); Variable sar_speedrun_autostop("sar_speedrun_autostop", "0", 0, 2, "Automatically stop recording demos when a speedrun finishes. If 2, automatically append the run time to the demo name.\n"); CON_COMMAND(sar_speedrun_start, "sar_speedrun_start - start the speedrun timer\n") { SpeedrunTimer::Start(); } CON_COMMAND(sar_speedrun_stop, "sar_speedrun_start - stop the speedrun timer\n") { SpeedrunTimer::Stop(getEffectiveMapName()); } CON_COMMAND(sar_speedrun_split, "sar_speedrun_split - perform a split on the speedrun timer\n") { SpeedrunTimer::Split(true, getEffectiveMapName()); } CON_COMMAND(sar_speedrun_pause, "sar_speedrun_pause - pause the speedrun timer\n") { SpeedrunTimer::Pause(); } CON_COMMAND(sar_speedrun_resume, "sar_speedrun_resume - resume the speedrun timer\n") { SpeedrunTimer::Resume(); } CON_COMMAND(sar_speedrun_reset, "sar_speedrun_reset - reset the speedrun timer\n") { SpeedrunTimer::Reset(); } CON_COMMAND(sar_speedrun_result, "sar_speedrun_result - print the speedrun result\n") { if (g_speedrun.isReset) { console->Print("No active or completed speedrun!\n"); return; } int total = 0; for (SplitInfo split : g_speedrun.splits) { total += split.ticks; auto ticksStr = SpeedrunTimer::Format(split.ticks * *engine->interval_per_tick); auto totalStr = SpeedrunTimer::Format(total * *engine->interval_per_tick); console->Print("%s - %s (%d) - %s\n", split.name.c_str(), ticksStr.c_str(), split.ticks, totalStr.c_str()); if (split.segments.size() > 1) { total -= split.ticks; for (Segment seg : split.segments) { total += seg.ticks; auto ticksStr = SpeedrunTimer::Format(seg.ticks * *engine->interval_per_tick); auto totalStr = SpeedrunTimer::Format(total * *engine->interval_per_tick); console->Print(" %s - %s (%d) - %s\n", seg.name.c_str(), ticksStr.c_str(), seg.ticks, totalStr.c_str()); } } } if (g_speedrun.isRunning) { console->Print("[current split]\n"); for (Segment seg : g_speedrun.currentSplit) { total += seg.ticks; auto ticksStr = SpeedrunTimer::Format(seg.ticks * *engine->interval_per_tick); auto totalStr = SpeedrunTimer::Format(total * *engine->interval_per_tick); console->Print(" %s - %s (%d) - %s\n", seg.name.c_str(), ticksStr.c_str(), seg.ticks, totalStr.c_str()); } int segTicks = SpeedrunTimer::GetSegmentTicks(); total += segTicks; auto ticksStr = SpeedrunTimer::Format(segTicks * *engine->interval_per_tick); auto totalStr = SpeedrunTimer::Format(total * *engine->interval_per_tick); console->Print(" [current segment] - %s (%d) - %s\n", ticksStr.c_str(), segTicks, totalStr.c_str()); } total = SpeedrunTimer::GetTotalTicks(); console->Print("Total: %d (%s)\n", total, SpeedrunTimer::Format(total * *engine->interval_per_tick).c_str()); } CON_COMMAND(sar_speedrun_export, "sar_speedrun_export <filename> - export the speedrun result to the specified CSV file\n") { if (args.ArgC() != 2) { console->Print(sar_speedrun_export.ThisPtr()->m_pszHelpString); return; } if (g_speedrun.isReset) { console->Print("No active or completed speedrun!\n"); return; } if (g_speedrun.isRunning) { console->Print("Only completed speedruns can be exported!\n"); return; } std::string filename = args[1]; if (filename.length() < 4 || filename.substr(filename.length() - 4, 4) != ".csv") { filename += ".csv"; } FILE *f = fopen(filename.c_str(), "w"); if (!f) { console->Print("Could not open file '%s'\n", filename.c_str()); return; } // I'll give in and do Microsoft's stupid thing only on the platform // where people are probably using Excel. #ifdef _WIN32 fputs(MICROSOFT_PLEASE_FIX_YOUR_SOFTWARE_SMHMYHEAD "\n", f); #endif fputs("Split Name,Ticks,Time,Total Ticks,Total Time\n", f); int total = 0; for (SplitInfo split : g_speedrun.splits) { total += split.ticks; auto fmtdTicks = SpeedrunTimer::Format(split.ticks * *engine->interval_per_tick); auto fmtdTotal = SpeedrunTimer::Format(total * *engine->interval_per_tick); fprintf(f, "%s,%d,%s,%d,%s\n", split.name.c_str(), split.ticks, fmtdTicks.c_str(), total, fmtdTotal.c_str()); } fclose(f); console->Print("Speedrun successfully exported to '%s'!\n", filename.c_str()); } CON_COMMAND(sar_speedrun_export_all, "sar_speedrun_export_all <filename> - export the results of many speedruns to the specified CSV file\n") { // TODO: this kinda isn't good, and should probably be revamped when the // speedrun system is modified to track all splits. if (args.ArgC() != 2) { return console->Print(sar_speedrun_export_all.ThisPtr()->m_pszHelpString); } if (SpeedrunTimer::IsRunning()) { console->Print("Note: incomplete speedruns are not included in the export\n"); } if (g_runs.size() == 0) { return console->Print("No completed runs to export!\n"); } std::vector<std::string> header; for (std::string ruleName : SpeedrunTimer::GetCategoryRules()) { auto rule = SpeedrunTimer::GetRule(ruleName); if (!rule) continue; if (rule->action != RuleAction::SPLIT && rule->action != RuleAction::STOP) continue; header.push_back(ruleName); } std::string filename = args[1]; if (filename.length() < 4 || filename.substr(filename.length() - 4, 4) != ".csv") { filename += ".csv"; } #ifdef _WIN32 bool exists = !_access(filename.c_str(), 0); #else bool exists = !access(filename.c_str(), F_OK); #endif if (exists) { console->Print("File exists; appending data. Warning: if the file is for a different set of splits, the data exported will be incorrect!\n"); } FILE *f = fopen(filename.c_str(), "a"); if (!f) { console->Print("Could not open file '%s'\n", filename.c_str()); return; } // I'll give in and do Microsoft's stupid thing only on the platform // where people are probably using Excel. #ifdef _WIN32 fputs(MICROSOFT_PLEASE_FIX_YOUR_SOFTWARE_SMHMYHEAD "\n", f); #endif if (!exists) { for (size_t i = 0; i < header.size(); ++i) { if (i != 0) fputc(',', f); fputs(header[i].c_str(), f); } fputc('\n', f); } for (auto &run : g_runs) { int total = 0; for (size_t i = 0; i < header.size(); ++i) { if (i != 0) fputc(',', f); auto it = run.find(header[i]); if (it != run.end()) { int ticks = it->second; total += ticks; auto fmtdTicks = SpeedrunTimer::Format(ticks * *engine->interval_per_tick); auto fmtdTotal = SpeedrunTimer::Format(total * *engine->interval_per_tick); fprintf(f, "%s (%s)", fmtdTotal.c_str(), fmtdTicks.c_str()); } } fputc('\n', f); } fclose(f); g_runs.clear(); console->Print("Speedruns successfully exported to '%s'!\n", filename.c_str()); } void SpeedrunTimer::CategoryChanged() { g_runs.clear(); } CON_COMMAND(sar_speedrun_reset_export, "sar_speedrun_reset_export - reset the log of complete and incomplete runs to be exported\n") { g_runs.clear(); }
24.996583
191
0.690573
[ "vector" ]
b42223e8d92a676773ef6d19a8ee7875b0aa8d9a
12,101
cpp
C++
packages/Meshfree/test/tstNearestNeighborOperator.cpp
Rombur/DataTransferKit
5c674720d13b89dd5f23f51285f5c613b6298147
[ "BSD-3-Clause" ]
51
2015-02-03T15:41:00.000Z
2021-11-15T12:35:39.000Z
packages/Meshfree/test/tstNearestNeighborOperator.cpp
Rombur/DataTransferKit
5c674720d13b89dd5f23f51285f5c613b6298147
[ "BSD-3-Clause" ]
552
2015-01-08T22:06:25.000Z
2022-02-01T15:39:40.000Z
packages/Meshfree/test/tstNearestNeighborOperator.cpp
Rombur/DataTransferKit
5c674720d13b89dd5f23f51285f5c613b6298147
[ "BSD-3-Clause" ]
27
2015-02-12T04:59:09.000Z
2020-10-27T16:56:55.000Z
/**************************************************************************** * Copyright (c) 2012-2020 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <Teuchos_UnitTestHarness.hpp> #include <DTK_DBC.hpp> // DataTransferKitException #include <DTK_NearestNeighborOperator.hpp> #include <Kokkos_Core.hpp> #include <array> #include <numeric> #include <random> #include <vector> std::vector<std::array<DataTransferKit::Coordinate, 3>> makeStructuredCloud( DataTransferKit::Coordinate Lx, DataTransferKit::Coordinate Ly, DataTransferKit::Coordinate Lz, int nx, int ny, int nz, DataTransferKit::Coordinate ox = 0., DataTransferKit::Coordinate oy = 0., DataTransferKit::Coordinate oz = 0. ) { std::vector<std::array<DataTransferKit::Coordinate, 3>> cloud( nx * ny * nz ); std::function<int( int, int, int )> ind = [nx, ny]( int i, int j, int k ) { return i + j * nx + k * ( nx * ny ); }; DataTransferKit::Coordinate x, y, z; for ( int i = 0; i < nx; ++i ) for ( int j = 0; j < ny; ++j ) for ( int k = 0; k < nz; ++k ) { x = ox + i * Lx / nx; y = oy + j * Ly / ny; z = oz + k * Lz / nz; cloud[ind( i, j, k )] = {{x, y, z}}; } return cloud; } std::vector<std::array<DataTransferKit::Coordinate, 3>> makeRandomCloud( DataTransferKit::Coordinate Lx, DataTransferKit::Coordinate Ly, DataTransferKit::Coordinate Lz, int n, DataTransferKit::Coordinate seed = 0. ) { std::vector<std::array<DataTransferKit::Coordinate, 3>> cloud( n ); std::default_random_engine generator( seed ); std::uniform_real_distribution<DataTransferKit::Coordinate> distributionx( 0.0, Lx ); std::uniform_real_distribution<DataTransferKit::Coordinate> distributiony( 0.0, Ly ); std::uniform_real_distribution<DataTransferKit::Coordinate> distributionz( 0.0, Lz ); for ( int i = 0; i < n; ++i ) { DataTransferKit::Coordinate x = distributionx( generator ); DataTransferKit::Coordinate y = distributiony( generator ); DataTransferKit::Coordinate z = distributionz( generator ); cloud[i] = {{x, y, z}}; } return cloud; } template <typename DeviceType> void copyPointsFromCloud( std::vector<std::array<DataTransferKit::Coordinate, 3>> const &cloud, Kokkos::View<DataTransferKit::Coordinate **, DeviceType> &points ) { int const n_points = cloud.size(); int const spatial_dim = 3; Kokkos::realloc( points, n_points, spatial_dim ); auto points_host = Kokkos::create_mirror_view( points ); for ( int i = 0; i < n_points; ++i ) for ( int d = 0; d < spatial_dim; ++d ) points_host( i, d ) = cloud[i][d]; Kokkos::deep_copy( points, points_host ); } TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( NearestNeighborOperator, unique_source_point, DeviceType ) { MPI_Comm comm = MPI_COMM_WORLD; int comm_size; MPI_Comm_size( comm, &comm_size ); int comm_rank; MPI_Comm_rank( comm, &comm_rank ); int const space_dim = 3; // Build structured cloud of points for the source and random cloud for the // target. Kokkos::View<DataTransferKit::Coordinate **, DeviceType> source_points( "source", 0, 0 ); Kokkos::View<DataTransferKit::Coordinate **, DeviceType> target_points( "target", 1, space_dim ); if ( comm_rank == 0 ) { Kokkos::resize( source_points, 1, space_dim ); auto source_points_host = Kokkos::create_mirror_view( source_points ); for ( int d = 0; d < space_dim; ++d ) source_points_host( 0, d ) = (double)comm_size; Kokkos::deep_copy( source_points, source_points_host ); } auto target_points_host = Kokkos::create_mirror_view( target_points ); for ( int d = 0; d < space_dim; ++d ) target_points_host( 0, d ) = (double)comm_rank; Kokkos::deep_copy( target_points, target_points_host ); DataTransferKit::NearestNeighborOperator<DeviceType> nnop( comm, source_points, target_points ); Kokkos::View<double *, DeviceType> source_values( "in", 0 ); Kokkos::View<double *, DeviceType> target_values( "out", 0 ); Kokkos::realloc( source_values, source_points.extent( 0 ) ); Kokkos::realloc( target_values, target_points.extent( 0 ) ); if ( comm_rank == 0 ) { auto source_values_host = Kokkos::create_mirror_view( source_values ); source_values_host( 0 ) = 255.; Kokkos::deep_copy( source_values, source_values_host ); } nnop.apply( source_values, target_values ); auto target_values_host = Kokkos::create_mirror_view( target_values ); Kokkos::deep_copy( target_values_host, target_values ); std::vector<double> target_values_ref = {255.}; TEST_COMPARE_ARRAYS( target_values_host, target_values_ref ); } TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( NearestNeighborOperator, structured_clouds, DeviceType ) { // The source is a structured cloud. The target is the same cloud but // distributed differently among the processors. MPI_Comm comm = MPI_COMM_WORLD; int comm_size; MPI_Comm_size( comm, &comm_size ); int comm_rank; MPI_Comm_rank( comm, &comm_rank ); // Build the structured cloud of points for the source and the target. double const Lx = 2.; double const Ly = 3.; double const Lz = 5.; unsigned int const nx = 7; unsigned int const ny = 11; unsigned int const nz = 13; double const source_offset_x = comm_rank * Lx; double const source_offset_y = comm_rank * Ly; double const source_offset_z = comm_rank * Lz; Kokkos::View<DataTransferKit::Coordinate **, DeviceType> source_points( "source_points", 0, 0 ); copyPointsFromCloud<DeviceType>( makeStructuredCloud( Lx, Ly, Lz, nx, ny, nz, source_offset_x, source_offset_y, source_offset_z ), source_points ); double const target_offset_x = ( ( comm_rank + 1 ) % comm_size ) * Lx; double const target_offset_y = ( ( comm_rank + 1 ) % comm_size ) * Ly; double const target_offset_z = ( ( comm_rank + 1 ) % comm_size ) * Lz; Kokkos::View<DataTransferKit::Coordinate **, DeviceType> target_points( "target_points", 0, 0 ); copyPointsFromCloud<DeviceType>( makeStructuredCloud( Lx, Ly, Lz, nx, ny, nz, target_offset_x, target_offset_y, target_offset_z ), target_points ); unsigned int const n_points = source_points.extent( 0 ); Kokkos::View<double *, DeviceType> target_values( "target_values", n_points ); DataTransferKit::NearestNeighborOperator<DeviceType> nnop( comm, source_points, target_points ); Kokkos::View<double *, DeviceType> source_values( "source_values", n_points ); Kokkos::deep_copy( source_values, Kokkos::subview( source_points, Kokkos::ALL, 0 ) ); nnop.apply( source_values, target_values ); // Check results auto target_values_host = Kokkos::create_mirror_view( target_values ); Kokkos::deep_copy( target_values_host, target_values ); auto target_points_host = Kokkos::create_mirror_view( target_points ); Kokkos::deep_copy( target_points_host, target_points ); for ( unsigned int i = 0; i < n_points; ++i ) TEST_FLOATING_EQUALITY( target_values_host( i ), static_cast<double>( target_points_host( i, 0 ) ), 1e-14 ); } TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( NearestNeighborOperator, mixed_clouds, DeviceType ) { // The source is a structured cloud. The target is a random cloud. MPI_Comm comm = MPI_COMM_WORLD; int comm_size; MPI_Comm_size( comm, &comm_size ); int comm_rank; MPI_Comm_rank( comm, &comm_rank ); // Build the structured cloud of points for the source. unsigned int constexpr spacedim = 3; DataTransferKit::Coordinate const Lx = 17.; DataTransferKit::Coordinate const Ly = 19.; DataTransferKit::Coordinate const Lz = 23.; unsigned int const nx = 29; unsigned int const ny = 31; unsigned int const nz = 37; DataTransferKit::Coordinate const source_offset_x = comm_rank * Lx; DataTransferKit::Coordinate const source_offset_y = 0; DataTransferKit::Coordinate const source_offset_z = 0; std::vector<std::array<DataTransferKit::Coordinate, spacedim>> structured_cloud = makeStructuredCloud( Lx, Ly, Lz, nx, ny, nz, source_offset_x, source_offset_y, source_offset_z ); Kokkos::View<DataTransferKit::Coordinate **, DeviceType> source_points( "source_points", 0, 0 ); copyPointsFromCloud<DeviceType>( structured_cloud, source_points ); // Build the random cloud of points for the target. unsigned int const n_target_points = 41; std::vector<std::array<DataTransferKit::Coordinate, spacedim>> random_cloud = makeRandomCloud( comm_size * Lx, Ly, Lz, n_target_points, comm_rank ); Kokkos::View<DataTransferKit::Coordinate **, DeviceType> target_points( "target_points", 0, 0 ); copyPointsFromCloud<DeviceType>( random_cloud, target_points ); Kokkos::View<double *, DeviceType> target_values( "target_values", n_target_points ); DataTransferKit::NearestNeighborOperator<DeviceType> nnop( comm, source_points, target_points ); unsigned int const n_points = source_points.extent( 0 ); Kokkos::View<double *, DeviceType> source_values( "source_values", n_points ); Kokkos::deep_copy( source_values, Kokkos::subview( source_points, Kokkos::ALL, 0 ) ); nnop.apply( source_values, target_values ); // Check results auto target_values_host = Kokkos::create_mirror_view( target_values ); Kokkos::deep_copy( target_values_host, target_values ); for ( unsigned int i = 0; i < n_target_points; ++i ) { double ref_value = round( target_points( i, 0 ) / Lx * nx ) * Lx / nx; if ( ref_value == Lx * comm_size ) ref_value -= Lx / nx; TEST_FLOATING_EQUALITY( target_values_host( i ), ref_value, 1e-14 ); } } // Include the test macros. #include "DataTransferKit_ETIHelperMacros.h" // Create the test group #define UNIT_TEST_GROUP( NODE ) \ using DeviceType##NODE = typename NODE::device_type; \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( \ NearestNeighborOperator, unique_source_point, DeviceType##NODE ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( \ NearestNeighborOperator, structured_clouds, DeviceType##NODE ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( NearestNeighborOperator, \ mixed_clouds, DeviceType##NODE ) // Demangle the types DTK_ETI_MANGLING_TYPEDEFS() // Instantiate the tests DTK_INSTANTIATE_N( UNIT_TEST_GROUP )
41.727586
80
0.610941
[ "vector" ]
b4228e1061cf6abdc83d4df8f979fc825c9e9adb
35,678
cc
C++
chrome/browser/ui/webui/settings/site_settings_helper_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/ui/webui/settings/site_settings_helper_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/ui/webui/settings/site_settings_helper_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2016 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/ui/webui/settings/site_settings_helper.h" #include "base/callback_helpers.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/strings/utf_string_conversions.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/permissions/permission_decision_auto_blocker_factory.h" #include "chrome/browser/usb/usb_chooser_context.h" #include "chrome/browser/usb/usb_chooser_context_factory.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/browser/content_settings_utils.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings_utils.h" #include "components/content_settings/core/common/pref_names.h" #include "components/content_settings/core/test/content_settings_mock_provider.h" #include "components/content_settings/core/test/content_settings_test_utils.h" #include "components/permissions/chooser_context_base.h" #include "components/permissions/permission_decision_auto_blocker.h" #include "components/prefs/pref_service.h" #include "content/public/test/browser_task_environment.h" #include "extensions/browser/extension_registry.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace site_settings { namespace { constexpr ContentSettingsType kContentType = ContentSettingsType::GEOLOCATION; constexpr ContentSettingsType kContentTypeNotifications = ContentSettingsType::NOTIFICATIONS; constexpr ContentSettingsType kContentTypeCookies = ContentSettingsType::COOKIES; } class SiteSettingsHelperTest : public testing::Test { public: void VerifySetting(const base::ListValue& exceptions, int index, const std::string& pattern, const std::string& pattern_display_name, const ContentSetting setting) { const base::DictionaryValue* dict; exceptions.GetDictionary(index, &dict); std::string actual_pattern; dict->GetString("origin", &actual_pattern); EXPECT_EQ(pattern, actual_pattern); std::string actual_display_name; dict->GetString(kDisplayName, &actual_display_name); EXPECT_EQ(pattern_display_name, actual_display_name); std::string actual_setting; dict->GetString(kSetting, &actual_setting); EXPECT_EQ(content_settings::ContentSettingToString(setting), actual_setting); } void AddSetting(HostContentSettingsMap* map, const std::string& pattern, ContentSetting setting) { map->SetContentSettingCustomScope( ContentSettingsPattern::FromString(pattern), ContentSettingsPattern::Wildcard(), kContentType, setting); } private: content::BrowserTaskEnvironment task_environment_; }; TEST_F(SiteSettingsHelperTest, ExceptionListWithEmbargoedAndBlockedOrigins) { TestingProfile profile; constexpr char kOriginToEmbargo[] = "https://embargoed.co.uk:443"; auto* auto_blocker = PermissionDecisionAutoBlockerFactory::GetForProfile(&profile); for (size_t i = 0; i < 3; ++i) { auto_blocker->RecordDismissAndEmbargo(GURL(kOriginToEmbargo), kContentTypeNotifications, false); } constexpr char kOriginToBlock[] = "https://www.blocked.com:443"; auto* map = HostContentSettingsMapFactory::GetForProfile(&profile); map->SetContentSettingDefaultScope(GURL(kOriginToBlock), GURL(kOriginToBlock), kContentTypeNotifications, CONTENT_SETTING_BLOCK); base::ListValue exceptions; site_settings::GetExceptionsForContentType(kContentTypeNotifications, &profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/false, &exceptions); // |exceptions| size should be 2. One blocked and one embargoed origins. ASSERT_EQ(2U, exceptions.GetSize()); base::Value* value = nullptr; // Get last added origin. exceptions.Get(0, &value); base::Value* is_embargoed = value->FindKey(site_settings::kIsEmbargoed); ASSERT_NE(nullptr, is_embargoed); // Last added origin is blocked, |embargo| key should be false. EXPECT_FALSE(is_embargoed->GetBool()); // Get embargoed origin. exceptions.Get(1, &value); is_embargoed = value->FindKey(site_settings::kIsEmbargoed); ASSERT_NE(nullptr, is_embargoed); EXPECT_TRUE(is_embargoed->GetBool()); } TEST_F(SiteSettingsHelperTest, ExceptionListShowsIncognitoEmbargoed) { TestingProfile profile; constexpr char kOriginToBlock[] = "https://www.blocked.com:443"; constexpr char kOriginToEmbargo[] = "https://embargoed.co.uk:443"; constexpr char kOriginToEmbargoIncognito[] = "https://embargoed.incognito.co.uk:443"; // Add an origin under embargo for non incognito profile. { auto* auto_blocker = PermissionDecisionAutoBlockerFactory::GetForProfile(&profile); for (size_t i = 0; i < 3; ++i) { auto_blocker->RecordDismissAndEmbargo(GURL(kOriginToEmbargo), kContentTypeNotifications, false); } // Check that origin is under embargo. ASSERT_EQ(CONTENT_SETTING_BLOCK, auto_blocker ->GetEmbargoResult(GURL(kOriginToEmbargo), kContentTypeNotifications) .content_setting); } // Check there is 1 embargoed origin for a non-incognito profile. { base::ListValue exceptions; site_settings::GetExceptionsForContentType( kContentTypeNotifications, &profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/false, &exceptions); ASSERT_EQ(1U, exceptions.GetSize()); } TestingProfile* incognito_profile = TestingProfile::Builder().BuildIncognito(&profile); // Check there are no blocked origins for an incognito profile. { base::ListValue exceptions; site_settings::GetExceptionsForContentType(kContentTypeNotifications, incognito_profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/true, &exceptions); ASSERT_EQ(0U, exceptions.GetSize()); } { auto* incognito_map = HostContentSettingsMapFactory::GetForProfile(incognito_profile); incognito_map->SetContentSettingDefaultScope( GURL(kOriginToBlock), GURL(kOriginToBlock), kContentTypeNotifications, CONTENT_SETTING_BLOCK); } // Check there is only 1 blocked origin for an incognito profile. { base::ListValue exceptions; site_settings::GetExceptionsForContentType(kContentTypeNotifications, incognito_profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/true, &exceptions); // The exceptions size should be 1 because previously embargoed origin // was for a non-incognito profile. ASSERT_EQ(1U, exceptions.GetSize()); } // Add an origin under embargo for incognito profile. { auto* incognito_auto_blocker = PermissionDecisionAutoBlockerFactory::GetForProfile(incognito_profile); for (size_t i = 0; i < 3; ++i) { incognito_auto_blocker->RecordDismissAndEmbargo( GURL(kOriginToEmbargoIncognito), kContentTypeNotifications, false); } EXPECT_EQ(CONTENT_SETTING_BLOCK, incognito_auto_blocker ->GetEmbargoResult(GURL(kOriginToEmbargoIncognito), kContentTypeNotifications) .content_setting); } // Check there are 2 blocked or embargoed origins for an incognito profile. { base::ListValue exceptions; site_settings::GetExceptionsForContentType(kContentTypeNotifications, incognito_profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/true, &exceptions); ASSERT_EQ(2U, exceptions.GetSize()); } } TEST_F(SiteSettingsHelperTest, ExceptionListShowsEmbargoed) { TestingProfile profile; constexpr char kOriginToBlock[] = "https://www.blocked.com:443"; constexpr char kOriginToEmbargo[] = "https://embargoed.co.uk:443"; // Check there is no blocked origins. { base::ListValue exceptions; site_settings::GetExceptionsForContentType( kContentTypeNotifications, &profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/false, &exceptions); ASSERT_EQ(0U, exceptions.GetSize()); } auto* map = HostContentSettingsMapFactory::GetForProfile(&profile); map->SetContentSettingDefaultScope(GURL(kOriginToBlock), GURL(kOriginToBlock), kContentTypeNotifications, CONTENT_SETTING_BLOCK); { // Check there is 1 blocked origin. base::ListValue exceptions; site_settings::GetExceptionsForContentType( kContentTypeNotifications, &profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/false, &exceptions); ASSERT_EQ(1U, exceptions.GetSize()); } // Add an origin under embargo. auto* auto_blocker = PermissionDecisionAutoBlockerFactory::GetForProfile(&profile); const GURL origin_to_embargo(kOriginToEmbargo); for (size_t i = 0; i < 3; ++i) { auto_blocker->RecordDismissAndEmbargo(origin_to_embargo, kContentTypeNotifications, false); } // Check that origin is under embargo. EXPECT_EQ(CONTENT_SETTING_BLOCK, auto_blocker ->GetEmbargoResult(origin_to_embargo, kContentTypeNotifications) .content_setting); // Check there are 2 blocked origins. { base::ListValue exceptions; site_settings::GetExceptionsForContentType( kContentTypeNotifications, &profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/false, &exceptions); // The size should be 2, 1st is blocked origin, 2nd is embargoed origin. ASSERT_EQ(2U, exceptions.GetSize()); // Fetch and check the first origin. const base::DictionaryValue* dictionary; std::string primary_pattern, display_name; ASSERT_TRUE(exceptions.GetDictionary(0, &dictionary)); ASSERT_TRUE( dictionary->GetString(site_settings::kOrigin, &primary_pattern)); ASSERT_TRUE( dictionary->GetString(site_settings::kDisplayName, &display_name)); EXPECT_EQ(kOriginToBlock, primary_pattern); EXPECT_EQ(kOriginToBlock, display_name); // Fetch and check the second origin. ASSERT_TRUE(exceptions.GetDictionary(1, &dictionary)); ASSERT_TRUE( dictionary->GetString(site_settings::kOrigin, &primary_pattern)); ASSERT_TRUE( dictionary->GetString(site_settings::kDisplayName, &display_name)); EXPECT_EQ(kOriginToEmbargo, primary_pattern); EXPECT_EQ(kOriginToEmbargo, display_name); } { // Non-permission types should not DCHECK when there is autoblocker data // present. base::ListValue exceptions; site_settings::GetExceptionsForContentType( kContentTypeCookies, &profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/false, &exceptions); ASSERT_EQ(0U, exceptions.GetSize()); } } TEST_F(SiteSettingsHelperTest, CheckExceptionOrder) { TestingProfile profile; HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(&profile); base::ListValue exceptions; // Check that the initial state of the map is empty. GetExceptionsForContentType(kContentType, &profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/false, &exceptions); EXPECT_EQ(0u, exceptions.GetSize()); map->SetDefaultContentSetting(kContentType, CONTENT_SETTING_ALLOW); // Add a policy exception. std::string star_google_com = "http://[*.]google.com"; auto policy_provider = std::make_unique<content_settings::MockProvider>(); policy_provider->SetWebsiteSetting( ContentSettingsPattern::FromString(star_google_com), ContentSettingsPattern::Wildcard(), kContentType, std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); policy_provider->set_read_only(true); content_settings::TestUtils::OverrideProvider( map, std::move(policy_provider), HostContentSettingsMap::POLICY_PROVIDER); // Add user preferences. std::string http_star = "http://*"; std::string maps_google_com = "http://maps.google.com"; AddSetting(map, http_star, CONTENT_SETTING_BLOCK); AddSetting(map, maps_google_com, CONTENT_SETTING_BLOCK); AddSetting(map, star_google_com, CONTENT_SETTING_ALLOW); // Add an extension exception. std::string drive_google_com = "http://drive.google.com"; auto extension_provider = std::make_unique<content_settings::MockProvider>(); extension_provider->SetWebsiteSetting( ContentSettingsPattern::FromString(drive_google_com), ContentSettingsPattern::Wildcard(), kContentType, std::make_unique<base::Value>(CONTENT_SETTING_ASK)); extension_provider->set_read_only(true); content_settings::TestUtils::OverrideProvider( map, std::move(extension_provider), HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER); exceptions.Clear(); GetExceptionsForContentType(kContentType, &profile, /*extension_registry=*/nullptr, /*web_ui=*/nullptr, /*incognito=*/false, &exceptions); EXPECT_EQ(5u, exceptions.GetSize()); // The policy exception should be returned first, the extension exception // second and pref exceptions afterwards. // The default content setting should not be returned. int i = 0; // From policy provider: VerifySetting(exceptions, i++, star_google_com, star_google_com, CONTENT_SETTING_BLOCK); // From extension provider: VerifySetting(exceptions, i++, drive_google_com, drive_google_com, CONTENT_SETTING_ASK); // From user preferences: VerifySetting(exceptions, i++, maps_google_com, maps_google_com, CONTENT_SETTING_BLOCK); VerifySetting(exceptions, i++, star_google_com, star_google_com, CONTENT_SETTING_ALLOW); VerifySetting(exceptions, i++, http_star, "http://*", CONTENT_SETTING_BLOCK); } // Tests the following content setting sources: Chrome default, user-set global // default, user-set pattern, user-set origin setting, extension, and policy. TEST_F(SiteSettingsHelperTest, ContentSettingSource) { TestingProfile profile; HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(&profile); GURL origin("https://www.example.com/"); auto* extension_registry = extensions::ExtensionRegistry::Get(&profile); std::string source; std::string display_name; ContentSetting content_setting; // Built in Chrome default. content_setting = GetContentSettingForOrigin(&profile, map, origin, kContentType, &source, extension_registry, &display_name); EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kDefault), source); EXPECT_EQ(CONTENT_SETTING_ASK, content_setting); // User-set global default. map->SetDefaultContentSetting(kContentType, CONTENT_SETTING_ALLOW); content_setting = GetContentSettingForOrigin(&profile, map, origin, kContentType, &source, extension_registry, &display_name); EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kDefault), source); EXPECT_EQ(CONTENT_SETTING_ALLOW, content_setting); // User-set pattern. AddSetting(map, "https://*", CONTENT_SETTING_BLOCK); content_setting = GetContentSettingForOrigin(&profile, map, origin, kContentType, &source, extension_registry, &display_name); EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kPreference), source); EXPECT_EQ(CONTENT_SETTING_BLOCK, content_setting); // User-set origin setting. map->SetContentSettingDefaultScope(origin, origin, kContentType, CONTENT_SETTING_ALLOW); content_setting = GetContentSettingForOrigin(&profile, map, origin, kContentType, &source, extension_registry, &display_name); EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kPreference), source); EXPECT_EQ(CONTENT_SETTING_ALLOW, content_setting); // ChromeOS - DRM disabled. #if BUILDFLAG(IS_CHROMEOS_ASH) profile.GetPrefs()->SetBoolean(prefs::kEnableDRM, false); // Note this is not testing |kContentType|, because this setting is only valid // for protected content. content_setting = GetContentSettingForOrigin( &profile, map, origin, ContentSettingsType::PROTECTED_MEDIA_IDENTIFIER, &source, extension_registry, &display_name); EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kDrmDisabled), source); EXPECT_EQ(CONTENT_SETTING_BLOCK, content_setting); #endif // Extension. auto extension_provider = std::make_unique<content_settings::MockProvider>(); extension_provider->SetWebsiteSetting( ContentSettingsPattern::FromURL(origin), ContentSettingsPattern::FromURL(origin), kContentType, std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); extension_provider->set_read_only(true); content_settings::TestUtils::OverrideProvider( map, std::move(extension_provider), HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER); content_setting = GetContentSettingForOrigin(&profile, map, origin, kContentType, &source, extension_registry, &display_name); EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kExtension), source); EXPECT_EQ(CONTENT_SETTING_BLOCK, content_setting); // Enterprise policy. auto policy_provider = std::make_unique<content_settings::MockProvider>(); policy_provider->SetWebsiteSetting( ContentSettingsPattern::FromURL(origin), ContentSettingsPattern::FromURL(origin), kContentType, std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); policy_provider->set_read_only(true); content_settings::TestUtils::OverrideProvider( map, std::move(policy_provider), HostContentSettingsMap::POLICY_PROVIDER); content_setting = GetContentSettingForOrigin(&profile, map, origin, kContentType, &source, extension_registry, &display_name); EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kPolicy), source); EXPECT_EQ(CONTENT_SETTING_ALLOW, content_setting); // Insecure origins. content_setting = GetContentSettingForOrigin( &profile, map, GURL("http://www.insecure_http_site.com/"), kContentType, &source, extension_registry, &display_name); EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kInsecureOrigin), source); EXPECT_EQ(CONTENT_SETTING_BLOCK, content_setting); } namespace { // Test GURLs // TODO(https://crbug.com/1042727): Fix test GURL scoping and remove this getter // function. GURL GoogleUrl() { return GURL("https://google.com"); } GURL ChromiumUrl() { return GURL("https://chromium.org"); } GURL AndroidUrl() { return GURL("https://android.com"); } GURL TestUrl() { return GURL("https://test.com"); } void ExpectValidChooserExceptionObject( const base::Value& actual_exception_object, const std::string& chooser_type, const std::u16string& display_name, const base::Value& chooser_object) { const base::Value* chooser_type_value = actual_exception_object.FindKeyOfType( kChooserType, base::Value::Type::STRING); ASSERT_TRUE(chooser_type_value); EXPECT_EQ(chooser_type_value->GetString(), chooser_type); const base::Value* display_name_value = actual_exception_object.FindKeyOfType( kDisplayName, base::Value::Type::STRING); ASSERT_TRUE(display_name_value); EXPECT_EQ(base::UTF8ToUTF16(display_name_value->GetString()), display_name); const base::Value* object_value = actual_exception_object.FindKeyOfType( kObject, base::Value::Type::DICTIONARY); ASSERT_TRUE(object_value); EXPECT_EQ(*object_value, chooser_object); const base::Value* sites_value = actual_exception_object.FindKeyOfType(kSites, base::Value::Type::LIST); ASSERT_TRUE(sites_value); } void ExpectValidSiteExceptionObject(const base::Value& actual_site_object, const GURL& origin, const std::string source, bool incognito) { ASSERT_TRUE(actual_site_object.is_dict()); const base::Value* display_name_value = actual_site_object.FindKeyOfType(kDisplayName, base::Value::Type::STRING); ASSERT_TRUE(display_name_value); EXPECT_EQ(display_name_value->GetString(), origin.GetOrigin().spec()); const base::Value* origin_value = actual_site_object.FindKeyOfType(kOrigin, base::Value::Type::STRING); ASSERT_TRUE(origin_value); EXPECT_EQ(origin_value->GetString(), origin.GetOrigin().spec()); const base::Value* setting_value = actual_site_object.FindKeyOfType(kSetting, base::Value::Type::STRING); ASSERT_TRUE(setting_value); EXPECT_EQ(setting_value->GetString(), content_settings::ContentSettingToString(CONTENT_SETTING_DEFAULT)); const base::Value* source_value = actual_site_object.FindKeyOfType(kSource, base::Value::Type::STRING); ASSERT_TRUE(source_value); EXPECT_EQ(source_value->GetString(), source); const base::Value* incognito_value = actual_site_object.FindKeyOfType(kIncognito, base::Value::Type::BOOLEAN); ASSERT_TRUE(incognito_value); EXPECT_EQ(incognito_value->GetBool(), incognito); } } // namespace TEST_F(SiteSettingsHelperTest, CreateChooserExceptionObject) { const std::string kUsbChooserGroupName = ContentSettingsTypeToGroupName(ContentSettingsType::USB_CHOOSER_DATA) .as_string(); const std::string& kPolicySource = SiteSettingSourceToString(SiteSettingSource::kPolicy); const std::string& kPreferenceSource = SiteSettingSourceToString(SiteSettingSource::kPreference); const std::u16string& kObjectName = u"Gadget"; ChooserExceptionDetails exception_details; // Create a chooser object for testing. auto chooser_object = std::make_unique<base::DictionaryValue>(); chooser_object->SetKey("name", base::Value(kObjectName)); // Add a user permission for a requesting origin of |kGoogleOrigin| and an // embedding origin of |kChromiumOrigin|. exception_details[std::make_pair(GoogleUrl().GetOrigin(), kPreferenceSource)] .insert(std::make_pair(ChromiumUrl().GetOrigin(), /*incognito=*/false)); { auto exception = CreateChooserExceptionObject( /*display_name=*/kObjectName, /*object=*/*chooser_object, /*chooser_type=*/kUsbChooserGroupName, /*chooser_exception_details=*/exception_details); ExpectValidChooserExceptionObject( exception, /*chooser_type=*/kUsbChooserGroupName, /*display_name=*/kObjectName, *chooser_object); const auto& sites_list = exception.FindKey(kSites)->GetList(); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[0], /*origin=*/GoogleUrl(), /*source=*/kPreferenceSource, /*incognito=*/false); } // Add a user permissions for a requesting and embedding origin pair of // |kAndroidOrigin| granted in an off the record profile. exception_details[std::make_pair(AndroidUrl().GetOrigin(), kPreferenceSource)] .insert(std::make_pair(AndroidUrl().GetOrigin(), /*incognito=*/true)); { auto exception = CreateChooserExceptionObject( /*display_name=*/kObjectName, /*object=*/*chooser_object, /*chooser_type=*/kUsbChooserGroupName, /*chooser_exception_details=*/exception_details); ExpectValidChooserExceptionObject(exception, /*chooser_type=*/kUsbChooserGroupName, /*display_name=*/kObjectName, *chooser_object); // The map sorts the sites by requesting origin, so |kAndroidOrigin| should // be first, followed by the origin pair (kGoogleOrigin, kChromiumOrigin). const auto& sites_list = exception.FindKey(kSites)->GetList(); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[0], /*origin=*/AndroidUrl(), /*source=*/kPreferenceSource, /*incognito=*/true); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[1], /*origin=*/GoogleUrl(), /*source=*/kPreferenceSource, /*incognito=*/false); } // Add a policy permission for a requesting origin of |kGoogleOrigin| with a // wildcard embedding origin. exception_details[std::make_pair(GoogleUrl().GetOrigin(), kPolicySource)] .insert(std::make_pair(GURL::EmptyGURL(), /*incognito=*/false)); { auto exception = CreateChooserExceptionObject( /*display_name=*/kObjectName, /*object=*/*chooser_object, /*chooser_type=*/kUsbChooserGroupName, /*chooser_exception_details=*/exception_details); ExpectValidChooserExceptionObject(exception, /*chooser_type=*/kUsbChooserGroupName, /*display_name=*/kObjectName, *chooser_object); // The map sorts the sites by requesting origin, but the // CreateChooserExceptionObject method sorts the sites further by the // source. Therefore, policy granted sites are listed before user granted // sites. const auto& sites_list = exception.FindKey(kSites)->GetList(); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[0], /*origin=*/GoogleUrl(), /*source=*/kPolicySource, /*incognito=*/false); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[1], /*origin=*/AndroidUrl(), /*source=*/kPreferenceSource, /*incognito=*/true); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[2], /*origin=*/GoogleUrl(), /*source=*/kPreferenceSource, /*incognito=*/false); } } namespace { constexpr char kUsbPolicySetting[] = R"( [ { "devices": [{ "vendor_id": 6353, "product_id": 5678 }], "urls": ["https://chromium.org"] }, { "devices": [{ "vendor_id": 6353 }], "urls": ["https://google.com,https://android.com"] }, { "devices": [{ "vendor_id": 6354 }], "urls": ["https://android.com,"] }, { "devices": [{}], "urls": ["https://google.com,https://google.com"] } ])"; class SiteSettingsHelperChooserExceptionTest : public testing::Test { protected: Profile* profile() { return &profile_; } void SetUp() override { SetUpUsbChooserContext(); } // Sets up the UsbChooserContext with two devices and permissions for these // devices. It also adds three policy defined permissions. The two devices // represent the two types of USB devices, persistent and ephemeral, that can // be granted permission. void SetUpUsbChooserContext() { device::mojom::UsbDeviceInfoPtr persistent_device_info = device_manager_.CreateAndAddDevice(6353, 5678, "Google", "Gizmo", "123ABC"); device::mojom::UsbDeviceInfoPtr ephemeral_device_info = device_manager_.CreateAndAddDevice(6354, 0, "Google", "Gadget", ""); auto* chooser_context = UsbChooserContextFactory::GetForProfile(profile()); mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager; device_manager_.AddReceiver( device_manager.InitWithNewPipeAndPassReceiver()); chooser_context->SetDeviceManagerForTesting(std::move(device_manager)); chooser_context->GetDevices( base::DoNothing::Once<std::vector<device::mojom::UsbDeviceInfoPtr>>()); base::RunLoop().RunUntilIdle(); const auto kAndroidOrigin = url::Origin::Create(AndroidUrl()); const auto kChromiumOrigin = url::Origin::Create(ChromiumUrl()); const auto kTestOrigin = url::Origin::Create(TestUrl()); // Add the user granted permissions for testing. "Gizmo" is allowed on two // origins, one overlapping with the policy and one distinct. "Gadget" is // allowed on one origin which is overlapping with the policy. chooser_context->GrantDevicePermission(kTestOrigin, *persistent_device_info); chooser_context->GrantDevicePermission(kChromiumOrigin, *persistent_device_info); chooser_context->GrantDevicePermission(kAndroidOrigin, *ephemeral_device_info); // Add the policy granted permissions for testing. auto policy_value = base::JSONReader::ReadDeprecated(kUsbPolicySetting); DCHECK(policy_value); profile()->GetPrefs()->Set(prefs::kManagedWebUsbAllowDevicesForUrls, *policy_value); } device::FakeUsbDeviceManager device_manager_; private: content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; }; void ExpectDisplayNameEq(const base::Value& actual_exception_object, const std::string& display_name) { const std::string* actual_display_name = actual_exception_object.FindStringKey(kDisplayName); ASSERT_TRUE(actual_display_name); EXPECT_EQ(*actual_display_name, display_name); } } // namespace TEST_F(SiteSettingsHelperChooserExceptionTest, GetChooserExceptionListFromProfile) { const std::string kUsbChooserGroupName = ContentSettingsTypeToGroupName(ContentSettingsType::USB_CHOOSER_DATA) .as_string(); const ChooserTypeNameEntry* chooser_type = ChooserTypeFromGroupName(kUsbChooserGroupName); const std::string& kPolicySource = SiteSettingSourceToString(SiteSettingSource::kPolicy); const std::string& kPreferenceSource = SiteSettingSourceToString(SiteSettingSource::kPreference); // The chooser exceptions are ordered by display name. Their corresponding // sites are ordered by permission source precedence, then by the requesting // origin and the embedding origin. User granted permissions that are also // granted by policy are combined with the policy so that duplicate // permissions are not displayed. base::Value exceptions = GetChooserExceptionListFromProfile(profile(), *chooser_type); base::Value::ConstListView exceptions_list = exceptions.GetList(); ASSERT_EQ(exceptions_list.size(), 4u); // This exception should describe the permissions for any device with the // vendor ID corresponding to "Google Inc.". There are no user granted // permissions that intersect with this permission, and this policy only // grants one permission to the "https://android.com" origin. { const auto& exception = exceptions_list[0]; ExpectDisplayNameEq(exception, /*display_name=*/"Devices from Google Inc."); const auto& sites_list = exception.FindKey(kSites)->GetList(); ASSERT_EQ(sites_list.size(), 1u); ExpectValidSiteExceptionObject(sites_list[0], /*origin=*/AndroidUrl(), /*source=*/kPolicySource, /*incognito=*/false); } // This exception should describe the permissions for any device. // There are no user granted permissions that intersect with this permission, // and this policy only grants one permission to the following site: // "https://google.com". { const auto& exception = exceptions_list[1]; ExpectDisplayNameEq(exception, /*display_name=*/"Devices from any vendor"); const auto& sites_list = exception.FindKey(kSites)->GetList(); ASSERT_EQ(sites_list.size(), 1u); ExpectValidSiteExceptionObject(sites_list[0], /*origin=*/GoogleUrl(), /*source=*/kPolicySource, /*incognito=*/false); } // This exception should describe the permissions for any device with the // vendor ID 6354. There is a user granted permission for a device with that // vendor ID, so the site list for this exception will only have the policy // granted permission, which is the following: "https://android.com" { const auto& exception = exceptions_list[2]; ExpectDisplayNameEq(exception, /*display_name=*/"Devices from vendor 0x18D2"); const auto& sites_list = exception.FindKey(kSites)->GetList(); ASSERT_EQ(sites_list.size(), 1u); ExpectValidSiteExceptionObject(sites_list[0], /*origin=*/AndroidUrl(), /*source=*/kPolicySource, /*incognito=*/false); } // This exception should describe the permissions for the "Gizmo" device. // The user granted permissions are the following: // * "https://chromium.org" // * "https://test.org" // The policy granted permission is the following: // * "https://chromium.org" // The chromium granted permission should be coalesced into the policy // permissions. The test one does not overlap with any policy permission so // it will be a separate preference-sourced exception. { const auto& exception = exceptions_list[3]; ExpectDisplayNameEq(exception, /*display_name=*/"Gizmo"); const auto& sites_list = exception.FindKey(kSites)->GetList(); ASSERT_EQ(sites_list.size(), 2u); ExpectValidSiteExceptionObject(sites_list[0], /*origin=*/ChromiumUrl(), /*source=*/kPolicySource, /*incognito=*/false); ExpectValidSiteExceptionObject(sites_list[1], /*origin=*/TestUrl(), /*source=*/kPreferenceSource, /*incognito=*/false); } } } // namespace site_settings
42.830732
81
0.674505
[ "object", "vector" ]
b423d88bb9adab6a166fbea6f583c3998b6adbd5
14,473
cpp
C++
groups/btl/btlmt/btlmt_channelpoolchannel.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2021-04-28T13:51:30.000Z
2021-04-28T13:51:30.000Z
groups/btl/btlmt/btlmt_channelpoolchannel.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
null
null
null
groups/btl/btlmt/btlmt_channelpoolchannel.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2019-06-26T13:28:48.000Z
2019-06-26T13:28:48.000Z
// btlmt_channelpoolchannel.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <btlmt_channelpoolchannel.h> #include <bsls_ident.h> BSLS_IDENT("$Id$ $CSID$") #include <btlmt_channelpool.h> #include <btlb_blob.h> #include <btlb_blobutil.h> #include <btlb_pooledblobbufferfactory.h> #include <bdlf_bind.h> #include <bdlf_memfn.h> #include <bdlma_bufferedsequentialallocator.h> #include <bdlma_concurrentpoolallocator.h> #include <bdlt_currenttime.h> #include <bslma_default.h> #include <bslmt_lockguard.h> #include <bsls_assert.h> #include <bsls_performancehint.h> #include <bsls_platform.h> #include <bsls_timeinterval.h> #include <bsl_functional.h> namespace BloombergLP { namespace btlmt { // ------------------------ // class ChannelPoolChannel // ------------------------ // PRIVATE MANIPULATORS int ChannelPoolChannel::addReadQueueEntry( int numBytes, const BlobBasedReadCallback& callback, const bsls::TimeInterval& timeOut) { if (d_closed) { return -6; // RETURN } BSLS_ASSERT(0 < numBytes); d_readQueue.push_back(ReadQueueEntry()); ReadQueueEntry& entry = d_readQueue.back(); entry.d_numBytesNeeded = numBytes; entry.d_timeOut = timeOut; entry.d_timeOutTimerId = 0; entry.d_progress = AsyncChannel::e_SUCCESS; entry.d_readCallback = callback; if (0 != timeOut.totalMicroseconds()) { registerTimeoutAndUpdateClockId(timeOut); entry.d_timeOutTimerId = d_nextClockId; } if (1 == d_readQueue.size()) { d_channelPool_p->enableRead(d_channelId); } return 0; } void ChannelPoolChannel::registerTimeoutAndUpdateClockId( const bsls::TimeInterval& timeOut) { // This interface stinks: we have to guess a clockId that will not compete // with other clients of the channelpool! Instead, channelpool should // return us a unique clockId. We make an educated first guess (set to // 'channelId + 0x00800000' in the ctor so as not to conflict with the // handles used as clockId in the session pool) and increment it if it // happens to be a duplicate. With current usage in session pool, a single // iteration through the loop (i.e., no loop at all) should be guaranteed. // Note that the loop increments by 0x01000001 which is prime to 2^32, and // so it will run 2^32 times before it tries the same clockId. ReadQueue::iterator entryIter = d_readQueue.end(); --entryIter; bsl::function<void()> timeoutCallback(bdlf::BindUtil::bind( bdlf::MemFnUtil::memFn(&ChannelPoolChannel::timeoutCb, this), entryIter)); while (1 == d_channelPool_p->registerClock(timeoutCallback, timeOut, bsls::TimeInterval(0), ++d_nextClockId, d_channelId)) { d_nextClockId += 0x01000000; } } void ChannelPoolChannel::removeTopReadEntry(bool invokeCallback) { ReadQueueEntry& entry = d_readQueue.front(); int timerId = entry.d_timeOutTimerId; int cancellationCode = entry.d_progress; BlobBasedReadCallback& callback = entry.d_readCallback; d_readQueue.pop_front(); bslmt::LockGuardUnlock<bslmt::Mutex> guard(&d_mutex); d_channelPool_p->deregisterClock(timerId); if (invokeCallback) { int dummy; btlb::Blob dummyBlob; callback(cancellationCode, &dummy, &dummyBlob, 0); } } // CREATORS ChannelPoolChannel::ChannelPoolChannel( int channelId, ChannelPool *channelPool, btlb::BlobBufferFactory *blobBufferFactory, bdlma::ConcurrentPoolAllocator *spAllocator, bslma::Allocator *basicAllocator) : d_mutex() , d_callbackInProgress(false) , d_closed(false) , d_readQueue(basicAllocator) , d_blobBufferFactory_p(blobBufferFactory, 0, &bslma::ManagedPtrUtil::noOpDeleter) , d_spAllocator_p(spAllocator) , d_channelPool_p(channelPool) , d_nextClockId(channelId + 0x00800000) , d_channelId(channelId) , d_peerAddress() , d_localAddress() , d_allocator_p(bslma::Default::allocator(basicAllocator)) { BSLS_ASSERT(0 != channelPool); BSLS_ASSERT(0 != blobBufferFactory); BSLS_ASSERT(0 != spAllocator); // Queue these addresses since the ChannelPool channel can have // disappeared when we get SESSION_DOWN. d_channelPool_p->getLocalAddress(&d_localAddress, d_channelId); d_channelPool_p->getPeerAddress(&d_peerAddress, d_channelId); } ChannelPoolChannel::~ChannelPoolChannel() { // Cancel future callbacks, but do not invoke them if this channel is // closed. cancelRead(); } // MANIPULATORS int ChannelPoolChannel::read(int numBytes, const BlobBasedReadCallback& callback) { bslmt::LockGuard<bslmt::Mutex> lock(&d_mutex); return addReadQueueEntry(numBytes, callback, bsls::TimeInterval(0)); } int ChannelPoolChannel::timedRead(int numBytes, const bsls::TimeInterval& timeOut, const BlobBasedReadCallback& callback) { bslmt::LockGuard<bslmt::Mutex> lock(&d_mutex); return addReadQueueEntry(numBytes, callback, timeOut); } int ChannelPoolChannel::write(const btlb::Blob& blob, int highWaterMark) { return d_channelPool_p->write(d_channelId, blob, highWaterMark); } void ChannelPoolChannel::timeoutCb(ReadQueue::iterator entryIter) { bslmt::LockGuard<bslmt::Mutex> lock(&d_mutex); // It seems that at this point, 'd_callbackInProgress' must be false. We // need to investigate and remove the if statement if this is true. if (d_callbackInProgress && entryIter == d_readQueue.begin()) { // We are invoking this callback, it will either succeed (consume // everything and be removed from the queue) or need more bytes (and // re-enter the loop), so we cannot remove it, but we can mark it as // canceled. It will ensure that it is not called again in case more // bytes are needed. entryIter->d_progress = AsyncChannel::e_TIMEOUT; } else { // Remove this callback from the queue. BlobBasedReadCallback callback = entryIter->d_readCallback; d_readQueue.erase(entryIter); { bslmt::LockGuardUnlock<bslmt::Mutex> unlockGuard(&d_mutex); int dummy = 0; btlb::Blob emptyBlob; callback(AsyncChannel::e_TIMEOUT, &dummy, &emptyBlob, d_channelId); } } } void ChannelPoolChannel::cancelRead() { const int NUM_ENTRIES = 16; const int SIZE = NUM_ENTRIES * sizeof(ReadQueueEntry); char BUFFER[SIZE]; bdlma::BufferedSequentialAllocator bufferAllocator(BUFFER, SIZE); ReadQueue cancelQueue(&bufferAllocator); { bslmt::LockGuard<bslmt::Mutex> lock(&d_mutex); if (!d_readQueue.size()) { return; // RETURN } ReadQueue::iterator it = d_readQueue.begin(); if (d_callbackInProgress) { it->d_progress = AsyncChannel::e_CANCELED; ++it; } if (!d_closed) { cancelQueue.insert(cancelQueue.end(), it, d_readQueue.end()); } for (ReadQueue::iterator it2 = it; it2 != d_readQueue.end(); ++it2) { if (bsls::TimeInterval(0) != it2->d_timeOut) { d_channelPool_p->deregisterClock(it2->d_timeOutTimerId); } } d_readQueue.erase(it, d_readQueue.end()); } if (!d_closed) { // We do not invoke callbacks on a closed channel, because to be // correct those callbacks should only be involved in the dispatcher // thread of the channel pool's manager corresponding to this channel, // but this object might be being destroyed and no further callbacks // referencing this channel should be invoked. bsls::TimeInterval now = bdlt::CurrentTime::now(); int dummy = 0; btlb::Blob dummyBlob; for (ReadQueue::iterator it = cancelQueue.begin(); it != cancelQueue.end(); ++it) { bsl::function<void()> cancelNotifyCallback( bdlf::BindUtil::bind(it->d_readCallback, AsyncChannel::e_CANCELED, &dummy, &dummyBlob, d_channelId)); int rc; while (1 == (rc = d_channelPool_p->registerClock( cancelNotifyCallback, now, bsls::TimeInterval(0), ++d_nextClockId, d_channelId))) { d_nextClockId += 0x01000000; } if (rc) { // The channel was already cleaned up in channel pool because // the connection was closed at the other end. We assume that // this is the event manager's dispatcher thread and it is safe // to invoke the cancel notify callback from this thread. cancelNotifyCallback(); } } } } void ChannelPoolChannel::close() { bslmt::LockGuard<bslmt::Mutex> lock(&d_mutex); if (!d_closed) { d_closed = true; d_channelPool_p->shutdown(d_channelId, btlso::Flags::e_SHUTDOWN_GRACEFUL); if (!d_readQueue.size()) { return; // RETURN } ReadQueue::iterator it = d_readQueue.begin(); if (d_callbackInProgress) { it->d_progress = AsyncChannel::e_CLOSED; ++it; } for (ReadQueue::iterator it2 = it; it2 != d_readQueue.end(); ++it2) { if (bsls::TimeInterval(0) != it2->d_timeOut) { d_channelPool_p->deregisterClock(it2->d_timeOutTimerId); } } d_readQueue.erase(it, d_readQueue.end()); } } void ChannelPoolChannel::blobBasedDataCb(int *numNeeded, btlb::Blob *msg) { *numNeeded = 1; int numBytesAvailable = msg->length(); bslmt::LockGuard<bslmt::Mutex> lock(&d_mutex); d_callbackInProgress = true; while (!d_closed && d_readQueue.size() && (d_readQueue.front().d_numBytesNeeded <= numBytesAvailable || d_readQueue.front().d_progress)) { // Note: 'd_closed' may be set by a read callback within the loop, in // which case do not process further callbacks and exit the loop. ReadQueueEntry& entry = d_readQueue.front(); if (AsyncChannel::e_SUCCESS != entry.d_progress) { removeTopReadEntry(true); continue; } int numConsumed = 0; int minBytesBeforeNextCb = 0; const BlobBasedReadCallback& callback = entry.d_readCallback; numBytesAvailable = msg->length(); { bslmt::LockGuardUnlock<bslmt::Mutex> guard(&d_mutex); callback(e_SUCCESS, &minBytesBeforeNextCb, msg, d_channelId); numConsumed = numBytesAvailable - msg->length(); } BSLS_ASSERT(0 <= minBytesBeforeNextCb); BSLS_ASSERT(0 <= numConsumed); numBytesAvailable -= numConsumed; if (minBytesBeforeNextCb) { entry.d_numBytesNeeded = minBytesBeforeNextCb; if (minBytesBeforeNextCb <= numBytesAvailable) { continue; } *numNeeded = minBytesBeforeNextCb - numBytesAvailable; } else { removeTopReadEntry(false); if (!d_readQueue.size()) { d_channelPool_p->disableRead(d_channelId); } } } d_callbackInProgress = false; lock.release()->unlock(); } // ACCESSORS btlso::IPv4Address ChannelPoolChannel::localAddress() const { return d_localAddress; } btlso::IPv4Address ChannelPoolChannel::peerAddress() const { return d_peerAddress; } int ChannelPoolChannel::setSocketOption(int option, int level, int value) { return d_channelPool_p->setSocketOption(option, level, value, d_channelId); } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
33.736597
79
0.565536
[ "object" ]
b42f34b651c87e4e2cb1b483cbf75dc379f982ed
15,647
cpp
C++
code/AssetLib/Irr/IRRShared.cpp
sir-sparrow/assimp
8c3e983bc31f69eea0b5d690ad19b63062fbdd1c
[ "BSD-3-Clause" ]
7,604
2015-01-01T01:58:57.000Z
2022-03-31T09:51:25.000Z
code/AssetLib/Irr/IRRShared.cpp
sir-sparrow/assimp
8c3e983bc31f69eea0b5d690ad19b63062fbdd1c
[ "BSD-3-Clause" ]
3,677
2015-01-02T08:06:57.000Z
2022-03-31T19:24:26.000Z
code/AssetLib/Irr/IRRShared.cpp
sir-sparrow/assimp
8c3e983bc31f69eea0b5d690ad19b63062fbdd1c
[ "BSD-3-Clause" ]
2,728
2015-01-01T19:28:19.000Z
2022-03-31T16:07:18.000Z
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2021, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. --------------------------------------------------------------------------- */ /** @file IRRShared.cpp * @brief Shared utilities for the IRR and IRRMESH loaders */ //This section should be excluded only if both the Irrlicht AND the Irrlicht Mesh importers were omitted. #if !(defined(ASSIMP_BUILD_NO_IRR_IMPORTER) && defined(ASSIMP_BUILD_NO_IRRMESH_IMPORTER)) #include "IRRShared.h" #include <assimp/ParsingUtils.h> #include <assimp/fast_atof.h> #include <assimp/DefaultLogger.hpp> #include <assimp/material.h> using namespace Assimp; // Transformation matrix to convert from Assimp to IRR space const aiMatrix4x4 Assimp::AI_TO_IRR_MATRIX = aiMatrix4x4 ( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); // ------------------------------------------------------------------------------------------------ // read a property in hexadecimal format (i.e. ffffffff) void IrrlichtBase::ReadHexProperty(HexProperty &out ) { for (pugi::xml_attribute attrib : mNode->attributes()) { if (!ASSIMP_stricmp(attrib.name(), "name")) { out.name = std::string( attrib.value() ); } else if (!ASSIMP_stricmp(attrib.name(),"value")) { // parse the hexadecimal value out.value = strtoul16(attrib.name()); } } } // ------------------------------------------------------------------------------------------------ // read a decimal property void IrrlichtBase::ReadIntProperty(IntProperty & out) { for (pugi::xml_attribute attrib : mNode->attributes()) { if (!ASSIMP_stricmp(attrib.name(), "name")) { out.name = std::string(attrib.value()); } else if (!ASSIMP_stricmp(attrib.value(),"value")) { // parse the int value out.value = strtol10(attrib.name()); } } } // ------------------------------------------------------------------------------------------------ // read a string property void IrrlichtBase::ReadStringProperty( StringProperty& out) { for (pugi::xml_attribute attrib : mNode->attributes()) { if (!ASSIMP_stricmp(attrib.name(), "name")) { out.name = std::string(attrib.value()); } else if (!ASSIMP_stricmp(attrib.name(), "value")) { // simple copy the string out.value = std::string(attrib.value()); } } } // ------------------------------------------------------------------------------------------------ // read a boolean property void IrrlichtBase::ReadBoolProperty(BoolProperty &out) { for (pugi::xml_attribute attrib : mNode->attributes()) { if (!ASSIMP_stricmp(attrib.name(), "name")){ out.name = std::string(attrib.value()); } else if (!ASSIMP_stricmp(attrib.name(), "value")) { // true or false, case insensitive out.value = (ASSIMP_stricmp(attrib.value(), "true") ? false : true); } } } // ------------------------------------------------------------------------------------------------ // read a float property void IrrlichtBase::ReadFloatProperty(FloatProperty &out) { for (pugi::xml_attribute attrib : mNode->attributes()) { if (!ASSIMP_stricmp(attrib.name(), "name")) { out.name = std::string(attrib.value()); } else if (!ASSIMP_stricmp(attrib.name(), "value")) { // just parse the float out.value = fast_atof(attrib.value()); } } } // ------------------------------------------------------------------------------------------------ // read a vector property void IrrlichtBase::ReadVectorProperty( VectorProperty &out ) { for (pugi::xml_attribute attrib : mNode->attributes()) { if (!ASSIMP_stricmp(attrib.name(), "name")) { out.name = std::string(attrib.value()); } else if (!ASSIMP_stricmp(attrib.name(), "value")) { // three floats, separated with commas const char *ptr = attrib.value(); SkipSpaces(&ptr); ptr = fast_atoreal_move<float>( ptr,(float&)out.value.x ); SkipSpaces(&ptr); if (',' != *ptr) { ASSIMP_LOG_ERROR("IRR(MESH): Expected comma in vector definition"); } else { SkipSpaces(ptr + 1, &ptr); } ptr = fast_atoreal_move<float>( ptr,(float&)out.value.y ); SkipSpaces(&ptr); if (',' != *ptr) { ASSIMP_LOG_ERROR("IRR(MESH): Expected comma in vector definition"); } else { SkipSpaces(ptr + 1, &ptr); } ptr = fast_atoreal_move<float>( ptr,(float&)out.value.z ); } } } // ------------------------------------------------------------------------------------------------ // Convert a string to a proper aiMappingMode int ConvertMappingMode(const std::string& mode) { if (mode == "texture_clamp_repeat") { return aiTextureMapMode_Wrap; } else if (mode == "texture_clamp_mirror") { return aiTextureMapMode_Mirror; } return aiTextureMapMode_Clamp; } // ------------------------------------------------------------------------------------------------ // Parse a material from the XML file aiMaterial* IrrlichtBase::ParseMaterial(unsigned int& matFlags) { aiMaterial* mat = new aiMaterial(); aiColor4D clr; aiString s; matFlags = 0; // zero output flags int cnt = 0; // number of used texture channels unsigned int nd = 0; for (pugi::xml_node child : mNode->children()) { if (!ASSIMP_stricmp(child.name(), "color")) { // Hex properties HexProperty prop; ReadHexProperty(prop); if (prop.name == "Diffuse") { ColorFromARGBPacked(prop.value, clr); mat->AddProperty(&clr, 1, AI_MATKEY_COLOR_DIFFUSE); } else if (prop.name == "Ambient") { ColorFromARGBPacked(prop.value, clr); mat->AddProperty(&clr, 1, AI_MATKEY_COLOR_AMBIENT); } else if (prop.name == "Specular") { ColorFromARGBPacked(prop.value, clr); mat->AddProperty(&clr, 1, AI_MATKEY_COLOR_SPECULAR); } // NOTE: The 'emissive' property causes problems. It is // often != 0, even if there is obviously no light // emitted by the described surface. In fact I think // IRRLICHT ignores this property, too. #if 0 else if (prop.name == "Emissive") { ColorFromARGBPacked(prop.value,clr); mat->AddProperty(&clr,1,AI_MATKEY_COLOR_EMISSIVE); } #endif } else if (!ASSIMP_stricmp(child.name(), "float")) { // Float properties FloatProperty prop; ReadFloatProperty(prop); if (prop.name == "Shininess") { mat->AddProperty(&prop.value, 1, AI_MATKEY_SHININESS); } } else if (!ASSIMP_stricmp(child.name(), "bool")) { // Bool properties BoolProperty prop; ReadBoolProperty(prop); if (prop.name == "Wireframe") { int val = (prop.value ? true : false); mat->AddProperty(&val, 1, AI_MATKEY_ENABLE_WIREFRAME); } else if (prop.name == "GouraudShading") { int val = (prop.value ? aiShadingMode_Gouraud : aiShadingMode_NoShading); mat->AddProperty(&val, 1, AI_MATKEY_SHADING_MODEL); } else if (prop.name == "BackfaceCulling") { int val = (!prop.value); mat->AddProperty(&val, 1, AI_MATKEY_TWOSIDED); } } else if (!ASSIMP_stricmp(child.name(), "texture") || !ASSIMP_stricmp(child.name(), "enum")) { // String properties - textures and texture related properties StringProperty prop; ReadStringProperty(prop); if (prop.value.length()) { // material type (shader) if (prop.name == "Type") { if (prop.value == "solid") { // default material ... } else if (prop.value == "trans_vertex_alpha") { matFlags = AI_IRRMESH_MAT_trans_vertex_alpha; } else if (prop.value == "lightmap") { matFlags = AI_IRRMESH_MAT_lightmap; } else if (prop.value == "solid_2layer") { matFlags = AI_IRRMESH_MAT_solid_2layer; } else if (prop.value == "lightmap_m2") { matFlags = AI_IRRMESH_MAT_lightmap_m2; } else if (prop.value == "lightmap_m4") { matFlags = AI_IRRMESH_MAT_lightmap_m4; } else if (prop.value == "lightmap_light") { matFlags = AI_IRRMESH_MAT_lightmap_light; } else if (prop.value == "lightmap_light_m2") { matFlags = AI_IRRMESH_MAT_lightmap_light_m2; } else if (prop.value == "lightmap_light_m4") { matFlags = AI_IRRMESH_MAT_lightmap_light_m4; } else if (prop.value == "lightmap_add") { matFlags = AI_IRRMESH_MAT_lightmap_add; } else if (prop.value == "normalmap_solid" || prop.value == "parallaxmap_solid") { // Normal and parallax maps are treated equally matFlags = AI_IRRMESH_MAT_normalmap_solid; } else if (prop.value == "normalmap_trans_vertex_alpha" || prop.value == "parallaxmap_trans_vertex_alpha") { matFlags = AI_IRRMESH_MAT_normalmap_tva; } else if (prop.value == "normalmap_trans_add" || prop.value == "parallaxmap_trans_add") { matFlags = AI_IRRMESH_MAT_normalmap_ta; } else { ASSIMP_LOG_WARN("IRRMat: Unrecognized material type: ", prop.value); } } // Up to 4 texture channels are supported if (prop.name == "Texture1") { // Always accept the primary texture channel ++cnt; s.Set(prop.value); mat->AddProperty(&s, AI_MATKEY_TEXTURE_DIFFUSE(0)); } else if (prop.name == "Texture2" && cnt == 1) { // 2-layer material lightmapped? if (matFlags & AI_IRRMESH_MAT_lightmap) { ++cnt; s.Set(prop.value); mat->AddProperty(&s, AI_MATKEY_TEXTURE_LIGHTMAP(0)); // set the corresponding material flag matFlags |= AI_IRRMESH_EXTRA_2ND_TEXTURE; } else if (matFlags & AI_IRRMESH_MAT_normalmap_solid) { // alternatively: normal or parallax mapping ++cnt; s.Set(prop.value); mat->AddProperty(&s, AI_MATKEY_TEXTURE_NORMALS(0)); // set the corresponding material flag matFlags |= AI_IRRMESH_EXTRA_2ND_TEXTURE; } else if (matFlags & AI_IRRMESH_MAT_solid_2layer) { // or just as second diffuse texture ++cnt; s.Set(prop.value); mat->AddProperty(&s, AI_MATKEY_TEXTURE_DIFFUSE(1)); ++nd; // set the corresponding material flag matFlags |= AI_IRRMESH_EXTRA_2ND_TEXTURE; } else { ASSIMP_LOG_WARN("IRRmat: Skipping second texture"); } } else if (prop.name == "Texture3" && cnt == 2) { // Irrlicht does not seem to use these channels. ++cnt; s.Set(prop.value); mat->AddProperty(&s, AI_MATKEY_TEXTURE_DIFFUSE(nd + 1)); } else if (prop.name == "Texture4" && cnt == 3) { // Irrlicht does not seem to use these channels. ++cnt; s.Set(prop.value); mat->AddProperty(&s, AI_MATKEY_TEXTURE_DIFFUSE(nd + 2)); } // Texture mapping options if (prop.name == "TextureWrap1" && cnt >= 1) { int map = ConvertMappingMode(prop.value); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0)); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0)); } else if (prop.name == "TextureWrap2" && cnt >= 2) { int map = ConvertMappingMode(prop.value); if (matFlags & AI_IRRMESH_MAT_lightmap) { mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_U_LIGHTMAP(0)); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_V_LIGHTMAP(0)); } else if (matFlags & (AI_IRRMESH_MAT_normalmap_solid)) { mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_U_NORMALS(0)); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_V_NORMALS(0)); } else if (matFlags & AI_IRRMESH_MAT_solid_2layer) { mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(1)); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(1)); } } else if (prop.name == "TextureWrap3" && cnt >= 3) { int map = ConvertMappingMode(prop.value); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(nd + 1)); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(nd + 1)); } else if (prop.name == "TextureWrap4" && cnt >= 4) { int map = ConvertMappingMode(prop.value); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(nd + 2)); mat->AddProperty(&map, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(nd + 2)); } } } //break; /*case EXN_ELEMENT_END: // Assume there are no further nested nodes in <material> elements if ( !ASSIMP_stricmp(reader->getNodeName(),"material") || !ASSIMP_stricmp(reader->getNodeName(),"attributes")) { // Now process lightmapping flags // We should have at least one textur to do that .. if (cnt && matFlags & AI_IRRMESH_MAT_lightmap) { float f = 1.f; unsigned int unmasked = matFlags&~AI_IRRMESH_MAT_lightmap; // Additive lightmap? int op = (unmasked & AI_IRRMESH_MAT_lightmap_add ? aiTextureOp_Add : aiTextureOp_Multiply); // Handle Irrlicht's lightmapping scaling factor if (unmasked & AI_IRRMESH_MAT_lightmap_m2 || unmasked & AI_IRRMESH_MAT_lightmap_light_m2) { f = 2.f; } else if (unmasked & AI_IRRMESH_MAT_lightmap_m4 || unmasked & AI_IRRMESH_MAT_lightmap_light_m4) { f = 4.f; } mat->AddProperty( &f, 1, AI_MATKEY_TEXBLEND_LIGHTMAP(0)); mat->AddProperty( &op,1, AI_MATKEY_TEXOP_LIGHTMAP(0)); } return mat; } default: // GCC complains here ... break; } }*/ } ASSIMP_LOG_ERROR("IRRMESH: Unexpected end of file. Material is not complete"); return mat; } #endif // !(defined(ASSIMP_BUILD_NO_IRR_IMPORTER) && defined(ASSIMP_BUILD_NO_IRRMESH_IMPORTER))
40.32732
110
0.597686
[ "mesh", "vector", "solid" ]
b431c5e076fbaa9adf70755efb943d365001bdc9
9,953
cc
C++
source/common/redis/conn_pool_impl.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
2
2017-07-31T15:03:19.000Z
2018-02-20T16:18:49.000Z
source/common/redis/conn_pool_impl.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
null
null
null
source/common/redis/conn_pool_impl.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
null
null
null
#include "common/redis/conn_pool_impl.h" #include <cstdint> #include <memory> #include <string> #include <vector> #include "common/common/assert.h" #include "common/common/enum_to_int.h" #include "common/http/codes.h" #include "common/json/config_schemas.h" namespace Envoy { namespace Redis { namespace ConnPool { ConfigImpl::ConfigImpl(const Json::Object& config) : Validator(config, Json::Schema::REDIS_CONN_POOL_SCHEMA), op_timeout_(config.getInteger("op_timeout_ms")) {} ClientPtr ClientImpl::create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher, EncoderPtr&& encoder, DecoderFactory& decoder_factory, const Config& config) { std::unique_ptr<ClientImpl> client( new ClientImpl(host, dispatcher, std::move(encoder), decoder_factory, config)); client->connection_ = host->createConnection(dispatcher).connection_; client->connection_->addConnectionCallbacks(*client); client->connection_->addReadFilter(Network::ReadFilterSharedPtr{new UpstreamReadFilter(*client)}); client->connection_->connect(); client->connection_->noDelay(true); return std::move(client); } ClientImpl::ClientImpl(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher, EncoderPtr&& encoder, DecoderFactory& decoder_factory, const Config& config) : host_(host), encoder_(std::move(encoder)), decoder_(decoder_factory.create(*this)), config_(config), connect_or_op_timer_(dispatcher.createTimer([this]() -> void { onConnectOrOpTimeout(); })) { host->cluster().stats().upstream_cx_total_.inc(); host->cluster().stats().upstream_cx_active_.inc(); host->stats().cx_total_.inc(); host->stats().cx_active_.inc(); connect_or_op_timer_->enableTimer(host->cluster().connectTimeout()); } ClientImpl::~ClientImpl() { ASSERT(pending_requests_.empty()); ASSERT(connection_->state() == Network::Connection::State::Closed); host_->cluster().stats().upstream_cx_active_.dec(); host_->stats().cx_active_.dec(); } void ClientImpl::close() { connection_->close(Network::ConnectionCloseType::NoFlush); } PoolRequest* ClientImpl::makeRequest(const RespValue& request, PoolCallbacks& callbacks) { ASSERT(connection_->state() == Network::Connection::State::Open); pending_requests_.emplace_back(*this, callbacks); encoder_->encode(request, encoder_buffer_); connection_->write(encoder_buffer_); // Only boost the op timeout if we are not already connected. Otherwise, we are governed by // the connect timeout and the timer will be reset when/if connection occurs. This allows a // relatively long connection spin up time for example if TLS is being used. if (connected_) { connect_or_op_timer_->enableTimer(config_.opTimeout()); } return &pending_requests_.back(); } void ClientImpl::onConnectOrOpTimeout() { host_->outlierDetector().putHttpResponseCode(enumToInt(Http::Code::GatewayTimeout)); if (connected_) { host_->cluster().stats().upstream_rq_timeout_.inc(); } else { host_->cluster().stats().upstream_cx_connect_timeout_.inc(); } connection_->close(Network::ConnectionCloseType::NoFlush); } void ClientImpl::onData(Buffer::Instance& data) { try { decoder_->decode(data); } catch (ProtocolError&) { host_->outlierDetector().putHttpResponseCode(enumToInt(Http::Code::InternalServerError)); host_->cluster().stats().upstream_cx_protocol_error_.inc(); connection_->close(Network::ConnectionCloseType::NoFlush); } } void ClientImpl::onEvent(uint32_t events) { if ((events & Network::ConnectionEvent::RemoteClose) || (events & Network::ConnectionEvent::LocalClose)) { if (!pending_requests_.empty()) { host_->cluster().stats().upstream_cx_destroy_with_active_rq_.inc(); if (events & Network::ConnectionEvent::RemoteClose) { host_->outlierDetector().putHttpResponseCode(enumToInt(Http::Code::ServiceUnavailable)); host_->cluster().stats().upstream_cx_destroy_remote_with_active_rq_.inc(); } if (events & Network::ConnectionEvent::LocalClose) { host_->cluster().stats().upstream_cx_destroy_local_with_active_rq_.inc(); } } while (!pending_requests_.empty()) { PendingRequest& request = pending_requests_.front(); if (!request.canceled_) { request.callbacks_.onFailure(); } else { host_->cluster().stats().upstream_rq_cancelled_.inc(); } pending_requests_.pop_front(); } connect_or_op_timer_->disableTimer(); } else if (events & Network::ConnectionEvent::Connected) { connected_ = true; ASSERT(!pending_requests_.empty()); connect_or_op_timer_->enableTimer(config_.opTimeout()); } if ((events & Network::ConnectionEvent::RemoteClose) && !connected_) { host_->cluster().stats().upstream_cx_connect_fail_.inc(); host_->stats().cx_connect_fail_.inc(); } } void ClientImpl::onRespValue(RespValuePtr&& value) { ASSERT(!pending_requests_.empty()); PendingRequest& request = pending_requests_.front(); if (!request.canceled_) { request.callbacks_.onResponse(std::move(value)); } else { host_->cluster().stats().upstream_rq_cancelled_.inc(); } pending_requests_.pop_front(); // We boost the op timeout every time we pipeline a new op. However, if there are no remaining // ops in the pipeline we need to disable the timer. if (pending_requests_.empty()) { connect_or_op_timer_->disableTimer(); } host_->outlierDetector().putHttpResponseCode(enumToInt(Http::Code::OK)); } ClientImpl::PendingRequest::PendingRequest(ClientImpl& parent, PoolCallbacks& callbacks) : parent_(parent), callbacks_(callbacks) { parent.host_->cluster().stats().upstream_rq_total_.inc(); parent.host_->cluster().stats().upstream_rq_active_.inc(); parent.host_->stats().rq_total_.inc(); parent.host_->stats().rq_active_.inc(); } ClientImpl::PendingRequest::~PendingRequest() { parent_.host_->cluster().stats().upstream_rq_active_.dec(); parent_.host_->stats().rq_active_.dec(); } void ClientImpl::PendingRequest::cancel() { // If we get a cancellation, we just mark the pending request as cancelled, and then we drop // the response as it comes through. There is no reason to blow away the connection when the // remote is already responding as fast as possible. canceled_ = true; } ClientFactoryImpl ClientFactoryImpl::instance_; ClientPtr ClientFactoryImpl::create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher, const Config& config) { return ClientImpl::create(host, dispatcher, EncoderPtr{new EncoderImpl()}, decoder_factory_, config); } InstanceImpl::InstanceImpl(const std::string& cluster_name, Upstream::ClusterManager& cm, ClientFactory& client_factory, ThreadLocal::Instance& tls, const Json::Object& config) : cm_(cm), client_factory_(client_factory), tls_(tls), tls_slot_(tls.allocateSlot()), config_(config) { tls.set(tls_slot_, [this, cluster_name]( Event::Dispatcher& dispatcher) -> ThreadLocal::ThreadLocalObjectSharedPtr { return std::make_shared<ThreadLocalPool>(*this, dispatcher, cluster_name); }); } PoolRequest* InstanceImpl::makeRequest(const std::string& hash_key, const RespValue& value, PoolCallbacks& callbacks) { return tls_.getTyped<ThreadLocalPool>(tls_slot_).makeRequest(hash_key, value, callbacks); } InstanceImpl::ThreadLocalPool::ThreadLocalPool(InstanceImpl& parent, Event::Dispatcher& dispatcher, const std::string& cluster_name) : parent_(parent), dispatcher_(dispatcher), cluster_(parent_.cm_.get(cluster_name)) { cluster_->hostSet().addMemberUpdateCb( [this](const std::vector<Upstream::HostSharedPtr>&, const std::vector<Upstream::HostSharedPtr>& hosts_removed) -> void { onHostsRemoved(hosts_removed); }); } void InstanceImpl::ThreadLocalPool::onHostsRemoved( const std::vector<Upstream::HostSharedPtr>& hosts_removed) { for (const auto& host : hosts_removed) { auto it = client_map_.find(host); if (it != client_map_.end()) { // We don't currently support any type of draining for redis connections. If a host is gone, // we just close the connection. This will fail any pending requests. it->second->redis_client_->close(); } } } PoolRequest* InstanceImpl::ThreadLocalPool::makeRequest(const std::string& hash_key, const RespValue& request, PoolCallbacks& callbacks) { LbContextImpl lb_context(hash_key); Upstream::HostConstSharedPtr host = cluster_->loadBalancer().chooseHost(&lb_context); if (!host) { return nullptr; } ThreadLocalActiveClientPtr& client = client_map_[host]; if (!client) { client.reset(new ThreadLocalActiveClient(*this)); client->host_ = host; client->redis_client_ = parent_.client_factory_.create(host, dispatcher_, parent_.config_); client->redis_client_->addConnectionCallbacks(*client); } return client->redis_client_->makeRequest(request, callbacks); } void InstanceImpl::ThreadLocalActiveClient::onEvent(uint32_t events) { if ((events & Network::ConnectionEvent::RemoteClose) || (events & Network::ConnectionEvent::LocalClose)) { auto client_to_delete = parent_.client_map_.find(host_); ASSERT(client_to_delete != parent_.client_map_.end()); parent_.dispatcher_.deferredDelete(std::move(client_to_delete->second->redis_client_)); parent_.client_map_.erase(client_to_delete); } } void InstanceImpl::ThreadLocalPool::shutdown() { while (!client_map_.empty()) { client_map_.begin()->second->redis_client_->close(); } } } // ConnPool } // Redis } // Envoy
39.185039
100
0.701999
[ "object", "vector" ]
b43741500f267de3143a9050e05fd6a900421772
3,716
cpp
C++
src/modules/audio/openal/Pool.cpp
darmie/love2d
3f3f9fa5185653683fddc31eddfda10aff7d9694
[ "Apache-2.0" ]
null
null
null
src/modules/audio/openal/Pool.cpp
darmie/love2d
3f3f9fa5185653683fddc31eddfda10aff7d9694
[ "Apache-2.0" ]
null
null
null
src/modules/audio/openal/Pool.cpp
darmie/love2d
3f3f9fa5185653683fddc31eddfda10aff7d9694
[ "Apache-2.0" ]
1
2021-10-21T14:47:36.000Z
2021-10-21T14:47:36.000Z
/** * Copyright (c) 2006-2019 LOVE Development Team * * 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 "Pool.h" #include "Source.h" namespace love { namespace audio { namespace openal { Pool::Pool() : sources() , totalSources(0) { // Clear errors. alGetError(); // Generate sources. for (int i = 0; i < MAX_SOURCES; i++) { alGenSources(1, &sources[i]); // We might hit an implementation-dependent limit on the total number // of sources before reaching MAX_SOURCES. if (alGetError() != AL_NO_ERROR) break; totalSources++; } if (totalSources < 4) throw love::Exception("Could not generate sources."); #ifdef AL_SOFT_direct_channels ALboolean hasext = alIsExtensionPresent("AL_SOFT_direct_channels"); #endif // Make all sources available initially. for (int i = 0; i < totalSources; i++) { #ifdef AL_SOFT_direct_channels if (hasext) { // Bypass virtualization of speakers for multi-channel sources in OpenAL Soft. alSourcei(sources[i], AL_DIRECT_CHANNELS_SOFT, AL_TRUE); } #endif available.push(sources[i]); } } Pool::~Pool() { Source::stop(this); // Free all sources. alDeleteSources(totalSources, sources); } bool Pool::isAvailable() const { bool has = false; { thread::Lock lock(mutex); has = !available.empty(); } return has; } bool Pool::isPlaying(Source *s) { bool p = false; { thread::Lock lock(mutex); p = (playing.find(s) != playing.end()); } return p; } void Pool::update() { thread::Lock lock(mutex); std::vector<Source *> torelease; for (const auto &i : playing) { if (!i.first->update()) torelease.push_back(i.first); } for (Source *s : torelease) releaseSource(s); } int Pool::getActiveSourceCount() const { return (int) playing.size(); } int Pool::getMaxSources() const { return totalSources; } bool Pool::assignSource(Source *source, ALuint &out, char &wasPlaying) { out = 0; if (findSource(source, out)) return wasPlaying = true; wasPlaying = false; if (available.empty()) return false; out = available.front(); available.pop(); playing.insert(std::make_pair(source, out)); source->retain(); return true; } bool Pool::releaseSource(Source *source, bool stop) { ALuint s; if (findSource(source, s)) { if (stop) source->stopAtomic(); source->release(); available.push(s); playing.erase(source); return true; } return false; } bool Pool::findSource(Source *source, ALuint &out) { std::map<Source *, ALuint>::const_iterator i = playing.find(source); if (i == playing.end()) return false; out = i->second; return true; } thread::Lock Pool::lock() { return thread::Lock(mutex); } std::vector<love::audio::Source*> Pool::getPlayingSources() { std::vector<love::audio::Source*> sources; sources.reserve(playing.size()); for (auto &i : playing) sources.push_back(i.first); return sources; } } // openal } // audio } // love
19.253886
81
0.689989
[ "vector" ]
b438833e7ebc23a199b936e7d85c92201e370976
4,855
cpp
C++
main.cpp
tehongis/CaveScavenger
a3f878e01958baf84f2f9007a2d862f550a15c7f
[ "MIT" ]
null
null
null
main.cpp
tehongis/CaveScavenger
a3f878e01958baf84f2f9007a2d862f550a15c7f
[ "MIT" ]
null
null
null
main.cpp
tehongis/CaveScavenger
a3f878e01958baf84f2f9007a2d862f550a15c7f
[ "MIT" ]
null
null
null
// Code by Tero Hongisto. // Release under MIT license. #include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_mixer.h> #include <Box2D/Box2D.h> #define TICK_INTERVAL 50 using namespace std; static SDL_Renderer *gRenderer = NULL; static Uint32 next_time; static Uint32 time_left(void) { Uint32 now; now = SDL_GetTicks(); if (next_time <= now) return 0; else return next_time - now; } class gObj { double objX; double objY; int objW; int objH; double objAngle; double objMomentum; SDL_Texture *objTexture; public: //Default Constructor gObj(int x, int y, double angle, SDL_Texture *texture) { objX = x; objY = y; objAngle = angle; objTexture = texture; SDL_QueryTexture(texture, NULL, NULL, &objW, &objH); objMomentum = 0.0; } public: void move() { objX = objX + objMomentum * sin(objAngle); objY = objY + objMomentum * cos(objAngle); objMomentum = objMomentum * 0.01; } void push(double pushAngle, double pushForce) { objAngle = pushAngle; objMomentum = pushForce; } void draw() { //Set rendering space and render to screen SDL_Rect renderQuad = {int(objX), int(objY), int(objW / 2), int(objH / 2)}; //Render ship to screen SDL_RenderCopyEx(gRenderer, objTexture, NULL, &renderQuad, objAngle, NULL, SDL_FLIP_NONE); } }; static SDL_Texture *loadTexture(std::string path) { //The final texture SDL_Texture *newTexture = NULL; //Load image at specified path SDL_Surface *loadedSurface = IMG_Load(path.c_str()); if (loadedSurface == NULL) { printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError()); } else { //Create texture from surface pixels newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface); if (newTexture == NULL) { printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError()); } //Get rid of old loaded surface SDL_FreeSurface(loadedSurface); } return newTexture; } int main() { SDL_Window *gWindow = NULL; SDL_Event event; SDL_Joystick *joy = NULL; static const char *nameMusic = "music/Stardrive.mp3"; static const char *nameBackground = "graphics/Aurora.jpg"; static const char *nameBox = "graphics/RTS_Crate.png"; static const char *nameShip = "graphics/Ship_A.png"; static SDL_Texture *textureBackground = NULL; static SDL_Texture *textureShip = NULL; static SDL_Texture *textureBox = NULL; bool RUNNING = false; // start SDL with video and audio support if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) == -1) { printf("SDL_Init: %s\n", SDL_GetError()); exit(1); } printf("Joysticks: %d\n", SDL_NumJoysticks()); // Check for joystick if (SDL_NumJoysticks() > 0) { // Open joystick joy = SDL_JoystickOpen(0); } else { printf("SDL_Init: Couldn't open Joystick.\n"); exit(1); } if (joy) { printf("Opened Joystick 0\n"); printf("Name: %s\n", SDL_JoystickName(0)); printf("Number of Axes: %d\n", SDL_JoystickNumAxes(joy)); printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(joy)); printf("Number of Balls: %d\n", SDL_JoystickNumBalls(joy)); } Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 2048); gWindow = SDL_CreateWindow("Cave", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 768, SDL_WINDOW_OPENGL); gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED); textureBackground = loadTexture(nameBackground); textureShip = loadTexture(nameShip); textureBox = loadTexture(nameBox); gObj *ship = new gObj(120, 150, 30, textureShip); gObj *box = new gObj(140, 200, 20, textureBox); // Check that the gWindow was successfully created if (gWindow == NULL) { // In the case that the gWindow could not be made... printf("Could not create gWindow: %s\n", SDL_GetError()); return 1; } Mix_Music *music = Mix_LoadMUS(nameMusic); next_time = SDL_GetTicks() + TICK_INTERVAL; Mix_PlayMusic(music, 1); RUNNING = true; while (RUNNING) { // Get the next event if (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { RUNNING = false; } } static const Uint8 *keys; keys = SDL_GetKeyboardState(NULL); if (keys[SDL_SCANCODE_ESCAPE]) { RUNNING = false; printf("Exiting.\n"); } //Render background SDL_RenderCopy(gRenderer, textureBackground, NULL, NULL); ship->move(); box->move(); ship->draw(); box->draw(); SDL_RenderPresent(gRenderer); SDL_Delay(time_left()); next_time += TICK_INTERVAL; } // Destroy texture SDL_DestroyTexture(textureBackground); textureBackground = NULL; SDL_DestroyTexture(textureShip); textureShip = NULL; SDL_DestroyTexture(textureBox); textureBox = NULL; SDL_JoystickClose(joy); // Close and destroy the gWindow SDL_DestroyWindow(gWindow); // Clean up SDL_Quit(); return EXIT_SUCCESS; }
20.83691
116
0.700515
[ "render" ]
b43a135e6af5b533493721280b3045c090893aeb
3,989
hpp
C++
cell_based/src/population/division_rules/RandomDirectionCentreBasedDivisionRule.hpp
DGermano8/ChasteDom
539a3a811698214c0938489b0cfdffd1abccf667
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
cell_based/src/population/division_rules/RandomDirectionCentreBasedDivisionRule.hpp
DGermano8/ChasteDom
539a3a811698214c0938489b0cfdffd1abccf667
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
cell_based/src/population/division_rules/RandomDirectionCentreBasedDivisionRule.hpp
DGermano8/ChasteDom
539a3a811698214c0938489b0cfdffd1abccf667
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2005-2018, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford 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. */ #ifndef RANDOMDIRECTIONCENTREBASEDDIVISIONRULE_HPP_ #define RANDOMDIRECTIONCENTREBASEDDIVISIONRULE_HPP_ #include "ChasteSerialization.hpp" #include <boost/serialization/base_object.hpp> #include "AbstractCentreBasedDivisionRule.hpp" #include "AbstractCentreBasedCellPopulation.hpp" // Forward declaration prevents circular include chain template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> class AbstractCentreBasedCellPopulation; template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> class AbstractCentreBasedDivisionRule; /** * A class to generate two daughter cell positions, located a distance * AbstractCentreBasedCellPopulation::mMeinekeDivisionSeparation apart, * along a random axis. The midpoint between the two daughter cell * positions corresponds to the parent cell's position. */ template<unsigned ELEMENT_DIM, unsigned SPACE_DIM=ELEMENT_DIM> class RandomDirectionCentreBasedDivisionRule : public AbstractCentreBasedDivisionRule<ELEMENT_DIM, SPACE_DIM> { private: friend class boost::serialization::access; /** * Serialize the object and its member variables. * * @param archive the archive * @param version the current version of this class */ template<class Archive> void serialize(Archive & archive, const unsigned int version) { archive & boost::serialization::base_object<AbstractCentreBasedDivisionRule<ELEMENT_DIM, SPACE_DIM> >(*this); } public: /** * Default constructor. */ RandomDirectionCentreBasedDivisionRule() { } /** * Empty destructor. */ virtual ~RandomDirectionCentreBasedDivisionRule() { } /** * Overridden CalculateCellDivisionVector() method. * * @param pParentCell The cell to divide * @param rCellPopulation The centre-based cell population * * @return the two daughter cell positions. */ virtual std::pair<c_vector<double, SPACE_DIM>, c_vector<double, SPACE_DIM> > CalculateCellDivisionVector(CellPtr pParentCell, AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>& rCellPopulation); }; #include "SerializationExportWrapper.hpp" EXPORT_TEMPLATE_CLASS_ALL_DIMS(RandomDirectionCentreBasedDivisionRule) #endif // RANDOMDIRECTIONCENTREBASEDDIVISIONRULE_HPP_
38.728155
129
0.781399
[ "object" ]
b43e9d3bb47d048d07982d8990632d71b55c1564
53,321
cpp
C++
hphp/runtime/vm/jit/relocation-arm.cpp
divinity76/hhvm
cfde9bb3d7d49740d0ca0228e2d714637b155a13
[ "PHP-3.01", "Zend-2.0" ]
9,491
2015-01-01T00:30:28.000Z
2022-03-31T20:22:11.000Z
hphp/runtime/vm/jit/relocation-arm.cpp
divinity76/hhvm
cfde9bb3d7d49740d0ca0228e2d714637b155a13
[ "PHP-3.01", "Zend-2.0" ]
4,796
2015-01-01T00:26:31.000Z
2022-03-31T01:09:05.000Z
hphp/runtime/vm/jit/relocation-arm.cpp
divinity76/hhvm
cfde9bb3d7d49740d0ca0228e2d714637b155a13
[ "PHP-3.01", "Zend-2.0" ]
2,126
2015-01-01T11:13:29.000Z
2022-03-28T19:58:15.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2017 Qualcomm Datacenter Technologies, Inc. | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/jit/relocation.h" #include "hphp/runtime/vm/jit/abi-arm.h" #include "hphp/runtime/vm/jit/align-arm.h" #include "hphp/runtime/vm/jit/asm-info.h" #include "hphp/runtime/vm/jit/cg-meta.h" #include "hphp/runtime/vm/jit/containers.h" #include "hphp/runtime/vm/jit/fixup.h" #include "hphp/runtime/vm/jit/ir-opcode.h" #include "hphp/runtime/vm/jit/service-requests.h" #include "hphp/runtime/vm/jit/smashable-instr.h" #include "hphp/runtime/vm/jit/smashable-instr-arm.h" #include "hphp/vixl/a64/macro-assembler-a64.h" namespace HPHP { namespace jit { namespace arm { using namespace vixl; namespace { TRACE_SET_MOD(mcg); ////////////////////////////////////////////////////////////////////// /* * See relocation.h for an overview. A note about adjusting for * relocation: for ARM, this includes the following * * PC Relative * ADR/ADRP - Builds PC relatative addresses. * B[.<cc>] (immediate) - Branch to a PC relative address. * BL (immediate) - Branch with link to a PC relative address. * LDR (literal) - Loads a literal from a PC relative address. * * Immediates * MOV/MOVK - Used to build up targets 16 bits at a time. * LDR (literal) - The literal loaded may be a target address. * * adjustCodeForRelocation must support updating live instructions. * For ARM, we can update a single instruction or a 64 bit literal * in the instruction stream atomically. We can't, however, update * multiple instructions atomically since there may be a thread * executing instructions within that range. Therefore, MOV/MOVK * instructions can't be adjusted for live ranges of instructions. * Any emitted code that uses MOV/MOVK and which must be adjusted * while live, should instead use LDR (literal). Smashables use this * approach; they embed a literal in the instruction stream which * can then be updated atomically. At the time of this writing, only * the vasm opcode (leap) produces a live region that must be updated, * and so it uses an approach with LDR (literal) instead of MOV/MOVK. */ ////////////////////////////////////////////////////////////////////// struct Patch { TCA destAddr; TCA srcTargetAddr; Instruction* src; }; using PatchList = std::vector<Patch>; using InstrSet = jit::hash_set<Instruction*>; struct JmpOutOfRange : std::exception {}; /* * Maintains various state during relocation. */ struct Env { explicit Env(RelocationInfo& rel, CodeBlock& srcBlock, CodeBlock& destBlock, TCA start, TCA end, CGMeta& meta, TCA* exitAddr, InstrSet& far) : rel(rel) , srcBlock(srcBlock) , destBlock(destBlock) , start(start) , end(end) , meta(meta) , exitAddr(exitAddr) , updateInternalRefs(false) , far(far) { if (exitAddr) *exitAddr = nullptr; } RelocationInfo& rel; CodeBlock& srcBlock; CodeBlock& destBlock; const TCA start, end; CGMeta& meta; TCA* exitAddr; bool updateInternalRefs; /* * Maintains a list of any instruction that failed to be adjusted because * it was too far. Failing to adjust will trigger a retry and that insruction * will be relocated to a PIC form. */ InstrSet& far; /* * If rewrites remove the need for certain pooled literals, they are added to * this set so they can be removed. */ InstrSet literalsToRemove; /* * Simple relocation just copies src instructions to dest instructions. * If a src instruction(s) are actually rewritten, then those src * instructions are tracked in this list. */ InstrSet rewrites; /* * Rewritten instruction sequences have no clear mapping to source addresses, * yet they may want to address parts of the range being relocated that were * relocated after they were rewritten. */ PatchList rewriteAdjust; }; ////////////////////////////////////////////////////////////////////// /* * Decodes all possible sequences generated by the macro assembler to Mov an * immediate into a register. If instr does not point to the start of such a * sequence, then 0 is returned. Otherwise target is set to the immediate, and * the length of the sequence in instructions is returned. */ size_t decodePossibleMovSequence(Instruction* instr, Instruction* end, uint64_t& target, uint32_t& rd) { if (instr->IsMovz()) { // 64 target = (uint64_t)instr->ImmMoveWide() << (16 * instr->ShiftMoveWide()); } else if (instr->IsMovn()) { // 32 or 64 target = ~((uint64_t)instr->ImmMoveWide() << (16 * instr->ShiftMoveWide())); if (!instr->SixtyFourBits()) { target &= (1UL << 32) - 1; } } else if (instr->IsLogicalImmediate() && // 32 or 64 bit orr instr->Rn() == kZeroRegCode) { target = instr->ImmLogical(); } else { // We did not detect the start of a mov sequence. return 0; } size_t length = 1; // We already decoded the first instruction above. rd = instr->Rd(); auto next = instr->NextInstruction(); while ((next < end && next->IsMovk() && (next->Rd() == rd)) || (next < end && next->IsNop())) { if (next->IsMovk()) { auto const shift = 16 * next->ShiftMoveWide(); auto const mask = 0xffffLL << shift; target &= ~mask; target |= (uint64_t)next->ImmMoveWide() << shift; } length++; next = next->NextInstruction(); } return length; } /* * Write a mov sequence to load `target` into `reg` starting at `destAddr`. * Returns false if the new sequence does not fit into `length` instructions. */ bool writeMovSequence(CodeBlock& cb, TCA destAddr, int length, TCA target, uint32_t reg) { bool ok = true; // Save the frontier for restoration below. auto savedFrontier = cb.frontier(); cb.setFrontier(destAddr); // Write the new mov/movk sequence. vixl::MacroAssembler a { cb }; auto const dst = vixl::Register(reg, 64); a.Mov(dst, target); // If the new sequence is longer than the original, then we must // gracefully fail. length -= (cb.frontier() - destAddr) >> kInstructionSizeLog2; if (length < 0) { ok = false; } // If the sequence is shorter, then pad with nops while (length > 0) { a.nop(); length--; } // Restore the frontier cb.setFrontier(savedFrontier); return ok; } /* * Check if an instruction uses a PC relative offset to encode a target. */ bool isPCRelative(Instruction* instr) { return instr->IsPCRelAddressing() || instr->IsLoadLiteral() || instr->IsCondBranchImm() || instr->IsUncondBranchImm() || instr->IsCompareBranch() || instr->IsTestBranch(); } /* * Write a PC relative instruction's, `instr`'s, offset to `target` - `from`. * If the new offset is not possible to encode in the instruction, this returns * false. Otherwise it updates the offset, and returns true. */ bool writePCRelative(Instruction* instr, Instruction* target, Instruction* from) { assertx(isPCRelative(instr)); auto const imm = static_cast<int64_t>(Instruction::Cast(target) - from); if ((instr->IsPCRelAddressing() && !is_int21(imm)) || (instr->IsLoadLiteral() && !is_int19(imm >> kInstructionSizeLog2)) || (instr->IsCondBranchImm() && !is_int19(imm >> kInstructionSizeLog2)) || (instr->IsUncondBranchImm() && !is_int26(imm >> kInstructionSizeLog2)) || (instr->IsCompareBranch() && !is_int19(imm >> kInstructionSizeLog2)) || (instr->IsTestBranch() && !is_int14(imm >> kInstructionSizeLog2))) { // This instruction cannot address such a distant address return false; } instr->SetImmPCOffsetTarget(Instruction::Cast(target), from); return true; } /* * Identifies all of the instruction words in a range which are embedded * literals. This set of literals is used during relocation and adjusting to * indicate that they should not be analyzed as instructions. */ InstrSet findLiterals(Instruction* start, Instruction* end) { InstrSet literals; for (auto instr = start; instr < end; instr = instr->NextInstruction()) { if (literals.count(instr)) continue; auto addLiteral = [&] (Instruction* lit) { if (lit >= start && lit < end) { literals.insert(lit); } }; if (instr->IsLoadLiteral()) { auto const la = Instruction::Cast(instr->LiteralAddress()); addLiteral(la); if (instr->Mask(LoadLiteralMask) == LDR_x_lit) { addLiteral(la->NextInstruction()); } } } return literals; } /* * A far JCC pattern is: * B.cc NEXT * LDR Rx, LITERAL_ADDR * BR Rx * NEXT: * * Note that the condition code is the inverse of the condition code that is * emitted if the JCC is not far (i.e., it's a single direct branch * instruction). */ constexpr auto kFarJccLen = 3 * kInstructionSize; TCA farJccTarget(TCA inst) { auto const b = Instruction::Cast(inst); auto const ldr = b->NextInstruction(); auto const br = ldr->NextInstruction(); auto const next = br->NextInstruction(); if (b->IsCondBranchImm() && b->ImmPCOffsetTarget() == next && ldr->IsLoadLiteral() && ldr->Mask(LoadLiteralMask) == LDR_w_lit && br->Mask(UnconditionalBranchToRegisterMask) == BR && br->Rn() == ldr->Rd()) { auto const target32 = *reinterpret_cast<uint32_t*>(ldr->LiteralAddress()); assertx((target32 & 3) == 0); return reinterpret_cast<TCA>(target32); } return nullptr; } /* * Returns a far JCC's original condition, which is inverted in the emitted * code pattern. */ ConditionCode farJccCond(TCA inst) { auto const b = Instruction::Cast(inst); assertx(b->IsCondBranchImm()); return arm::convertCC(InvertCondition(static_cast<Condition>(b->Bits(3, 0)))); } /* * This function attempts to optimize a "far jcc" pattern, i.e.: * B.<cc> (after) * LDR Reg (literal A) * BR Reg * (after) * * If the "literal A" target is within +-1MB, the condition is inverted and a * single JCC is emitted: * B.<neg(cc)> (literal A) * * Otherwise, if the "literal A" target is within +-128MB, the code will be * optimized to: * B.<cc> (after) * B (literal A) * (after) * * This function returns whether or not the code was optimized. */ bool optimizeFarJcc(Env& env, TCA srcAddr, TCA destAddr, size_t& srcCount, size_t& destCount) { auto const srcFrom = Instruction::Cast(srcAddr); auto const srcAddrActual = env.srcBlock.toDestAddress(srcAddr); auto const src = Instruction::Cast(srcAddrActual); if (env.meta.smashableLocations.count(srcAddr)) return false; if (env.far.count(src)) return false; if (env.end < srcAddr + kFarJccLen) return false; auto const target = farJccTarget(srcAddrActual); if (!target) return false; auto adjusted = env.rel.adjustedAddressAfter(target); if (!adjusted) adjusted = target; auto imm = static_cast<int64_t>(adjusted - destAddr) >> kInstructionSizeLog2; if (env.start <= adjusted && adjusted < env.end) { // adjusted still points in the source range. It will need to be adjusted // at the end of relocation. imm = static_cast<int64_t>(adjusted - srcAddr) >> kInstructionSizeLog2; } // NB: the imm offset was computed relative to destAddr, but the more general // case, which handles int26, uses imm-1 because of the extra instruction that // it requires. if (!is_int26(imm - 1)) return false; if (env.start <= adjusted && adjusted < env.end) { env.rewriteAdjust.emplace_back(Patch { destAddr, adjusted, src }); } env.literalsToRemove.insert( src->NextInstruction()->ImmPCOffsetTarget(srcFrom->NextInstruction())); vixl::MacroAssembler a { env.destBlock }; env.destBlock.setFrontier(destAddr); // This inverts the condition code for us. auto const cc = arm::convertCC(farJccCond(srcAddrActual)); if (is_int19(imm)) { a.b(imm, cc); } else { // Branch over the next instruction. const int nextImm = 2; a.b(nextImm, vixl::InvertCondition(cc)); // NB: the imm offset was computed relative to destAddr, but we emitted an // extra branch above, thus the -1 here. a.b(imm - 1); destCount++; } srcCount = kFarJccLen >> kInstructionSizeLog2; for (auto i = src; i < src + (srcCount << kInstructionSizeLog2); i = i->NextInstruction()) { env.rewrites.insert(i); } env.updateInternalRefs = true; FTRACE(3, "Relocated and optimized a far JCC at src {} with target {} to {}.\n", srcAddrActual, target, env.destBlock.toDestAddress(destAddr)); return true; } /* * A far JMP pattern is: * LDR x, LITERAL_ADDR * BR x */ constexpr auto kFarJmpLen = 2 * kInstructionSize; TCA farJmpTarget(TCA inst) { auto const ldr = Instruction::Cast(inst); auto const br = ldr->NextInstruction(); if (ldr->IsLoadLiteral() && ldr->Mask(LoadLiteralMask) == LDR_w_lit && br->Mask(UnconditionalBranchToRegisterMask) == BR && br->Rn() == ldr->Rd()) { auto const target32 = *reinterpret_cast<uint32_t*>(ldr->LiteralAddress()); assertx((target32 & 3) == 0); return reinterpret_cast<TCA>(target32); } return nullptr; } /* * This attempts to shrink Ldr, Br sequences to PC relative branches. * This returns true if it was able to shrink the the sequence, otherwise it * returns false. * * destCount, srcCount and rewrites are updated to reflect when an * instruction(s) is rewritten to a different instruction sequence. * env.literalsToRemove is updated to include any literals that are no long * used. */ bool optimizeFarJmp(Env& env, TCA srcAddr, TCA destAddr, size_t& srcCount, size_t& destCount) { auto const srcFrom = Instruction::Cast(srcAddr); auto const srcAddrActual = env.srcBlock.toDestAddress(srcAddr); auto const src = Instruction::Cast(srcAddrActual); if (env.meta.smashableLocations.count(srcAddr)) return false; if (env.meta.veneerAddrs.count(srcAddr)) return false; if (env.far.count(src)) return false; if (env.end < srcAddr + kFarJmpLen) return false; auto target = farJmpTarget(srcAddrActual); if (!target) return false; assertx(((uint64_t)target & 3) == 0); assertx(src->Mask(LoadLiteralMask) == LDR_w_lit); env.literalsToRemove.insert(src->ImmPCOffsetTarget(srcFrom)); // If adjusted is not found, the target may point forward in the range, and // not have a known destination address yet. We will make the jmp point back // to the source range. This should then be updated during address // adjustments. auto adjusted = env.rel.adjustedAddressAfter(target); if (!adjusted) adjusted = target; auto imm = static_cast<int64_t>(adjusted - destAddr) >> kInstructionSizeLog2; if (env.start <= adjusted && adjusted < env.end) { // adjusted still points in the source range. It will need to be adjusted // at the end of relocation. env.rewriteAdjust.emplace_back(Patch { destAddr, adjusted, src }); imm = static_cast<int64_t>(adjusted - srcAddr) >> kInstructionSizeLog2; } vixl::MacroAssembler a { env.destBlock }; env.destBlock.setFrontier(destAddr); destCount--; if (is_int26(imm)) { a.b(imm); destCount += 1; } else { auto const tmp = rVixlScratch0; a.SetScratchRegisters(vixl::NoReg, vixl::NoReg); a.Mov(tmp, adjusted); // Pad out to two instructions for adjustment later if ((env.destBlock.frontier() - destAddr) == kInstructionSize) { a.Nop(); } a.Br(tmp); a.SetScratchRegisters(rVixlScratch0, rVixlScratch1); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; } srcCount = kFarJmpLen >> kInstructionSizeLog2; for (auto i = src; i < src + (srcCount << kInstructionSizeLog2); i = i->NextInstruction()) { env.rewrites.insert(i); } env.updateInternalRefs = true; FTRACE(3, "Relocated and optimized far JMP at src {} with target {} to {}.\n", srcAddrActual, target, env.destBlock.toDestAddress(destAddr)); return true; } /* * Returns true if the source is a PC relative instruction. Relocates the * that instruction, adjusting the offsets in the instruction. If the new * offset cannot be encoded, then the instruction is changed into a multi- * instruction sequence, overwritting the original PC relative instruction * that was initially copied. The following are the PC relative instructions: * ADR/ADRP * LDR (literal) * B.<cc> (immediate) * B (immediate) * BL (immediate) * * destCount, srcCount and rewrites are updated to reflect when an * instruction(s) is rewritten to a different instruction sequence. */ bool relocatePCRelative(Env& env, TCA srcAddr, TCA destAddr, size_t& /*srcCount*/, size_t& destCount) { auto const srcFrom = Instruction::Cast(srcAddr); auto const destFrom = Instruction::Cast(destAddr); auto const srcAddrActual = env.srcBlock.toDestAddress(srcAddr); auto const destAddrActual = env.destBlock.toDestAddress(destAddr); auto const src = Instruction::Cast(srcAddrActual); auto const dest = Instruction::Cast(destAddrActual); if (!isPCRelative(src)) return false; auto target = reinterpret_cast<TCA>(src->ImmPCOffsetTarget(srcFrom)); // If the target is outside of the range of this relocation, // then update it. if (((target < env.start) || (target >= env.end)) && env.meta.fallthru != srcAddr) { /* * Calculate the new offset and determine if it can be encoded * in a PC relative instruciton or if it needs to be converted * to make use of an absolute target. * Note: Use the VIXL scratch registers when transforming. Their * scope is just a single macroassembler directive, whereas * the scope of rAsm is an entire vasm instruction. */ auto imm = static_cast<int64_t>(src->ImmPCOffsetTarget(srcFrom) - destFrom); bool isRelative = true; if (src->IsPCRelAddressing()) { if (!is_int21(imm) || env.far.count(src)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; auto const dst = vixl::Register(src->Rd(), 64); a.Mov(dst, src->ImmPCOffsetTarget(srcFrom)); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; isRelative = false; } } else if (src->IsLoadLiteral()) { imm >>= kInstructionSizeLog2; if (!is_int19(imm) || env.far.count(src)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; a.SetScratchRegisters(vixl::NoReg, vixl::NoReg); auto const dst = vixl::Register(src->Rd(), 64); auto const tmp = dst.Is(rVixlScratch0) ? rVixlScratch1 : rVixlScratch0; a.Mov(tmp, src->ImmPCOffsetTarget(srcFrom)); a.Ldr(dst, vixl::MemOperand(tmp)); a.SetScratchRegisters(rVixlScratch0, rVixlScratch1); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; isRelative = false; } } else if (src->IsCondBranchImm()) { imm >>= kInstructionSizeLog2; if (!is_int19(imm) || env.far.count(src)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; vixl::Label end; auto const cond = static_cast<Condition>(src->ConditionBranch()); auto const tmp = rVixlScratch0; a.SetScratchRegisters(vixl::NoReg, vixl::NoReg); a.B(&end, vixl::InvertCondition(cond)); a.Mov(tmp, src->ImmPCOffsetTarget(srcFrom)); a.Br(tmp); a.bind(&end); a.SetScratchRegisters(rVixlScratch0, rVixlScratch1); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; isRelative = false; } } else if (src->IsUncondBranchImm()) { // Handle both B and BL forms of UncondBranchImm. imm >>= kInstructionSizeLog2; if (!is_int26(imm) || env.far.count(src)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; a.SetScratchRegisters(vixl::NoReg, vixl::NoReg); auto const tmp = rVixlScratch0; a.Mov(tmp, src->ImmPCOffsetTarget(srcFrom)); assertx(src->Mask(UnconditionalBranchMask) == B || src->Mask(UnconditionalBranchMask) == BL); if (src->Mask(UnconditionalBranchMask) == BL) a.Blr(tmp); else a.Br(tmp); a.SetScratchRegisters(rVixlScratch0, rVixlScratch1); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; isRelative = false; } } else if (src->IsCompareBranch()) { imm >>= kInstructionSizeLog2; if (!is_int19(imm) || env.far.count(src)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; vixl::Label end; auto const rt = vixl::Register(src->Rt(), 64); auto const tmp = rVixlScratch0; a.SetScratchRegisters(vixl::NoReg, vixl::NoReg); if (src->Mask(CompareBranchMask) == CBZ_x) { a.Cbnz(rt, &end); } else { a.Cbz(rt, &end); } a.Mov(tmp, src->ImmPCOffsetTarget(srcFrom)); a.Br(tmp); a.bind(&end); a.SetScratchRegisters(rVixlScratch0, rVixlScratch1); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; isRelative = false; } } else if (src->IsTestBranch()) { imm >>= kInstructionSizeLog2; if (!is_int14(imm) || env.far.count(src)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; vixl::Label end; auto const bit_pos = src->ImmTestBranchBit40(); auto const rt = vixl::Register(src->Rt(), 64); auto const tmp = rVixlScratch0; a.SetScratchRegisters(vixl::NoReg, vixl::NoReg); if (src->Mask(TestBranchMask) == TBZ) { a.Tbnz(rt, bit_pos, &end); } else { a.Tbz(rt, bit_pos, &end); } a.Mov(tmp, src->ImmPCOffsetTarget(srcFrom)); a.Br(tmp); a.bind(&end); a.SetScratchRegisters(rVixlScratch0, rVixlScratch1); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; isRelative = false; } } // Update offset if it was NOT converted from relative to absolute if (isRelative) { dest->SetImmPCOffsetTarget(src->ImmPCOffsetTarget(srcFrom), destFrom); } else { // Otherwise it was rewritten to absolute, and this // internal reference must be updated later. env.rewrites.insert(src); env.updateInternalRefs = true; } } // Update the exitAddr if it was requested for this translation. if ((src->IsCondBranchImm() || src->IsUncondBranchImm() || src->IsCompareBranch() || src->IsTestBranch()) && env.exitAddr) { *env.exitAddr = target; } return true; } /* * Returns true if the instruction sequence builds up an absolute * immediate via a MOV/MOVK and can be replaced with a single PC * relative instruction. The following instruction sequences are supported: * MOV/MOVK, LDR to LDR literal * MOV/MOVK, BR<L> to B<L> * MOV/MOVK absolute to ADR * * destCount, srcCount and rewrites are updated to reflect when an * instruction(s) is rewritten to a different instruction sequence. */ bool relocateImmediate(Env& env, TCA srcAddr, TCA destAddr, size_t& srcCount, size_t& destCount) { auto const srcAddrActual = env.srcBlock.toDestAddress(srcAddr); auto const endAddrActual = env.srcBlock.toDestAddress(env.end); auto const destAddrActual = env.destBlock.toDestAddress(destAddr); auto const src = Instruction::Cast(srcAddrActual); auto const end = Instruction::Cast(endAddrActual); auto const dest = Instruction::Cast(destAddrActual); // Don't turn non address immediates into PC relative instructions. PC // relative instructions are considered to be addresses by other parts of // the relocator. if (!env.meta.addressImmediates.count(srcAddr)) return false; uint64_t target; uint32_t rd; auto const length = decodePossibleMovSequence(src, end, target, rd); if (!length) return false; auto next = src + length * kInstructionSize; auto adjusted = env.rel.adjustedAddressAfter(reinterpret_cast<TCA>(target)); if (!adjusted) { adjusted = reinterpret_cast<TCA>(target); } auto imm = static_cast<int64_t>(Instruction::Cast(adjusted) - dest); bool isAbsolute = true; /* * If the next instruction after a sequence of MOV/MOVK uses the * target, see if the entire sequence can be converted to a * single PC relative instruction. Supported transformations include: * MOV/MOVK, LDR to LDR literal * MOV/MOVK, BR<L> to B<L> * MOV/MOVK absolute to ADR */ if (next->Mask(LoadStoreUnsignedOffsetMask) == LDR_x_unsigned && next->Rn() == rd && !next->ImmShiftLS()) { // Only transform if the MOV/MOVK sequence def'd a vixl scratch or Vasm // scratch register. Otherwise we run the risk of not def'ing a live // register. auto const tmp = vixl::Register(rd, 64); if (tmp.Is(rVixlScratch0) || tmp.Is(rVixlScratch1) || tmp.Is(rAsm)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; vixl::Label target; auto const dst = vixl::Register(next->Rd(), 64); a.Ldr(dst, &target); auto savedFrontier = env.destBlock.frontier(); env.destBlock.setFrontier(adjusted); a.bind(&target); env.destBlock.setFrontier(savedFrontier); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; srcCount = ((next - src) >> kInstructionSizeLog2) + 1; isAbsolute = false; // Add range of source instructions to rewrites (MOV/MOVKs/LDR) for (auto i = src; i < next->NextInstruction(); i = i->NextInstruction()) { env.rewrites.insert(i); } } } else if (next->IsUncondBranchReg() && next->Rn() == rd) { imm >>= kInstructionSizeLog2; // Only transform if the MOV/MOVK sequence def'd a vixl scratch or Vasm // scratch register. Otherwise we run the risk of not def'ing a live // register. auto const dst = vixl::Register(rd, 64); if (dst.Is(rVixlScratch0) || dst.Is(rVixlScratch1) || dst.Is(rAsm)) { if (is_int26(imm)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; if (next->Mask(UnconditionalBranchToRegisterMask) == BR) { a.b(imm); } else { a.bl(imm); } destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; srcCount = ((next - src) >> kInstructionSizeLog2) + 1; isAbsolute = false; // Add range of source instructions to rewrites (MOV/MOVKs/B<L>) // Note: next points past the MOV/MOVK sequence to the B<L>. We're // replacing all of them so iterate past next for the B<L>. for (auto i = src; i < next->NextInstruction(); i = i->NextInstruction()) { env.rewrites.insert(i); } } } } else { if (is_int21(imm)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; auto const dst = vixl::Register(rd, 64); a.adr(dst, imm); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; srcCount = (next - src) >> kInstructionSizeLog2; isAbsolute = false; // Add range of source instructions to rewrites (MOV/MOVKs) for (auto i = src; i < next; i = i->NextInstruction()) { env.rewrites.insert(i); } } } // If we did NOT convert to a PC relative instruction sequence, then // see if we need to adjust the target of the mov/movk sequence now. if (isAbsolute) { if (adjusted != reinterpret_cast<TCA>(target)) { env.destBlock.setFrontier(destAddr); destCount--; vixl::MacroAssembler a { env.destBlock }; auto const dst = vixl::Register(rd, 64); a.Mov(dst, adjusted); destCount += (env.destBlock.frontier() - destAddr) >> kInstructionSizeLog2; srcCount = (next - src) >> kInstructionSizeLog2; // Add range of source instructions to rewrites (MOV/MOVKs) for (auto i = src; i < next; i = i->NextInstruction()) { env.rewrites.insert(i); } // The mov sequence emitted above might be a different length than before. env.updateInternalRefs = true; } else if ((reinterpret_cast<TCA>(target) >= srcAddr) && (reinterpret_cast<TCA>(target) < env.end)) { // Otherwise if the target wasn't adjusted because it's an addresses // within this translation that we have yet relocated, then mark the // internal ref to be updated later. env.updateInternalRefs = true; } } else { // Otherwise we rewrote the instruction sequence which can trigger internal // reference to need updating later. env.updateInternalRefs = true; } return true; } size_t relocateImpl(Env& env) { auto destStart = env.destBlock.frontier(); size_t asmCount{0}; /* * These sets track instruction words within the source sequence which should * be ignored during the analysis. Literals are copied and ignored even though * they sometimes coincedently hold valid encodings of instructions. Any * source instructions which are transformed should also be ignored when * adjusting internal refs since they have correct PC relative offsets and * immediate already. */ try { // Find the literals embedded within the range InstrSet literals = findLiterals(Instruction::Cast(env.srcBlock.toDestAddress(env.start)), Instruction::Cast(env.srcBlock.toDestAddress(env.end))); // Relocate each instruction to the destination. size_t srcCount, destCount, alignCount; TCA protectedStart = nullptr, protectedEnd = nullptr; for (auto srcAddr = env.start; srcAddr < env.end; srcAddr += srcCount << kInstructionSizeLog2) { auto const srcPtr = env.srcBlock.toDestAddress(srcAddr); auto const srcFrom = Instruction::Cast(srcAddr); auto const src = Instruction::Cast(srcPtr); srcCount = 1; destCount = 1; alignCount = 0; auto destAddr = env.destBlock.frontier(); // Align the frontier to follow any potential aligment constraints. auto af = env.meta.alignments.equal_range(srcAddr); while (af.first != af.second) { auto const alignPair = af.first->second; auto const alignInfo = alignment_info(alignPair.first); // We want to prevent resizing of intstruction that are protected by // this alignment constraint. Save the range of bytes that should // be protected. auto const low = srcAddr + alignInfo.offset; auto const hi = srcAddr + alignInfo.nbytes; assertx(low < hi); if (!protectedStart || protectedStart > low) protectedStart = low; if (!protectedEnd || protectedEnd < hi) protectedEnd = hi; // The adjust metadata for relocation phase will handle updating the // alignment constraints. TCA tmp = env.destBlock.frontier(); align(env.destBlock, nullptr, alignPair.first, alignPair.second); auto const adjustment = env.destBlock.frontier() - tmp; if (adjustment) { destAddr += adjustment; alignCount += adjustment; // Padding was added we should update internal references since PC // relative addresses will be skewed. env.updateInternalRefs = true; } ++af.first; } auto const preserveAlignment = protectedStart <= srcAddr && srcAddr < protectedEnd; // Initially copy the instruction word env.destBlock.bytes(kInstructionSize, env.srcBlock.toDestAddress(srcAddr)); // If it's not a literal, and we don't need to satisfy an aligment // constraint, then attempt any special relocations. if (!literals.count(src) && !preserveAlignment) { // Remove nops that are not necessary for alignment constraints. if (src->IsNop()) { destCount = 0; env.updateInternalRefs = true; } // Relocate functions are needed for correctness, while optimize // functions will attempt to improve instruction sequences. optimizeFarJcc(env, srcAddr, destAddr, srcCount, destCount) || optimizeFarJmp(env, srcAddr, destAddr, srcCount, destCount) || relocatePCRelative(env, srcAddr, destAddr, srcCount, destCount) || relocateImmediate(env, srcAddr, destAddr, srcCount, destCount); } if (!preserveAlignment && env.literalsToRemove.erase(srcFrom)) { destCount = 0; env.updateInternalRefs = true; } // If we just copied the Ldr of a mcprep instruction. Flag internal refs // to get updated so its immediate can reflect its new location. if (env.meta.addressImmediates.count(reinterpret_cast<TCA>( ~reinterpret_cast<uintptr_t>(srcAddr)))) { assertx(possiblySmashableMovq(srcPtr)); env.updateInternalRefs = true; } // Address immediates may be internal references that need updating. if (env.meta.addressImmediates.count(srcAddr)) { auto updateInternalRefsCheck = [&](uintptr_t addr) { if (env.start <= reinterpret_cast<TCA>(addr) && reinterpret_cast<TCA>(addr) < env.end) { env.updateInternalRefs = true; } }; if (src->IsLoadLiteral()) { auto const addr = src->LiteralAddress(); assertx(env.srcBlock.toDestAddress(env.start) <= addr && addr < env.srcBlock.toDestAddress(env.end)); if (src->Mask(LoadLiteralMask) == LDR_w_lit) { updateInternalRefsCheck(*reinterpret_cast<uint32_t*>(addr)); } else { updateInternalRefsCheck(*reinterpret_cast<uintptr_t*>(addr)); } } else { uint32_t rd; uint64_t target; if (decodePossibleMovSequence(src, Instruction::Cast(env.end), target, rd)) { updateInternalRefsCheck(target); } } } if (srcAddr == env.start) { /* * For the start of the range, we only want to overwrite the "after" * address (since the "before" address could belong to the previous * tracelet, which could be being relocated to a completely different * address. recordRange will do that for us, so just make sure we * have the right address setup. */ destStart = destAddr; } else { env.rel.recordAddress(srcAddr, destAddr - alignCount, alignCount); } // Update the destAddr and reset the frontier destAddr += destCount << kInstructionSizeLog2; assertx(destAddr <= env.destBlock.frontier()); env.destBlock.setFrontier(destAddr); asmCount += destCount; } // while (src != env.end) // Remap fallthru. if (env.meta.fallthru) { auto const srcAddr = *env.meta.fallthru; if (env.srcBlock.contains(srcAddr)) { auto const src = Instruction::Cast(env.srcBlock.toDestAddress(srcAddr)); env.rewrites.insert(src); // We are handling adjustment here. auto const destAddrBefore = env.rel.adjustedAddressBefore(srcAddr); auto const destAddr = env.rel.adjustedAddressAfter(srcAddr); auto const destFrom = Instruction::Cast(destAddr); auto const dest = Instruction::Cast(env.destBlock.toDestAddress(destAddr)); assertx(dest->IsUncondBranchImm()); if (Instruction::Cast(destAddr)->NextInstruction() == Instruction::Cast(env.destBlock.frontier())) { // Remove the fallthru jmp and update mapping. There are no literals // or veneers, so we do not need a jump to fallthru properly. env.destBlock.setFrontier(destAddrBefore); env.rel.recordAddress(srcAddr, destAddrBefore - kInstructionSize, 0); env.meta.fallthru.reset(); } else { // Adjust the fallthru jmp. auto const success = writePCRelative(dest, Instruction::Cast(env.destBlock.frontier()), destFrom); always_assert(success); } } } env.rel.recordRange(env.start, env.end, destStart, env.destBlock.frontier()); /* * We know literals to remove will be empty because during relocation any * literal that is removed should be able to be skipped over. An LDR * loading a literal that is under an alignment constraint must also be * under an alignment constraint. This means the instruction sequence * cannot be optimized, and the literal will never be removed. */ always_assert(env.literalsToRemove.empty()); bool ok = true; /* * When rewriting instruction sequences the addresses of points later in * the range are unknown. This patches in adjusted addresses now. */ for (auto const& pl : env.rewriteAdjust) { auto const destFrom = Instruction::Cast(pl.destAddr); auto const dest = Instruction::Cast(env.destBlock.toDestAddress(pl.destAddr)); auto const src = pl.src; auto const adjusted = env.rel.adjustedAddressAfter(pl.srcTargetAddr); if (adjusted) { if (isPCRelative(dest)) { if (!writePCRelative(dest, Instruction::Cast(adjusted), destFrom)) { FTRACE(3, "relocate: PC relative instruction at {} has", "internal reference 0x{:08x} which can't be adjusted.", "Will try again and far.\n", (uint64_t)dest, adjusted); env.far.insert(src); ok = false; } } uint64_t target; uint32_t rd; auto const destEnd = Instruction::Cast(env.destBlock.frontier()); if (int length = decodePossibleMovSequence(dest, destEnd, target, rd)) { if (!writeMovSequence(env.destBlock, pl.destAddr, length, adjusted, rd)) { env.far.insert(src); ok = false; } } } } /* * Finally update any internal refs if needed. This indicates that the * range of instructions grew/shrank and therefore the internal refs * may be off. */ if (env.updateInternalRefs) { for (auto srcAddr = env.start; srcAddr < env.end; srcAddr += kInstructionSize) { auto const srcFrom = Instruction::Cast(srcAddr); auto const src = Instruction::Cast(env.srcBlock.toDestAddress(srcAddr)); // Adjust this instruction if A) it wasn't written from a pc relative // instruction to an absolute (or vice-versa) and B) it isn't a literal. if (!env.rewrites.count(src) && !literals.count(src)) { auto const destAddr = env.rel.adjustedAddressAfter(srcAddr); auto const destFrom = Instruction::Cast(destAddr); auto const dest = Instruction::Cast(env.destBlock.toDestAddress(destAddr)); /* * PC Relative * ADR/ADRP * LDR (literal) * B[.<cc>] (immediate) * BL (immediate) * CB[N]Z * TB[N]Z */ if (isPCRelative(src)) { auto const old_target = reinterpret_cast<TCA>(src->ImmPCOffsetTarget(srcFrom)); auto const adjusted_target = env.rel.adjustedAddressAfter(old_target); auto const new_target = Instruction::Cast(adjusted_target ? adjusted_target : old_target); /* * Calculate the new offset and update. At this stage, we've already * relocated and now we're just adjusting an internal reference. * Therefore we can't change relative instructions to absolute, as * that would change the code size. Our only recourse is to mark it * as far and then retry the entire relocation again. */ if (!writePCRelative(dest, new_target, destFrom)) { FTRACE(3, "relocate: PC relative instruction at {} has", "internal reference 0x{:08x} which can't be adjusted.", "Will try again and far.\n", (uint64_t)src, new_target); env.far.insert(src); ok = false; } } /* * Immediates * LDR (literal) * MOV/MOVK */ if (src->IsLoadLiteral()) { assertx(dest->IsLoadLiteral()); auto const addr = dest->LiteralAddress(); if (src->Mask(LoadLiteralMask) == LDR_w_lit) { auto target = *reinterpret_cast<uint32_t*>(addr); auto adjusted = env.rel.adjustedAddressAfter(reinterpret_cast<TCA>(target)); if (adjusted) { if (env.meta.addressImmediates.count(srcAddr)) { patchTarget32(addr, adjusted); } else { FTRACE(3, "relocate: instruction at {} has immediate 0x{} " "which looks like an address that needs relocating\n", srcAddr, target); } } } else { auto const target = *reinterpret_cast<uintptr_t*>(addr); auto const adjusted = [&] () -> uintptr_t { if (env.meta.addressImmediates.count( reinterpret_cast<TCA>( ~reinterpret_cast<uintptr_t>(srcAddr)))) { auto munge = [] (TCA addr) { return (reinterpret_cast<uintptr_t>(addr) << 1) | 1; }; // An mcprep smashableMovq. During live relocation, // the target will probably have been smashed before // we get here. In that case, its no longer encoding a // tc address, and we don't need to do anything. if (target & 1) { always_assert(target == munge(srcAddr)); return munge(destAddr); } } else { auto const ret = reinterpret_cast<uintptr_t>( env.rel.adjustedAddressAfter(reinterpret_cast<TCA>(target)) ); if (ret && env.meta.addressImmediates.count(srcAddr)) { return ret; } else if (ret) { FTRACE(3, "relocate: instruction at {} has immediate 0x{} " "which looks like an address that needs " "relocating\n", srcAddr, target); } } return 0; }(); if (adjusted) { *reinterpret_cast<uintptr_t*>(addr) = adjusted; } } } uint64_t target; uint32_t rd; if (int length = decodePossibleMovSequence(src, Instruction::Cast(env.end), target, rd)) { // Adjust the mov/movk sequence if necessary auto adjusted = env.rel.adjustedAddressAfter( reinterpret_cast<TCA>(target) ); if (adjusted && env.meta.addressImmediates.count(srcAddr)) { if (!writeMovSequence(env.destBlock, destAddr, length, adjusted, rd)) { ok = false; env.far.insert(src); } } else if (adjusted) { FTRACE(3, "relocate: instruction at {} has immediate 0x{} " "which looks like an address that needs relocating\n", srcAddr, target); } } } } } if (!ok) { throw JmpOutOfRange(); } env.rel.markAddressImmediates(env.meta.addressImmediates); } catch (...) { env.rel.rewind(env.start, env.end); env.destBlock.setFrontier(destStart); throw; } env.destBlock.sync(destStart); return asmCount; } ////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////// void adjustInstruction(RelocationInfo& rel, Instruction* instr, Instruction* end, bool live) { /* * PC Relative * ADR/ADRP * LDR (literal) * B[.<cc>] (immediate) * BL (immediate) * CB[N]Z * TB[N]Z */ if (isPCRelative(instr)) { auto const target = reinterpret_cast<TCA>(instr->ImmPCOffsetTarget()); auto const adjusted = rel.adjustedAddressAfter(target); if (adjusted) { /* * We're adjusting, not relocating. So if the offset can't be * encoded, our only recourse is to assert. */ if (!writePCRelative(instr, Instruction::Cast(adjusted), instr)) { always_assert_flog(false, "Can't adjust PC relative instruction. The " "offset is too large.\n"); } // Sync the updated instruction. auto const begin = reinterpret_cast<TCA>(instr); DataBlock::syncDirect(begin, begin + kInstructionSize); } } /* * Immediates * LDR (literal) * MOV/MOVK * * Note: We can't atomically rewrite multiple instructions, so we * assert when attempting to adjust MOV/MOVK when live. */ if (instr->IsLoadLiteral()) { if (instr->Mask(LoadLiteralMask) == LDR_w_lit) { auto addr = reinterpret_cast<uint32_t*>(instr->LiteralAddress()); auto target = *addr; auto adjusted = rel.adjustedAddressAfter(reinterpret_cast<TCA>(target)); if (adjusted) { if (rel.isAddressImmediate(reinterpret_cast<TCA>(instr))) { patchTarget32(reinterpret_cast<TCA>(addr), adjusted); } else { FTRACE(3, "relocate: instruction at {} has immediate 0x{} " "which looks like an address that needs relocating\n", reinterpret_cast<TCA>(instr), target); } } } else { auto addr = reinterpret_cast<TCA*>(instr->LiteralAddress()); auto target = *addr; auto adjusted = rel.adjustedAddressAfter(target); if (adjusted) { if (rel.isAddressImmediate(reinterpret_cast<TCA>(instr))) { patchTarget64(reinterpret_cast<TCA>(addr), adjusted); } else { FTRACE(3, "relocate: instruction at {} has immediate 0x{} " "which looks like an address that needs relocating\n", reinterpret_cast<TCA>(instr), target); } } } } uint64_t target; uint32_t rd; if (size_t length = decodePossibleMovSequence(instr, end, target, rd)) { auto adjusted = (uint64_t)rel.adjustedAddressAfter( reinterpret_cast<TCA>(target) ); if (adjusted && rel.isAddressImmediate(reinterpret_cast<TCA>(instr))) { always_assert_flog(!live, "Can't adjust MOV/MOVK for a live region.\n"); // Create a temporary CodeBlock over the mov/movk sequence CodeBlock movBlock; auto const movStart = reinterpret_cast<TCA>(instr); movBlock.init(movStart, length << kInstructionSizeLog2, "mov/movk"); // Write the new mov/movk sequence vixl::MacroAssembler a { movBlock }; auto const dst = vixl::Register(rd, 64); a.Mov(dst, adjusted); // If the sequence is shorter, then pad with nops length -= (movBlock.frontier() - movStart) >> kInstructionSizeLog2; while (length > 0) { a.nop(); length--; } // Sync the region movBlock.sync(); } else if (adjusted) { FTRACE(3, "relocate: instruction at {} has immediate 0x{} " "which looks like an address that needs relocating\n", reinterpret_cast<TCA>(instr), target); } } } void adjustInstructions(RelocationInfo& rel, Instruction* start, Instruction* end, bool live) { // Find the literals InstrSet literals = findLiterals(start, end); // Adjust the instructions for (auto instr = start; instr < end; instr = instr->NextInstruction()) { if (!literals.count(instr)) { adjustInstruction(rel, instr, end, live); } } } ////////////////////////////////////////////////////////////////////// /* * This should be called after calling relocate on all relevant ranges. It * will adjust all references into the original src ranges to point into the * corresponding relocated ranges. */ void adjustForRelocation(RelocationInfo& rel) { for (const auto& range : rel.srcRanges()) { adjustForRelocation(rel, range.first, range.second); } } /* * This will update a single range that might refer to relocated code (such * as the cold code corresponding to a tracelet). The range being adjusted * may or may not have been relocated. */ void adjustForRelocation(RelocationInfo& rel, TCA srcStart, TCA srcEnd) { auto start = Instruction::Cast(rel.adjustedAddressAfter(srcStart)); auto end = Instruction::Cast(rel.adjustedAddressBefore(srcEnd)); if (!start) { start = Instruction::Cast(srcStart); end = Instruction::Cast(srcEnd); } else { always_assert(end); } adjustInstructions(rel, start, end, false); } /* * Adjust potentially live references that point into the relocated area. Must * not be called until its safe to run the relocated code. */ void adjustCodeForRelocation(RelocationInfo& rel, CGMeta& meta) { for (auto codePtr : meta.codePointers) { if (auto adjusted = rel.adjustedAddressAfter(*codePtr)) { *codePtr = adjusted; } } } void findFixups(TCA start, TCA end, CGMeta& meta) { for (auto instr = Instruction::Cast(start); instr < Instruction::Cast(end); instr = instr->NextInstruction()) { // If instruction is a call if ((instr->Mask(UnconditionalBranchMask) == BL) || (instr->Mask(UnconditionalBranchToRegisterMask) == BLR)) { if (auto fixup = FixupMap::findFixup(start)) { meta.fixups.emplace_back(start, *fixup); } if (auto ct = getCatchTrace(start)) { meta.catches.emplace_back(start, *ct); } } } } /* * Relocate code in the range start, end into dest, and record * information about what was done to rel. * On exit, internal references (references into the source range) * will have been adjusted (ie they are still references into the * relocated code). External code references continue to point to * the same address as before relocation. */ size_t relocate(RelocationInfo& rel, CodeBlock& destBlock, TCA start, TCA end, CodeBlock& srcBlock, CGMeta& meta, TCA* exitAddr, AreaIndex) { InstrSet far; while (true) { try { Env env(rel, srcBlock, destBlock, start, end, meta, exitAddr, far); return relocateImpl(env); } catch (JmpOutOfRange& j) { } } } ////////////////////////////////////////////////////////////////////// }}}
36.174355
80
0.610622
[ "vector", "transform" ]
b4407646d447cd6ac3929ff1de3d5bdfbcb2726b
8,262
hpp
C++
envi-tools/include/envitools/ENVI.hpp
viscenter/envi-tools
3cd2c15b36daf543e4fdab17ca6df3cf577f38c9
[ "BSD-3-Clause" ]
null
null
null
envi-tools/include/envitools/ENVI.hpp
viscenter/envi-tools
3cd2c15b36daf543e4fdab17ca6df3cf577f38c9
[ "BSD-3-Clause" ]
2
2017-03-22T20:50:59.000Z
2017-04-24T14:39:36.000Z
envi-tools/include/envitools/ENVI.hpp
viscenter/envi-tools
3cd2c15b36daf543e4fdab17ca6df3cf577f38c9
[ "BSD-3-Clause" ]
1
2017-01-25T14:52:14.000Z
2017-01-25T14:52:14.000Z
#pragma once #include <array> #include <exception> #include <fstream> #include <iostream> #include <string> #include <boost/filesystem.hpp> #include <opencv2/core.hpp> namespace envitools { /** @class ENVI @author Seth Parker @date 02/07/2017 @brief ENVI file interface Reads ENVI files and streams band information from disk. More information at: <a href="https://www.harrisgeospatial.com/docs/ENVIHeaderFiles.html">ENVI Header Files</a> @ingroup envitools @ingroup io */ class ENVI { public: /** @brief Fundamental datatype options */ enum class DataType { Unsigned8 = 1, Signed16, Signed32, Float32, Float64, Complex32, Complex64, Unsigned16 = 12, Unsigned32, Signed64, Unsigned64 }; /** @brief Endianness options */ enum class Endianness { Little = 0, Big }; /** * @brief Band interleave options * * Band interleave describes the ordering of pixel information inside of * the image data file. This option, along with the ENVI::DataType, * determines the exact byte position of any arbitrary pixel. * * More information at: * <a href="https://www.harrisgeospatial.com/docs/enviimagefiles.html">ENVI * Image Files</a> * * <b>Band Sequential</b>: * The most direct interleave option. Every band image is written * sequentially into the data file. * * <b>Band-interleaved-by-pixel</b>: * The first pixel of each band is written in order, followed by the * second pixel of each band, and so on. * * <b>Band-interleaved-by-line</b>: * The first line of each band is written in order, followed by the * second line of each band, and so on. * * @image html ENVI-BSQ.png height=500px * @image html ENVI-BIP.png height=500px * @image html ENVI-BIL.png height=500px * @image latex ENVI-BSQ.eps height=2in * @image latex ENVI-BIP.eps height=2in * @image latex ENVI-BIL.eps height=2in * */ enum class Interleave { BandSequential, BandByPixel, BandByLine }; /** @brief Data access mode options * * Determines whether the data file stream will remain open after a call to * getBand(). * * <b>CloseOnComplete (default)</b>: The data file stream will be * immediately closed. * * <b>KeepOpen</b>: The data file stream will remain open. * */ enum class AccessMode { CloseOnComplete, KeepOpen }; /** @brief Shared pointer type */ using Pointer = std::shared_ptr<ENVI>; /** @name Constructors */ ///@{ /** @brief Load from ENVI header file */ explicit ENVI(const boost::filesystem::path& header) { parse_header_(header); find_data_file_(header); } /** @brief Load from ENVI header and data files */ explicit ENVI( const boost::filesystem::path& header, boost::filesystem::path data) : dataPath_{std::move(data)} { parse_header_(header); } /** @copybrief explicit ENVI(const boost::filesystem::path& header) */ static Pointer New(const boost::filesystem::path& header) { return std::make_shared<ENVI>(header); } /** @copybrief explicit ENVI(const boost::filesystem::path&, * boost::filesystem::path) */ static Pointer New( const boost::filesystem::path& header, boost::filesystem::path data) { return std::make_shared<ENVI>(header, data); } ///@} /** @name Data Access */ ///@{ /** @brief Read specific band from ENVI file */ cv::Mat getBand(int b); /** @brief Get wavelength of band as string */ std::string getWavelength(int b) { return wavelengths_[b]; } /** @brief Get list of wavelengths */ std::vector<std::string> getWavelengths() { return wavelengths_; } /** @brief Set the data access mode * * If set to ENVI::AccessMode::KeepOpen, the file stream will attempt to * remain open after a call to getBand(). This can slightly improve * performance when repeatedly accessing the data file. * * @warning If using the KeepOpen access mode, it's good practice to call * closeFile() when access to the data file is no longer needed. */ void setAccessMode(AccessMode m) { accessMode_ = m; } /** @brief Close the data file stream if it's open */ void closeFile(); ///@} /** @name Metadata */ ///@{ /** @brief Get the ENVI::DataType of the file */ DataType datatype() { return type_; } /** @brief Get the ENVI::Endianness of the file */ Endianness endianness() { return endian_; } /** @brief Get the ENVI::Interleave of the file */ Interleave interleave() { return interleave_; } /** @brief Get the width of the band images */ int width() { return samples_; } /** @brief Get the height of the band images */ int height() { return lines_; } /** @brief Get the number of band images */ int bands() { return bands_; } ///@} /** @name Debug */ ///@{ /** @brief Print information parsed from header * * Prints to std::cerr. For debug purposes only. */ void printHeader(); ///@} private: /** @brief Parse an ENVI header */ void parse_header_(const boost::filesystem::path& header); /** @brief Attempt to find ENVI data file relative to header */ void find_data_file_(const boost::filesystem::path& header); /** * @brief Return the byte position of pixel (x, y, band) in the ENVI data * file * * Position is dependent upon ENVI::Interleave and ENVI::DataType of the * ENVI file */ uint64_t pos_of_elem_(uint64_t band, uint64_t y, uint64_t x, uint64_t size); /** ENVI file's fundamental datatype */ DataType type_{DataType::Float32}; /** ENVI file's endianess */ Endianness endian_{Endianness::Big}; /** ENVI file's band ordering */ Interleave interleave_{Interleave::BandSequential}; /** Number of samples for each band (aka image width) */ int samples_{0}; /** Number of lines for each band (aka image height) */ int lines_{0}; /** Number of bands in ENVI file */ int bands_{0}; /** Path to ENVI data file */ boost::filesystem::path dataPath_; /** File stream for repeated access */ std::ifstream ifs_; /** Open the filestream if it's not already open */ void open_file_(); /** Current data access mode */ AccessMode accessMode_{AccessMode::CloseOnComplete}; /** List of parsed wavelengths */ std::vector<std::string> wavelengths_; /** * @brief Read a specific band image from the ENVI data file * * Image is returned with its native bit depth. * * @tparam T Fundamental type of pixel data * @param b ID number of band to extract * @return Band image with pixel type T */ template <typename T> cv::Mat get_band_(int b) { // Open the filestream open_file_(); // Setup output Mat cv::Mat_<T> output(lines_, samples_); // Size of each element auto length = sizeof(T); // Loop over every pixel in that band T value; std::ifstream::streampos pos; for (int y = 0; y < lines_; y++) { for (int x = 0; x < samples_; x++) { // Seek to the correct position in the data file pos = pos_of_elem_( static_cast<uint64_t>(b), static_cast<uint64_t>(y), static_cast<uint64_t>(x), length); ifs_.seekg(pos); // Read the bytes ifs_.read(reinterpret_cast<char*>(&value), length); if (ifs_.fail()) { auto msg = "Only read " + std::to_string(ifs_.gcount()) + " bytes. Expected: " + std::to_string(length); throw std::runtime_error(msg); } // Assign to the mat output.template at<T>(y, x) = value; } } if (accessMode_ == AccessMode::CloseOnComplete) { closeFile(); } return output; } }; }
29.612903
80
0.600944
[ "vector" ]
b4452f5145909002c7d79cfd278f84da346bbd22
792
cpp
C++
head/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
36
2015-01-13T19:34:04.000Z
2022-03-07T22:22:15.000Z
head/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
7
2015-10-20T19:05:01.000Z
2021-11-13T14:55:47.000Z
head/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
18
2015-04-23T20:59:52.000Z
2021-11-18T20:06:39.000Z
//===-- AArch64TargetObjectFile.cpp - AArch64 Object Info -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file deals with any AArch64 specific requirements on object files. // //===----------------------------------------------------------------------===// #include "AArch64TargetObjectFile.h" using namespace llvm; void AArch64LinuxTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM) { TargetLoweringObjectFileELF::Initialize(Ctx, TM); InitializeELF(TM.Options.UseInitArray); }
31.68
80
0.530303
[ "object" ]
b44564fa0d97cfef63ecdbae6e4d7f7ff3838f99
118,035
cpp
C++
src/objs/BIDR.cpp
nasa-jpl/Cassini_RADAR_Software
93a5be34d013c2913cf74f06e01c59b625bb4a17
[ "Apache-2.0" ]
4
2021-08-12T23:55:41.000Z
2022-02-23T03:32:46.000Z
src/objs/BIDR.cpp
nasa-jpl/Cassini_RADAR_Software
93a5be34d013c2913cf74f06e01c59b625bb4a17
[ "Apache-2.0" ]
null
null
null
src/objs/BIDR.cpp
nasa-jpl/Cassini_RADAR_Software
93a5be34d013c2913cf74f06e01c59b625bb4a17
[ "Apache-2.0" ]
null
null
null
static const char rcs_id_bidr_c[] = "@(#) $Id: BIDR.cpp,v 11.11 2013/10/15 23:02:19 bstiles Exp $"; #include <stdlib.h> #include <iomanip> #include <sstream> #include <string> #include <algorithm> #include "BIDR.h" #include "config_keywords.h" #include "Constants.h" #include "SimpleArray.h" #include "Utils.h" using std::cin; using std::cerr; using std::cout; using std::endl; using std::fixed; using std::ios; using std::setfill; using std::setprecision; using std::setw; using std::sort; using std::stringstream; //------------------------- // Static initializations //------------------------- string BIDR::pds_version_id_ = "PDS3"; string BIDR::record_type_ = "FIXED_LENGTH"; string BIDR::data_set_id_ = "CO-SSA-RADAR-5-BIDR-V1.0"; string BIDR::data_set_name_ = "CASSINI ORBITER SSA RADAR 5 BIDR V1.0"; string BIDR::producer_institution_name_ = "JET PROPULSION LABORATORY"; string BIDR::producer_id_ = "JPL"; string BIDR::instrument_host_name_ = "CASSINI ORBITER"; string BIDR::instrument_host_id_ = "CO"; string BIDR::instrument_name_ = "CASSINI RADAR"; string BIDR::instrument_id_ = "RADAR"; string BIDR::mission_name_ = "CASSINI-HUYGENS"; string BIDR::sample_type_[BIDRTYPECOUNT] = { "PC_REAL", // INC "UNSIGNED INTEGER", // BEAMMASK "PC_REAL", // S0_UNCORR "PC_REAL", // S0_CORR "PC_REAL", // LAT "PC_REAL", // LON "INTEGER", // START_BURST_NUM -- nondeliverable product "INTEGER", // END_BURST_NUM -- nondeliverable product "UNSIGNED INTEGER", // NUM_LOOKS "UNSIGNED INTEGER", // S0_CORR_DB -- nondeliverable product (from JPL) "PC_REAL", // DOPPLER "PC_REAL", // RANGE "INTEGER", // NOMINAL_BURST_NUM "PC_REAL", // S0NSQT_UNCORR "PC_REAL", // SO_STD "PC_REAL", // SO_NOISE_EQUIV "" // UNUSED }; int BIDR::sample_bits_[BIDRTYPECOUNT] = { BITS_PER_BYTE * sizeof(float), // INC BITS_PER_BYTE * sizeof(unsigned char), // BEAMMASK BITS_PER_BYTE * sizeof(float), // S0_UNCORR BITS_PER_BYTE * sizeof(float), // S0_CORR BITS_PER_BYTE * sizeof(float), // LAT BITS_PER_BYTE * sizeof(float), // LON BITS_PER_BYTE * sizeof(int), // START_BURST_NUM BITS_PER_BYTE * sizeof(int), // END_BURST_NUM BITS_PER_BYTE * sizeof(unsigned char), // NUM_LOOKS BITS_PER_BYTE * sizeof(unsigned char), // S0_CORR_DB BITS_PER_BYTE * sizeof(float), // DOPPLER BITS_PER_BYTE * sizeof(float), // RANGE BITS_PER_BYTE * sizeof(int), // NOMINAL_BURST_NUM BITS_PER_BYTE * sizeof(float), // S0NSQT_UNCORR BITS_PER_BYTE * sizeof(float), // S0_STD BITS_PER_BYTE * sizeof(float), // S0_NOISE_EQUIV 0 // UNUSED }; double BIDR::scaling_factor_ = 1.0; double BIDR::offset_ = 0.0; string BIDR::missing_constant_[BIDRTYPECOUNT] = { ISIS_NULL, // INC "0", // BEAMMASK ISIS_NULL, // S0_UNCORR ISIS_NULL, // S0_CORR ISIS_NULL, // LAT ISIS_NULL, // LON "0", // START_BURST_NUM "0", // END_BURST_NUM "0", // NUM_LOOKS "0", // S0_CORR_DB ISIS_NULL, // DOPPLER ISIS_NULL, // RANGE "0", // NOMINAL_BURST_NUM ISIS_NULL, // S0NSQT_UNCORR ISIS_NULL, // S0_STD ISIS_NULL, // S0_NOISE_EQUIV "" // UNUSED }; string BIDR::note_[BIDRTYPECOUNT] = { "The data values in this file are the incidence angles between the \ look vector and the surface normal at each pixel.", "The data values in this file identify the beam(s) used to produce \ the backscatter values for each pixel.", "The data values in this file are Synthetic Aperture Radar (SAR) \ normalized backscatter cross-section values. The values are \ physical scale (not in dB) and have not been corrected for \ incidence-angle effects. Biases due to noise have not been \ removed.", "The data values in this file are Synthetic Aperture Radar (SAR) \ normalized backscatter cross-section values. The values are \ physical scale (not in dB) and have been corrected for \ incidence-angle effects and biases due to thermal and quantization \ noise have been removed. The raw backscatter values have been \ multiplied by the function f(I), where I is the incidence angle \ and f(I) = 0.2907/(f1(I)+f2(I)+f3(I)), for \ f1(I)=2.8126*(cos(I)^4+893.9677*sin(I)^2)^(-1.5), \ f2(I)=0.5824*(cos(I)^4+34.1366*sin(I)^2)^(-1.5), \ and f3(I)=0.3767*cos(I)^1.9782.", "The data values in this file are the ordinary latitudes \ in the body fixed coordinate system for Titan.", "The data values in this file are the ordinary longitudes (positive \ west) in the body fixed coordinate coordinate system for Titan.", "The data values in this file are the indices of the starting (first) \ burst used to produce the backscatter values for each pixel.", "The data values in this file are the indices of the ending (last) \ burst used to produce the backscatter values for each pixel.", "The data values in this file are the number of looks used to produce \ the backscatter values for each pixel.", "", "The data values in this file is the Doppler freq in Hz corresponding \ to the pixel location in the nominal burst.", "The data values in this file is the Range in km corresponding \ to the pixel location in the nominal burst.", "The data values in this file are the indices of the nominal (center) \ burst used to produce the backscatter values for each pixel.", "The data values in this file are Synthetic Aperture Radar (SAR) \ normalized backscatter cross-section values. The values are \ physical scale (not in dB) and have not been corrected for \ incidence-angle effects. Biases due to thermal and quantization \ noise have been removed.", "The data values in this file are standard deviations of \ Synthetic Aperture Radar (SAR) normalized backscatter cross-section \ noise subtracted values w/o incidence angle correction. \ The values are physical scale (not in dB).", "The data values in this file are noise equivalent sigma-0 values \ associated with Synthetic Aperture Radar (SAR) normalized backscatter \ cross-section noise subtracted values w/o incidence angle correction. \ The values are physical scale (not in dB).", "" }; string BIDR::map_projection_type_ = "OBLIQUE CYLINDRICAL"; string BIDR::first_standard_parallel_ = "N/A"; string BIDR::second_standard_parallel_ = "N/A"; string BIDR::positive_longitude_direction_ = "WEST"; double BIDR::proj_center_latitude_ = 0.0; double BIDR::proj_center_longitude_ = 0.0; int BIDR::line_first_pixel_ = 1; int BIDR::sample_first_pixel_ = 1; double BIDR::map_projection_rotation_ = 90.0; string BIDR::coordinate_system_type_ = "BODY-FIXED ROTATING"; string BIDR::coordinate_system_name_ = "PLANETOGRAPHIC"; //-------------- // Constructors //-------------- BIDR::BIDR(const string& prefix, Config& cfg, L1B& l1b, SARProcParams& spp, const string& mode, BIDRModeE proc_mode=NORMAL) : procMode(proc_mode), inc_file(NULL), beammask_file(NULL), s0_uncorr_file(NULL), s0_corr_file(NULL), lat_file(NULL), lon_file(NULL), start_burst_num_file(NULL), end_burst_num_file(NULL), num_looks_file(NULL), X_file(NULL), std_file(NULL), s0ne_file(NULL), beam_deltas_file(NULL), dop_file(NULL), range_file(NULL), nom_burst_num_file(NULL), topoplus_file(NULL), num_lines_of_output(0), num_looks_required(0), max_looks_allowed(100000000), num_looks_to_skip(0), enable_max_looks(0), maximum_latitude_(-90), minimum_latitude_(90), maximum_longitude_(-180), minimum_longitude_(180), first_longitude_(-1000), auto_overwrite_bidr_(false), check_pds_string_lengths_(true), use_config_data_take_number_(false) { overlap_set=false; initProcMode(); if((procMode==TOPO || procMode==TOPO_PLUS) && !spp.noise_subtraction_on){ ErrorMessage e("BIDR Fatal Error: Topo mode requires noise_subtraction_on"); e.throwMe(); } // set up bad value float by specific bits. int val=BAD_VALUE_HEX; float* ptr=(float*) &val; BAD_VALUE=*ptr; DebugInfo dbg("BIDR::BIDR"); // For now if mode is not write throw an error if(mode!="w"){ ErrorMessage e("For now the BIDR constructor only works for write mode"); e.throwMe(); } if (cfg.keywordExists("SAR_PROC_AUTO_OVERWRITE_BIDR")) { auto_overwrite_bidr_ = (bool) cfg.getInt("SAR_PROC_AUTO_OVERWRITE_BIDR"); } openFiles(prefix,mode,spp.noise_subtraction_on); if (cfg.keywordExists("CHECK_PDS_STRING_LENGTHS")) { check_pds_string_lengths_ = (bool) cfg.getInt("CHECK_PDS_STRING_LENGTHS"); } if (!check_pds_string_lengths_) { // Display a warning message. Normally, this option should be enabled. cerr << "Warning: PDS string length limit checks have been disabled." << endl; cerr << "To enable the checks, set CHECK_PDS_STRING_LENGTHS to 1 in the " << "config file." << endl; } // Determine whether of not oblique cylindrical will be used use_oblique_cyl=(bool)cfg.getInt("USE_OBLIQUE_CYLINDRICAL"); // beam feathering feather_beams=(bool)cfg.getInt("ENABLE_BEAM_FEATHERING"); if(feather_beams && spp.single_beam_mode){ cerr<<"Warning Beam Feathering enabled in Single Beam Mode Ignoring ..." << endl; feather_beams=false; } dominant_beam3=false; if(cfg.keywordExists("SAR_PROC_DOMINANT_BEAM_3")){ dominant_beam3=(bool)cfg.getInt("SAR_PROC_DOMINANT_BEAM_3"); } mark_nadir_amb=false; if(cfg.keywordExists("BIDR_MARK_NADIR")){ mark_nadir_amb=(bool)cfg.getInt("BIDR_MARK_NADIR"); } output_beam_deltas=false; beam_deltas_file=NULL; if(cfg.keywordExists("SAR_PROC_BEAM_DELTAS_FILE")){ output_beam_deltas=true; string tmpstr=cfg.str("SAR_PROC_BEAM_DELTAS_FILE"); beam_deltas_file=fopen(tmpstr,"w"); } // Determine Incidence Angle Correction Model string incmod_string=cfg.str("INCIDENCE_ANGLE_CORRECTION_MODEL"); if(incmod_string=="VENUS" || incmod_string=="Venus"){ inc_correction_model=VENUS; venus_k1=0.0188; venus_k2=0.111; venus_s045=muhleman_backscatter(venus_k1,venus_k2,Uvar(45,"deg")); } // Correct name for this backscatter model is DBLINE041104 as it was // produced on Nov 4 2004. Original incorrect date is allowed for // backward compatibility. else if(incmod_string=="dBLine041004" || incmod_string=="DBLINE041004" || incmod_string=="dBLine041104" || incmod_string=="DBLINE041104"){ inc_correction_model=DBLINE041104; dbline_offset=4.1667; dbline_slope=-0.2333*180/pi; dbline_s045=pow(10,-0.6333); } else if(incmod_string=="RKIRK01TA"){ inc_correction_model=RKIRK01TA; invsin_coeff=0.0814; invsin_s045=0.0814/sin(45*pi/180); } else if(incmod_string=="HAGHAG"){ inc_correction_model=HAGHAG; } else if(incmod_string=="ENCELADUS_WYE1"){ inc_correction_model=ENCELADUS_WYE1; } else if(incmod_string=="RHEA_WYE1"){ inc_correction_model=RHEA_WYE1; } else if(incmod_string=="DIONE_WYE1"){ inc_correction_model=DIONE_WYE1; } else if(incmod_string=="INVALID" || incmod_string=="Invalid"){ inc_correction_model=INVALID_CORR; } else{ ErrorMessage e("BIDR::config BAD INCIDENCE_ANGLE_CORRECTION_MODEL "+ incmod_string); e.throwMe(); } if(inc_correction_model!=HAGHAG){ fprintf(stderr,"Warning Using Obsolete INC Correction MODEL\n"); fprintf(stdout,"Warning Using Obsolete INC Correction MODEL\n"); } // if so set up projection accordingly if(use_oblique_cyl){ StateVector s=spp.getClosestApproachState(); proj=OblCylProj(s); } look_direction_=spp.LookDirection(); // if not oblique cylindrical use default (trivial) Projection (do nothing here) // determine number of looks required to image num_looks_required=cfg.getInt("SARPROC_NUM_LOOKS_REQUIRED"); enable_max_looks=false; if(cfg.keywordExists("SARPROC_MAX_LOOKS_ALLOWED")){ max_looks_allowed=cfg.getInt("SARPROC_MAX_LOOKS_ALLOWED"); num_looks_to_skip=cfg.getInt("SARPROC_NUM_LOOKS_SKIPPED"); cerr << "Warning: only the first " << max_looks_allowed << " looks are used for each pixel in the BIDR!!!" << endl; enable_max_looks=true; } // Determine image resolution pixelsperdegree=cfg.getInt("BIDR_PIXELS_PER_DEGREE"); // The IGNORE_GAPS mode is needed if you want to process a swath // from a LBDR file with large gaps. It omits some error checking which // fails if there are gaps. if(cfg.keywordExists("BIDR_IGNORE_GAPS")){ ignore_gaps_mode=(bool)cfg.getInt("BIDR_IGNORE_GAPS"); } else ignore_gaps_mode=false; if(cfg.keywordExists("BIDR_ALLOW_DECREASING_LON")){ allow_decreasing_lon_mode=(bool)cfg.getInt("BIDR_ALLOW_DECREASING_LON"); } else allow_decreasing_lon_mode=false; // The REPLACE_X Mode is used to output arbitrary parameters to the X // backplane. As a side effect the new X paarmeter is the tie breaker for // choosing which beam to process. if(cfg.keywordExists("BIDR_REPLACE_X")){ replace_X_mode=(bool)cfg.getInt("BIDR_REPLACE_X"); if(replace_X_mode){ replace_X_param=cfg.str("BIDR_REPLACE_X_PARAM"); } } else replace_X_mode=false; if(cfg.keywordExists("SAR_PROC_USE_CONFIG_DATA_TAKE_NUMBER")){ use_config_data_take_number_ = cfg.getInt("SAR_PROC_USE_CONFIG_DATA_TAKE_NUMBER"); } if (use_config_data_take_number_) { data_take_id_ = cfg.getInt("data_take_number"); if (dbg.level) { dbg.file << "Data take ID from config file = " << data_take_id_ << endl; } } // Read or set other configuration parameters that are used to set values // in the PDS labels producer_full_name_ = PDSLabel::replaceSpaces(cfg.str("PRODUCER_FULL_NAME")); target_name_ = cfg.str("target"); source_product_id_ = l1b.productID(); if (source_product_id_.length() == 0) { // Should never occur, but set value to a non-empty string to avoid // writing an illegal PDS statement cerr << "Warning: cannot parse PRODUCT_ID from " << L1B_ACTIVE_MODE_FILENAME << " in BIDR::BIDR()" << endl; source_product_id_ = "UNKNOWN"; } product_version_ = cfg.getInt("BIDR_PRODUCT_VERSION_ID"); mission_phase_name_ = cfg.str("MISSION_PHASE_NAME"); data_set_map_projection_catalog_ = cfg.str("DATA_SET_MAP_PROJECTION_CATALOG"); software_version_ = cfg.str("BIDR_SOFTWARE_VERSION_ID"); // A valid FLYBY_ID is the character "T" followed by either "a", "A", or // a one- to three-digit number. The number may not consist of all zeroes, // but leading zeroes are allowed (although not strictly legal). string flyby_id = cfg.str("FLYBY_ID"); flyby_id_pass_ = ""; int flyby_id_len = flyby_id.length(); if (flyby_id_len < 2 || flyby_id_len > 4) { ErrorMessage e("BIDR::config: illegal value " + flyby_id + " for FLYBY_ID"); e.throwMe(); } else if (flyby_id_len == 2) { flyby_id_pass_ = flyby_id.substr(1); if (flyby_id[1] != 'a' && flyby_id[1] != 'A' && !(flyby_id[1] >= '1' && flyby_id[1] <= '9')) { ErrorMessage e("BIDR::config: illegal value " + flyby_id + " for FLYBY_ID"); e.throwMe(); } } else { flyby_id_pass_ = flyby_id.substr(1); // Strip leading zeroes while (flyby_id_pass_[0] == '0' && flyby_id_pass_.length() > 1) { flyby_id_pass_ = flyby_id_pass_.substr(1); } if (flyby_id_pass_[0] == '0') { ErrorMessage e("BIDR::config: illegal value " + flyby_id + " for FLYBY_ID"); e.throwMe(); } for (unsigned int i = 0; i < flyby_id_pass_.length(); i++) { if (flyby_id_pass_[i] < '0' || flyby_id_pass_[i] > '9') { ErrorMessage e("BIDR::config: illegal value " + flyby_id + " for FLYBY_ID"); e.throwMe(); } } } flyby_id_pass_ = PDSLabel::toUpper(flyby_id_pass_); if(flyby_id_pass_ == "A" && procMode!=TOPO && procMode!=TOPO_PLUS){ char resp[5]; cerr << "Should the Flyby ID be TA? ([nN]/yY) "; cout << "Should the Flyby ID be TA? ([nN]/yY) "; cin.getline(resp, 5); if (resp[0] != 'y' && resp[0] != 'Y') { ErrorMessage e("Fix the FLYBY_ID in the config file. Exiting."); e.throwMe(); } } // Determine segment number segment_id_=cfg.getInt("BIDR_SEGMENT_ID"); if(segment_id_<0 || segment_id_>49){ fprintf(stderr,"Fatal Error: Bad BIDR_SEGMENT_ID. Should be between 0 and 49\n"); fprintf(stdout,"Fatal Error: Bad BIDR_SEGMENT_ID. Should be between 0 and 49\n"); exit(1); } // Determine Latitude Bounds from L1B file // May need to move this functionality to a more suitable place later // Preprocessor could compute this and put in header. // or SARProcParams could initialize a number of things like this at once. // Right now I am placing it here so that the Projection object is available double maxlat=-pi/2; double minlat=pi/2; double firstlon=0; double minlon=4*pi; double maxlon=-4*pi; int valid_burst_no=0; int minlon_idx=0; int data_take_id_lbdr=0; while(!l1b.eof()){ // Reading individual parameters instead of whole record // for faster (but more fragile) access // l1b.readParameter("sclk"); // needed for PDS label start/stop timestamps l1b.readParameter("brst"); // needed for PDS label start/stop timestamps l1b.readParameter("t"); // needed for PDS label start/stop timestamps l1b.readParameter("beam_number"); // needed for single beam mode check l1b.readParameter("adc"); // needed for isSAR check l1b.readParameter("csr"); // needed for isCAl check in badSARData l1b.readParameter("engineer_qual_flag"); // needed for badSARData check l1b.readParameter("science_qual_flag"); // needed for badSARData check l1b.readParameter("act_centroid_lon"); // needed to compute lat bounds l1b.readParameter("act_centroid_lat"); // needed to compute lat bounds l1b.readParameter("record_id"); // needed for spp::inRegion l1b.readParameter("time_from_closest_approach"); // needed for spp.inRegion l1b.readParameter("time_from_epoch"); // needed for spp.inRegion l1b.readParameter("sab_counter"); // needed for quality override check l1b.readParameter("dtn"); // needed for PDS label product ID l1b.readParameter("num_pulses_received"); // needed for check in skipBurst l1b.skipRecord(); // go to beginning of next next record // only consider records which will be used by the SAR processor // perform checks to see if burst should be processed or skipped if(spp.skipBurst(proj,l1b)) continue; valid_burst_no++; // update count of bursts to be processed // set the start time only for the first valid burst; set the stop time // to be that of the current burst if (!sclk_start_.valid()) { sclk_start_ = Time(l1b.t); } sclk_stop_ = Time(l1b.t); // read the data take ID, which should be the same for all bursts data_take_id_lbdr = l1b.dtn; // update lat,lon bounds if necessary double slat,slon; double lat,lon; slat=l1b.act_centroid_lat.getInUnits("rad"); slon=l1b.act_centroid_lon.getInUnits("rad"); lat=proj.latInRad(slon,slat); lon=proj.lonInRad(slon,slat); if(lat < minlat) minlat=lat; if(lat > maxlat) maxlat=lat; if(valid_burst_no==1){ firstlon=lon; } // make certain longitude is in range (first_lon-180, first_lon+180) while(lon>firstlon+pi) lon-=2*pi; while(lon<firstlon-pi) lon+=2*pi; // This now works w/o worrying about wraparound so long as the // whole pass has less than 180 degrees of SAR coverage // which should always be the case for Cassini if(lon < minlon){ minlon=lon; minlon_idx=valid_burst_no; } if(lon > maxlon) maxlon=lon; } // Check for no valid bursts if(valid_burst_no==0){ cerr << "Fatal Error:BIDR constructor found no processable bursts." << endl; cerr << " Check to make sure all necesary parameters are being read for the various checks." << endl; cerr << " Check to make sure the region, radar mode," << endl; cerr << "and single beam SAR processor options are configured correctly." << endl; exit(1); } l1b.gotoFirstRecord(); // goes back to beginning of the file. // convert minlat and maxlat to integer degrees add desired pad // NEED TO MAKE THIS READ FROM THE CONFIG FILE Uvar latitude_pad=cfg["BIDR_LATLON_PAD_EACH_SIDE"]; double lpf=latitude_pad.getInUnits("deg"); minlat=floor(minlat*radtodeg-lpf); maxlat=ceil(maxlat*radtodeg+lpf); if(minlat<-90) minlat=-90; if(maxlat>90) maxlat=90; // compute the starting longitude for the grid and the direction of // motion bool lon_inc; // true if longitude is increasing // This equation fails if a short time region of multiple beam bursts // is being processed but for that case direction of motion is irrelevant // because the whole region being processed will fit in one longitude // window. lon_inc=(minlon_idx<valid_burst_no/2); if(!lon_inc && !allow_decreasing_lon_mode){ cerr << "Warning: BIDR::BIDR computed that oblcyl longitude is NOT" << endl << "Warning (cont): increasing with time. " << endl; cerr << "Warning: lon_inc is being explicitly set to true. " << endl; cerr << "Warning( cont): OK for short time runs ...." << endl; lon_inc=true; } double start_lon; if(lon_inc) start_lon=floor(minlon*radtodeg-lpf); else start_lon=ceil(maxlon*radtodeg+lpf); double lon_width=ceil((maxlon-minlon)*radtodeg+2*lpf); bool lon360=false; int lon_buffer_in_deg=9; Uvar lon_buffer_sz; if(cfg.keywordExists("BIDR_360_LON_BUFFER")){ lon360=cfg.getInt("BIDR_360_LON_BUFFER"); } if(cfg.keywordExists("BIDR_LON_BUFFER_SIZE")){ lon_buffer_sz=cfg["BIDR_LON_BUFFER_SIZE"]; // this must be a integer factor of 360 (degrees) or longitude wraps around // incorrectly lon_buffer_in_deg=(int)(lon_buffer_sz.getInUnits("deg")+0.5); int chk=360%lon_buffer_in_deg; if(chk!=0){ fprintf(stderr,"BAD BIDR_LON_BUFFER_SIZE should be factor of 360\n"); exit(1); } } // set up LatLonGrid grid=LatLonGrid(pixelsperdegree,minlat,maxlat,start_lon,lon_width,lon_inc,lon360,lon_buffer_in_deg); // Allocate arrays based on resolution and latitude bounds allocateArrays(spp); // Initialize standard lat/lon buffers int num_lats=grid.numLats(); int num_lons=grid.numLons(); int abs_start_i=grid.absStartValidIndex(); int start_i=grid.relLonIndex(abs_start_i); // The following two double for loops fail if lon_inc is false // So we have made sure it never can be. The OblCyl definition // precludes it anyway. if(lon_inc){ for(int i=start_i;i<num_lons;i++){ int abs_i=abs_start_i+i-start_i; for(int j=0;j<num_lats;j++){ double lon=grid.lonInRad(abs_i); double lat=grid.latInRad(j); slat_bfr[i][j]=proj.standardLatInRad(lon,lat); slon_bfr[i][j]=proj.standardLonInRad(lon,lat); } } for(int i=0;i<start_i;i++){ int abs_i=abs_start_i+num_lons-start_i+i; for(int j=0;j<num_lats;j++){ double lon=grid.lonInRad(abs_i); double lat=grid.latInRad(j); slat_bfr[i][j]=proj.standardLatInRad(lon,lat); slon_bfr[i][j]=proj.standardLonInRad(lon,lat); } } } else{ int abs_end_i=abs_start_i -num_lons +1; for(int i=start_i;i<num_lons;i++){ int abs_i=abs_end_i+i-start_i; for(int j=0;j<num_lats;j++){ double lon=grid.lonInRad(abs_i); double lat=grid.latInRad(j); slat_bfr[i][j]=proj.standardLatInRad(lon,lat); slon_bfr[i][j]=proj.standardLonInRad(lon,lat); } } for(int i=0;i<start_i;i++){ int abs_i=abs_end_i+num_lons-start_i+i; for(int j=0;j<num_lats;j++){ double lon=grid.lonInRad(abs_i); double lat=grid.latInRad(j); slat_bfr[i][j]=proj.standardLatInRad(lon,lat); slon_bfr[i][j]=proj.standardLonInRad(lon,lat); } } } if (dbg.level) { double latinrad = grid.latInRad(0); double loninrad = grid.lineNumberToLonInRad(0); dbg.file << "OC lat, lon at (0, 0) (rad): " << latinrad << " " << loninrad << endl; double latindeg = radtodeg * proj.standardLatInRad(loninrad, latinrad); double lonindeg = radtodeg * proj.standardLonInRad(loninrad, latinrad); dbg.file << "St lat, lon at (0, 0) (deg): " << latindeg << " " << lonindeg << endl; } if (!use_config_data_take_number_) { // Set data take ID to the value read from the last processable burst data_take_id_ = data_take_id_lbdr; if (dbg.level) { dbg.file << "Data take ID from LBDR file = " << data_take_id_ << endl; } } } void BIDR::openFiles(const string& prefix, const string& mode, int enable_noise_sub){ if(mode!="w"){ ErrorMessage e("BIDR::openFiles mode must be w."); e.throwMe(); } string inc_file_name = prefix + ".inc"; string beammask_file_name = prefix + ".beammask"; string s0_uncorr_file_name = prefix + ".s0_uncorr"; string s0_corr_file_name; if(enable_noise_sub) s0_corr_file_name = prefix + ".s0nsqt_corr"; else s0_corr_file_name = prefix + ".s0_corr"; string X_file_name; if(!enable_noise_sub) X_file_name=prefix + ".X"; else X_file_name=prefix+".s0nsqt_uncorr"; string std_file_name = prefix + ".s0nsqt_uncorr_std"; string s0ne_file_name = prefix + ".s0nsqt_noise_equiv"; string lat_file_name = prefix + ".lat"; string lon_file_name = prefix + ".lon"; string start_burst_num_file_name = prefix + ".start_burst_num"; string end_burst_num_file_name = prefix + ".end_burst_num"; string num_looks_file_name = prefix + ".num_looks"; string dop_file_name = prefix + ".doppler"; string range_file_name = prefix + ".range"; string nom_burst_num_file_name = prefix + ".nominal_burst_num"; string topoplus_file_name = prefix + ".topoplus"; if (!auto_overwrite_bidr_) { // If any of the BIDR output files exist, ask the user whether // to overwrite all the files. Any response other than "y" // or "Y" is interpreted as "no." if (fileExists(inc_file_name) || fileExists(beammask_file_name) || fileExists(s0_uncorr_file_name) || fileExists(s0_corr_file_name) || fileExists(lat_file_name) || fileExists(lon_file_name) || fileExists(dop_file_name) || fileExists(range_file_name) || fileExists(nom_burst_num_file_name) || fileExists(start_burst_num_file_name) || fileExists(end_burst_num_file_name) || fileExists(X_file_name) || fileExists(std_file_name) || fileExists(s0ne_file_name) || fileExists(num_looks_file_name)) { char resp[5]; cerr << "Overwrite existing BIDR output files? ([nN]/yY) "; cout << "Overwrite existing BIDR output files? ([nN]/yY) "; cin.getline(resp, 5); if (resp[0] != 'y' && resp[0] != 'Y') { ErrorMessage e("BIDR output files exist and will not be overwritten. Exiting."); e.throwMe(); } } } X_file=fopen(X_file_name, mode); if(output_enable_[INC])inc_file=fopen(inc_file_name, mode); if(output_enable_[BEAMMASK])beammask_file=fopen(beammask_file_name, mode); if(output_enable_[S0_UNCORR])s0_uncorr_file=fopen(s0_uncorr_file_name, mode); if(output_enable_[S0_CORR])s0_corr_file=fopen(s0_corr_file_name, mode); if(output_enable_[S0_STD])std_file=fopen(std_file_name, mode); if(output_enable_[S0_NOISE_EQUIV])s0ne_file=fopen(s0ne_file_name, mode); if(output_enable_[LAT])lat_file=fopen(lat_file_name, mode); if(output_enable_[LON])lon_file=fopen(lon_file_name, mode); if(output_enable_[START_BURST_NUM]) start_burst_num_file=fopen(start_burst_num_file_name, mode); if(output_enable_[END_BURST_NUM]) end_burst_num_file=fopen(end_burst_num_file_name, mode); if(output_enable_[NUM_LOOKS]) num_looks_file=fopen(num_looks_file_name, mode); if(output_enable_[NOMINAL_BURST_NUM]) nom_burst_num_file=fopen(nom_burst_num_file_name, mode); if(output_enable_[DOPPLER]) dop_file=fopen(dop_file_name, mode); if(output_enable_[RANGE]) range_file=fopen(range_file_name, mode); // fopen overload in Utils.cpp takes string inputs and throws errors on failure if(procMode==TOPO_PLUS) topoplus_file=fopen(topoplus_file_name, mode); } void BIDR::allocateArrays(const SARProcParams& spp) { DebugInfo dbg("BIDR::allocateArrays"); int num_lats=grid.numLats(); int num_lons=grid.numLons(); num_beams=5; // in single beam mode memory is conserved if(spp.single_beam_mode) num_beams=1; unsigned int bytes=0; int szarrayc3=size_array(sizeof(complex<float>),3, num_lons,num_beams,num_lats); int szarrayf3=size_array(sizeof(float),3, num_lons,num_beams,num_lats); int szarrayi3=size_array(sizeof(int),3, num_lons,num_beams,num_lats); int szarrayf2=size_array(sizeof(float),2, num_lons,num_lats); area_pixel=(float*)malloc(sizeof(float)*num_lats); float radii[3]; radii[0] = default_target_radii[PositionVector::X].km(); radii[1] = default_target_radii[PositionVector::Y].km(); radii[2] = default_target_radii[PositionVector::Z].km(); float rmag=sqrt(radii[0]*radii[0]+radii[1]*radii[1]+radii[2]*radii[2]); float pixresnom=(1.0/pixelsperdegree)*degtorad*rmag; pixresnom*=pixresnom; for(int j=0;j<num_lats;j++){ float lat_in_rad=grid.latInRad(j); area_pixel[j]=cos(lat_in_rad)*pixresnom; } if(output_enable_[S0_UNCORR]){ s0_uncorr_bfr= (float***)make_array(sizeof(complex<float>),3, num_lons,num_beams,num_lats); bytes+=szarrayc3; } s0_nsub_uncorr_bfr= (float***)make_array(sizeof(complex<float>),3, num_lons,num_beams,num_lats); bytes+=szarrayc3; s0ne_bfr= (float***)make_array(sizeof(complex<float>),3, num_lons,num_beams,num_lats); bytes+=szarrayc3; if(output_enable_[INC]){ inc_bfr=(float***)make_array(sizeof(float),3,num_lons,num_beams,num_lats); bytes+=szarrayf3; } if(output_enable_[DOPPLER]){ dop_bfr=(float***)make_array(sizeof(float),3,num_lons,num_beams,num_lats); bytes+=szarrayf3; } if(output_enable_[RANGE]){ range_bfr=(float***)make_array(sizeof(float),3,num_lons,num_beams,num_lats); bytes+=szarrayf3; } if(output_enable_[RANGE]||output_enable_[DOPPLER] ||output_enable_[NOMINAL_BURST_NUM]){ max_X_bfr=(float***)make_array(sizeof(float),3,num_lons,num_beams,num_lats); bytes+=szarrayf3; } X_bfr=(float***)make_array(sizeof(float),3,num_lons,num_beams,num_lats); bytes+=szarrayf3; if(output_enable_[START_BURST_NUM]){ start_burst_num= (int***)make_array(sizeof(int),3,num_lons,num_beams,num_lats); bytes+=szarrayi3; } if(output_enable_[END_BURST_NUM]){ end_burst_num=(int***)make_array(sizeof(int),3,num_lons,num_beams,num_lats); bytes+=szarrayi3; } if(output_enable_[NOMINAL_BURST_NUM]){ nom_burst_num=(int***)make_array(sizeof(int),3,num_lons,num_beams,num_lats); bytes+=szarrayi3; } num_looks=(int***)make_array(sizeof(int),3,num_lons,num_beams,num_lats); bytes+=szarrayi3; slat_bfr = (double**)make_array(sizeof(double),2,num_lons,num_lats); slon_bfr = (double**)make_array(sizeof(double),2,num_lons,num_lats); bytes+=2*szarrayf2; bursts_since_update=(int*)make_array(sizeof(int),1,num_lons); beams_found=(bool**)make_array(sizeof(bool),2,num_lons,num_beams); checksum_ = (int *) make_array(sizeof(int), 1, BIDRTYPECOUNT); beammask_io_bfr = (char*) make_array(sizeof(char), 1, num_lats); s0_corr_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); lat_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); lon_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); range_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); dop_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); inc_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); X_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); std_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); s0ne_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); s0_uncorr_io_bfr = (float*) make_array(sizeof(float), 1, num_lats); start_burst_num_io_bfr = (int*) make_array(sizeof(int), 1, num_lats); nom_burst_num_io_bfr = (int*) make_array(sizeof(int), 1, num_lats); end_burst_num_io_bfr = (int*) make_array(sizeof(int), 1, num_lats); num_looks_io_bfr = (unsigned char*) make_array(sizeof(unsigned char), 1, num_lats); bytes+=num_lats*(sizeof(char)+7*sizeof(float)+4*sizeof(int)); if(procMode==TOPO || procMode==TOPO_PLUS){ dsigma0=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); topo_inc1=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); topo_inc2=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); topo_lat=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); topo_lon=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); topo_wnl=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); mid_ds0=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); slope_ds0=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); rms_ds0=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); noisefloor1=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); noisefloor2=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); power1=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); power2=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); ambrat1=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); ambrat2=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); dsigma0std=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); dsigma0bias=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); sumsigma0=(float**)make_array(sizeof(float),2,4,MAX_BIDR_LINES); overlap_col=(int**)make_array(sizeof(int),2,4,MAX_BIDR_LINES); overlap_width=(int**)make_array(sizeof(int),2,4,MAX_BIDR_LINES); noise_equiv_s0=(float***)make_array(sizeof(float),3,num_lons,num_beams,num_lats); Xambig_bfr=(float***)make_array(sizeof(float),3,num_lons,num_beams,num_lats); resfactor=(float***)make_array(sizeof(float),3,num_lons,num_beams,num_lats); bytes+=szarrayf2*6 +szarrayf3*2; } if(procMode==TOPO_PLUS){ topoplus_s01=(float***)make_array(sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); topoplus_s02=(float***)make_array(sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); topoplus_s0ne1=(float***)make_array(sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); topoplus_s0ne2=(float***)make_array(sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); topoplus_s0baqscale1=(float***)make_array(sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); topoplus_s0baqscale2=(float***)make_array(sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); topoplus_s0amb1=(float***)make_array(sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); topoplus_s0amb2=(float***)make_array(sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); } if(!s0_uncorr_bfr || !s0_nsub_uncorr_bfr || !s0ne_bfr || !X_bfr || !bursts_since_update || !beams_found || !num_looks || !slat_bfr || !slon_bfr || !checksum_ || !beammask_io_bfr || !s0_corr_io_bfr || !lat_io_bfr || !lon_io_bfr || !s0_uncorr_io_bfr || !start_burst_num_io_bfr || !end_burst_num_io_bfr || !num_looks_io_bfr || !X_io_bfr || !std_io_bfr || !s0ne_io_bfr || !range_io_bfr || !dop_io_bfr || !nom_burst_num_io_bfr || !area_pixel){ cerr << "BIDR allocation failing for num_lons = " << num_lons <<", num_lats = " << num_lats << ", num_beams = " << num_beams << endl; ErrorMessage e("BIDR object failed to allocate buffers ...\nTry reducing PIXELS_PER_DEGREE or using SINGLE_BEAM_MODE"); e.throwMe(); } if((procMode==NORMAL)&& (!start_burst_num || !end_burst_num || !inc_bfr)){ cerr << "BIDR allocation failing for num_lons = " << num_lons <<", num_lats = " << num_lats << ", num_beams = " << num_beams << endl; ErrorMessage e("BIDR object failed to allocate buffers ...\nTry reducing PIXELS_PER_DEGREE or using SINGLE_BEAM_MODE"); e.throwMe(); } if((procMode==STEREO)&& (!range_bfr || !dop_bfr || !nom_burst_num)){ cerr << "BIDR allocation failing for num_lons = " << num_lons <<", num_lats = " << num_lats << ", num_beams = " << num_beams << endl; ErrorMessage e("BIDR object failed to allocate buffers ...\nTry reducing PIXELS_PER_DEGREE or using SINGLE_BEAM_MODE"); e.throwMe(); } if((procMode==TOPO || procMode==TOPO_PLUS)&& (!dsigma0 || !dsigma0std || !dsigma0bias || !sumsigma0 || !overlap_col || !overlap_width || !noise_equiv_s0 || !Xambig_bfr || !resfactor || !topo_inc1 || !topo_inc2 || !topo_lat || !topo_lon || !topo_wnl || !mid_ds0 || !slope_ds0 || !rms_ds0 || !inc_bfr || !noisefloor1 || !noisefloor2 || !ambrat1 || !ambrat2 || !power1 || !power2)){ cerr << "BIDR allocation failing for num_lons = " << num_lons <<", num_lats = " << num_lats << ", num_beams = " << num_beams << endl; ErrorMessage e("BIDR object failed to allocate buffers ...\nTry reducing PIXELS_PER_DEGREE or using SINGLE_BEAM_MODE"); e.throwMe(); } if((procMode==TOPO_PLUS)&& ( !topoplus_s01 || !topoplus_s02 || !topoplus_s0ne1 || !topoplus_s0ne2 || !topoplus_s0baqscale1 || !topoplus_s0baqscale2 || !topoplus_s0amb1 || !topoplus_s0amb2) ){ cerr << "BIDR TOPO_PLUS allocation failing for num_lons = " << num_lons <<" MAX_TOPO_OVERLAPWIDTH=" << MAX_TOPO_OVERLAP_WIDTH << endl; ErrorMessage e("BIDR object failed to allocate buffers ...\nTry reducing PIXELS_PER_DEGREE or using SINGLE_BEAM_MODE"); e.throwMe(); } // initialize arrays for(int i=0;i<num_lons;i++){ for(int b=0;b<num_beams;b++){ for(int j=0;j<num_lats;j++){ if(output_enable_[START_BURST_NUM])start_burst_num[i][b][j]=-1; if(output_enable_[END_BURST_NUM])end_burst_num[i][b][j]=-1; if(output_enable_[INC])inc_bfr[i][b][j]=0; num_looks[i][b][j]=0; if(procMode==STEREO) max_X_bfr[i][b][j]=0; if(procMode==TOPO || procMode==TOPO_PLUS){ resfactor[i][b][j]=0; noise_equiv_s0[i][b][j]=0; Xambig_bfr[i][b][j]=0; } X_bfr[i][b][j]=0; s0_uncorr_bfr[i][b][j]=0; s0_nsub_uncorr_bfr[i][b][j]=0; s0ne_bfr[i][b][j]=0; } } } if(procMode==TOPO || procMode==TOPO_PLUS){ for(int i=0;i<4;i++){ for(int j=0;j<MAX_BIDR_LINES;j++){ dsigma0[i][j]=0; sumsigma0[i][j]=0; dsigma0std[i][j]=0; dsigma0bias[i][j]=0; overlap_col[i][j]=0; overlap_width[i][j]=0; topo_inc1[i][j]=0; topo_inc2[i][j]=0; topo_lat[i][j]=0; topo_lon[i][j]=0; topo_wnl[i][j]=0; mid_ds0[i][j]=0; slope_ds0[i][j]=0; rms_ds0[i][j]=0; power1[i][j]=0; power2[i][j]=0; ambrat1[i][j]=0; ambrat2[i][j]=0; noisefloor1[i][j]=0; noisefloor2[i][j]=0; } } } if(procMode==TOPO_PLUS){ for(int i=0;i<4;i++){ for(int j=0;j<MAX_BIDR_LINES;j++){ for(int k=0;k<MAX_TOPO_OVERLAP_WIDTH;k++){ topoplus_s01[i][j][k]=BAD_VALUE; topoplus_s02[i][j][k]=BAD_VALUE; topoplus_s0ne1[i][j][k]=BAD_VALUE; topoplus_s0ne2[i][j][k]=BAD_VALUE; topoplus_s0baqscale1[i][j][k]=BAD_VALUE; topoplus_s0baqscale2[i][j][k]=BAD_VALUE; topoplus_s0amb1[i][j][k]=BAD_VALUE; topoplus_s0amb2[i][j][k]=BAD_VALUE; } } } } for(int i=0;i<num_lons;i++){ bursts_since_update[i]=0; for(int b=0;b<num_beams;b++){ beams_found[i][b]=false; } for(int j=0;j<num_lats;j++){ slat_bfr[i][j]=0; slon_bfr[i][j]=0; } } for(int i=0;i<BIDRTYPECOUNT;i++){ checksum_[i] = 0; } if(dbg.level){ dbg.file << "BIDR allocates " << bytes << " bytes of array + " << sizeof(BIDR) << " bytes of object = "; bytes+=sizeof(L1I); dbg.file << bytes << " bytes Total" << endl; dbg.file << " " << "num_lons=" << num_lons <<", num_lats=" << num_lats << ", num_beams=" << num_beams << endl; } } void BIDR::smoothOverlap(int**col, int** width){ // set up arrays for fits #define DEBUG_SMOOTH #ifdef DEBUG_SMOOTH FILE* dfp = fopen("dbgsmooth.txt","w"); #endif for(int i=0;i<4;i++){ // compute means and stds to normalize data for fit double line_mean=0, line_std=0; double col_mean=0, col_std=0; double width_mean=0, width_std=0; int line_min=0, line_max=0; int numsamp=0; bool min_found=false; for(int j=0;j<MAX_BIDR_LINES;j++){ // check valid overlap if(width[i][j]!=-1){ if(!min_found){ line_min=j; min_found=true; } line_max=j; numsamp++; line_mean+=j; line_std+=j*j; col_mean+=col[i][j]; col_std+=col[i][j]*col[i][j]; width_mean+=width[i][j]; width_std+=width[i][j]*width[i][j]; } } line_mean=line_mean/numsamp; col_mean=col_mean/numsamp; width_mean=width_mean/numsamp; line_std=line_std-numsamp*line_mean*line_mean; col_std=col_std-numsamp*col_mean*col_mean; width_std=width_std-numsamp*width_mean*width_mean; line_std=sqrt(line_std/(numsamp-1)); col_std=sqrt(col_std/(numsamp-1)); width_std=sqrt(width_std/(numsamp-1)); // compute normalize data for fits int N=line_max-line_min+1; Dvec x("x",N); Dvec yc("yc",N); Dvec yw("yw",N); for(int j=0;j<N;j++){ x(j)=((line_min+j)-line_mean)/line_std; yc(j)=(col[i][line_min+j]-col_mean)/col_std; yw(j)=(width[i][line_min+j]-width_mean)/width_std; } // perform 15th order polynomial fit on overlap and col // do fits from first valid (nonzero col, width>-1) to last // exclude zero values from fit. int porder=12; Dvec pc("pc",porder+1); Dvec pw("pw",porder+1); polyfit(pc,yc,x); polyfit(pw,yw,x); #ifdef DEBUG_SMOOTH fprintf(dfp,"pw=["); for(int j=0;j<porder+1;j++) fprintf(dfp,"%g ",pw(j)); fprintf(dfp,"]\n"); fprintf(dfp,"pc=["); for(int j=0;j<porder+1;j++) fprintf(dfp,"%g ",pc(j)); fprintf(dfp,"]\n"); fprintf(dfp,"width_mean=%g width_std=%g col_mean=%g col_std=%g line_mean=%g line_std=%g line_min=%d line_max=%d\n",width_mean,width_std,col_mean,col_std,line_mean,line_std,line_min,line_max); #endif double dcol[N]; double dwidth[N]; for(int j=0;j<N;j++){ dcol[j]=0; dwidth[j]=0; for(int k=porder;k>0;k--){ dcol[j]+=pc(k); dcol[j]*=x(j); dwidth[j]+=pw(k); dwidth[j]*=x(j); } dcol[j]+=pc(0); dwidth[j]+=pw(0); #ifdef DEBUG_SMOOTH fprintf(dfp,"FIT %d %d %g %g %g %g %g\n",i,j,x(j),yc(j),dcol[j],yw(j),dwidth[j]); #endif dcol[j]*=col_std; dcol[j]+=col_mean; dwidth[j]*=width_std; dwidth[j]+=width_mean; } // replace values with fit rounded to nearest nonnegative integer for(int j=0;j<MAX_BIDR_LINES;j++){ if(j<line_min){ col[i][j]=(int)(dcol[0]+0.5); width[i][j]=-1; } else if(j>line_max){ col[i][j]=(int)(dcol[N-1]+0.5); width[i][j]=-1; } else{ #ifdef DEBUG_SMOOTH fprintf(dfp,"%d %d %d %d ",i,j,col[i][j],width[i][j]); #endif col[i][j]=(int)(dcol[j-line_min]+0.5); width[i][j]=(int)(dwidth[j-line_min]*1+0.5); #ifdef DEBUG_SMOOTH fprintf(dfp,"%d %d\n",col[i][j],width[i][j]); #endif } } // end loop over j } // end loop over i } void BIDR::setOverlap(int** col, int** width){ overlap_set=true; if(procMode!=TOPO && procMode!=TOPO_PLUS){ ErrorMessage e("BIDR::setOverlap only works in TOPO and TOPO_PLUS modes"); e.throwMe(); } // set fixed overlap for candidate height SAR processor runs for(int i=0;i<4;i++){ for(int j=0;j<MAX_BIDR_LINES;j++){ overlap_col[i][j]=col[i][j]; overlap_width[i][j]=width[i][j]; if( procMode==TOPO_PLUS && 2*overlap_width[i][j]+1 > MAX_TOPO_OVERLAP_WIDTH){ cerr << "In BIDR.h MAX_TOPO_OVERlAP_WIDTH = " << MAX_TOPO_OVERLAP_WIDTH << endl; fprintf(stderr,"This is smaller than width for profile # %d line %d which is %d\n",i,j,2*width[i][j]+1); exit(1); } } } } void BIDR::updateTopoArrays(int first_i){ float noise_floor1[4]={0,0,0,0}, noise_floor2[4]={0,0,0,0}; float s01[4]={0,0,0,0},s02[4]={0,0,0,0}; float SNR1[4]={0,0,0,0},SNR2[4]={0,0,0,0}; float EY[4]={0,0,0,0}, EXY[4]={0,0,0,0}, EXX[4]={0,0,0,0}; float MSS[4]={0,0,0,0}; // mean sum square s01-s02; float P1[4]={0,0,0,0}, P2[4]={0,0,0,0}; // mean powers float sumX1[4]={0,0,0,0}, sumX2[4]={0,0,0,0}; // sums of X factor float sumXamb1[4]={0,0,0,0}, sumXamb2[4]={0,0,0,0}; // sums of Xambiguity int N[4]={0,0,0,0}; float truenumlooks1[4]={0,0,0,0},truenumlooks2[4]={0,0,0,0}; // estimate intermediate arrays dsigma0, overlap_col and overlap_width for(int b=0;b<4;b++){ bool found_overlap=false; int j0=0,j1=0; float nl1,nl2; int num_lats=grid.numLats(); //#define DEBUGTOPO for(int j=0;j<num_lats;j++){ float inc1, inc2,s01corr,s02corr, s0ne1, s0ne2; if(num_looks[first_i][b][j]>=num_looks_required){ nl1=num_looks[first_i][b][j]*resfactor[first_i][b][j]; } else{ nl1=0; } if(num_looks[first_i][b+1][j]>=num_looks_required){ nl2=num_looks[first_i][b+1][j]*resfactor[first_i][b+1][j]; } else{ nl2=0; } // only use data at least 3 dB above the noise floor if(!overlap_set){ if(s0_uncorr_bfr[first_i][b][j]<2*noise_equiv_s0[first_i][b][j]) nl1=0; if(s0_uncorr_bfr[first_i][b+1][j]<2*noise_equiv_s0[first_i][b+1][j]) nl2=0; } // if overlap is set only use pixels in range else{ int col=overlap_col[b][num_lines_of_output]; int width=overlap_width[b][num_lines_of_output]; if(j<col-width || j>col+width){ nl1=0; nl2=0; } } if(nl1>0 && nl2>0){ if(!found_overlap){ found_overlap=true; j0=j; } j1=j; inc1=inc_bfr[first_i][b][j]; inc2=inc_bfr[first_i][b+1][j]; s01corr=incAngleCorrect(s0_nsub_uncorr_bfr[first_i][b][j],inc1,0,0,inc_correction_model); s02corr=incAngleCorrect(s0_nsub_uncorr_bfr[first_i][b+1][j],inc2,0,0,inc_correction_model); s01[b]+=s01corr*nl1; if(isnan(s01[b])){ printf("BIDR::UpdateTopoArrays Found NaN in s01[%d], nl1=%g s01corr=%g s0_nsub_uncorr[i][b][j]=%g inc1=%g i=%d b=%d j=%d\n",b,nl1,s01corr,s0_nsub_uncorr_bfr[first_i][b][j],inc1,first_i,b,j); exit(1); } s02[b]+=s02corr*nl2; P1[b]+=X_bfr[first_i][b][j]*s0_uncorr_bfr[first_i][b][j]*nl1; P2[b]+=X_bfr[first_i][b+1][j]*s0_uncorr_bfr[first_i][b+1][j]*nl2; sumX1[b]+=X_bfr[first_i][b][j]*nl1; sumX2[b]+=X_bfr[first_i][b+1][j]*nl2; sumXamb1[b]+=Xambig_bfr[first_i][b][j]*nl1; sumXamb2[b]+=Xambig_bfr[first_i][b+1][j]*nl2; float x=j-overlap_col[b][num_lines_of_output]; float y= s01corr-s02corr; EY[b]+=y; MSS[b]+=y*y; EXY[b]+=x*y; EXX[b]+=x*x; N[b]++; truenumlooks1[b]+=nl1; truenumlooks2[b]+=nl2; s0ne1=incAngleCorrect(noise_equiv_s0[first_i][b][j],inc1,0,0,inc_correction_model); s0ne2=incAngleCorrect(noise_equiv_s0[first_i][b+1][j],inc2,0,0,inc_correction_model); noise_floor1[b]+=s0ne1*nl1; noise_floor2[b]+=s0ne2*nl2; #ifdef DEBUGTOPO if(num_lines_of_output>880 && num_lines_of_output<920 && b==0) printf("line %d overlap %d j0=%d j1=%d s01=%g s02=%g tnl1=%g tnl2=%g nf1=%g nf2=%g\n",num_lines_of_output,b, j0,j1,s01[b],s02[b],truenumlooks1[b],truenumlooks2[b], noise_floor1[b],noise_floor2[b]); #endif } } // end column (latitude)loop s01[b]/=truenumlooks1[b]; s02[b]/=truenumlooks2[b]; noise_floor1[b]/=truenumlooks1[b]; noise_floor2[b]/=truenumlooks2[b]; P1[b]/=truenumlooks1[b]; P2[b]/=truenumlooks1[b]; SNR1[b]=s01[b]/noise_floor1[b]; SNR2[b]=s02[b]/noise_floor2[b]; MSS[b]=MSS[b]/N[b]; EY[b]=EY[b]/N[b]; EXY[b]=EXY[b]/N[b]; EXX[b]=EXX[b]/N[b]; if(! overlap_set){ overlap_col[b][num_lines_of_output]=(j1+j0)/2; overlap_width[b][num_lines_of_output]=(j1-j0)/2; } if(truenumlooks1[b]==0) overlap_width[b][num_lines_of_output]=0; #ifdef DEBUGTOPO if(num_lines_of_output>880 && num_lines_of_output<920 && b==0) printf("Final normed line=%d s01=%g s02=%g nf1=%g nf2=%g SNR1=%g SNR2=%g col=%d width=%d\n",num_lines_of_output, s01[b],s02[b],noise_floor1[b],noise_floor2[b],SNR1[b],SNR2[b], overlap_col[b][num_lines_of_output], overlap_width[b][num_lines_of_output]); #endif } // end beam loop // compute remaining topo arrays for(int i=0;i<4;i++){ if(truenumlooks1[i]>0){ dsigma0[i][num_lines_of_output]=s01[i]-s02[i]; sumsigma0[i][num_lines_of_output]=s01[i]+s02[i]; dsigma0std[i][num_lines_of_output]=sqrt((1+2/SNR1[i]+1/(SNR1[i]*SNR1[i]))/truenumlooks1[i]+(1+2/SNR2[i]+1/(SNR2[i]*SNR2[i]))/truenumlooks2[i]); dsigma0bias[i][num_lines_of_output]=0.2*noise_floor1[i]+0.2*noise_floor2[i]; topo_inc1[i][num_lines_of_output]=inc_bfr[first_i][i][overlap_col[i][num_lines_of_output]]; topo_inc2[i][num_lines_of_output]=inc_bfr[first_i][i+1][overlap_col[i][num_lines_of_output]]; topo_lat[i][num_lines_of_output]=slat_bfr[first_i][overlap_col[i][num_lines_of_output]]; topo_lon[i][num_lines_of_output]=slon_bfr[first_i][overlap_col[i][num_lines_of_output]]; topo_wnl[i][num_lines_of_output]=(truenumlooks1[i]+truenumlooks2[i])/2.0; mid_ds0[i][num_lines_of_output]=EY[i]; slope_ds0[i][num_lines_of_output]=EXY[i]/EXX[i]; rms_ds0[i][num_lines_of_output]=sqrt(MSS[i]); noisefloor1[i][num_lines_of_output]=noise_floor1[i]; noisefloor2[i][num_lines_of_output]=noise_floor2[i]; ambrat1[i][num_lines_of_output]=sumXamb1[i]/sumX1[i]; ambrat2[i][num_lines_of_output]=sumXamb2[i]/sumX2[i]; power1[i][num_lines_of_output]=P1[i]; power2[i][num_lines_of_output]=P2[i]; } else{ dsigma0[i][num_lines_of_output]=BAD_VALUE; sumsigma0[i][num_lines_of_output]=BAD_VALUE; dsigma0std[i][num_lines_of_output]=BAD_VALUE; dsigma0bias[i][num_lines_of_output]=BAD_VALUE; topo_inc1[i][num_lines_of_output]=BAD_VALUE; topo_inc2[i][num_lines_of_output]=BAD_VALUE; topo_lat[i][num_lines_of_output]=BAD_VALUE; topo_lon[i][num_lines_of_output]=BAD_VALUE; topo_wnl[i][num_lines_of_output]=BAD_VALUE; mid_ds0[i][num_lines_of_output]=BAD_VALUE; slope_ds0[i][num_lines_of_output]=BAD_VALUE; rms_ds0[i][num_lines_of_output]=BAD_VALUE; noisefloor1[i][num_lines_of_output]=BAD_VALUE; noisefloor2[i][num_lines_of_output]=BAD_VALUE; power1[i][num_lines_of_output]=BAD_VALUE; power2[i][num_lines_of_output]=BAD_VALUE; ambrat1[i][num_lines_of_output]=BAD_VALUE; ambrat2[i][num_lines_of_output]=BAD_VALUE; } #ifdef DEBUGTOPO if(num_lines_of_output>880 && num_lines_of_output<920 && i==0) printf("Final dsigma0=%g sums0=%g dsigma0std=%g dsigma0bias=%g\n", dsigma0[i][num_lines_of_output], sumsigma0[i][num_lines_of_output], dsigma0std[i][num_lines_of_output], dsigma0bias[i][num_lines_of_output]); #endif } } void BIDR::topoProcessAndWrite(L1I& l1i, SARProcParams& spp, bool single_burst_mode, float trial_height){ // for now topo outputs a subset of NOMINAL backplanes so I // can merely call stripProcessAnd Write // this will need to change if I wind up outputting more stripProcessAndWrite(l1i,spp,single_burst_mode); } void BIDR::stripProcessAndWrite(L1I& l1i, SARProcParams& spp, bool single_burst_mode){ // set the direction to use for the X test when choosing a beam switch(l1i.replace_X_param){ case L1I::NONE: Xcheckdir=1; break; case L1I::RANGE_RES: Xcheckdir=-1; break; case L1I::AZIMUTH_RES: Xcheckdir=-1; break; case L1I::LOOKVEL_ANGLE: Xcheckdir=1; break; case L1I::RES_ELEMENT_ANGLE: Xcheckdir=1; break; case L1I::AMBIG_RATIO: Xcheckdir=-1; break; default: Xcheckdir=1; break; } static bool first_call=true; static DebugInfo dbg("BIDR::stripProcessAndWrite"); bool bad_margin=false; // flag to determine if usable area is clipped. // get burst and beam numbers int burst_no=l1i.sab_counter; int bn=l1i.beam_number-1; // necessary to save memory alloaction for single beam mode if(spp.single_beam_mode) bn=0; // determine value to replace X with if desired if(replace_X_mode){ replace_X_value=l1i.getParam(replace_X_param); } // determine loose boundaries on grid for burst image // Geometry conversion from (t,range, doppler) Standard(slat,slon) // performed by L1i from Standard (slat,slon) to OblCyl(lat,lon) is // performed by the OblCylProj object l1i.computeLatLonBounds(proj); // sets up simple model for converting lat/lon to/from OblCyl lat/lon // that only applies to burst proj.initBurstTransformation(); int bounds_ij[4]; // Get absolute boundary indices (w/o performing modulus to restrict to // grid) // If the boundaries extend beyond the edge of the current grid.getBoundary(l1i.lonlat_bounds, bounds_ij); int i_min=bounds_ij[0]; int i_max=bounds_ij[1]; int j_min=bounds_ij[2]; int j_max=bounds_ij[3]; if(dbg.level){ dbg.file << "BIDR::stripProcessAndWrite:Burst #" << burst_no << " Beam #" << l1i.beam_number << endl; } if(dbg.level){ dbg.file << "BIDR::stripProcessAndWrite:Lon Bounds (" << l1i.lonlat_bounds[0]*radtodeg <<"," << l1i.lonlat_bounds[1]*radtodeg << ")" << endl; dbg.file << "BIDR::stripProcessAndWrite:LonGrid Absolute Bounds (" << i_min <<"," << i_max << ") and Relative Bounds (" << grid.relLonIndex(i_min) <<"," << grid.relLonIndex(i_max) << ")" << endl; } // check to see if burst longitude bounds are in valid range bool minvalid =grid.checkValidLongitude(i_min); bool maxvalid =grid.checkValidLongitude(i_max); // Make sure both min and max longitudes are valid first time through // if not throw error if((!minvalid || !maxvalid) && first_call && !single_burst_mode && !ignore_gaps_mode){ float bufl1 = grid.absStartValidIndex()/(float)pixelsperdegree; float bufl2 = grid.absEndValidIndex()/(float)pixelsperdegree; float bl1 = i_min/(float)pixelsperdegree; float bl2 = i_max/(float)pixelsperdegree; ErrorMessage e("BIDR::StripProcessAndWrite Out of Bounds Longitude Line Needed for first burst (Burst#"+toStr(burst_no)+") \nTry Increasing BIDR_LATLON_PAD_EACH_SIDE OR BIDR_LON_BUFFER_SIZE (default 9 deg)\n Burst Lon Range=("+toStr(bl1)+","+toStr(bl2)+") Buffer lon range=("+toStr(bufl1)+","+toStr(bufl2)+") lon_inc is "+toStr(grid.lonIncreasing())); first_call=false; e.throwMe(); } first_call=false; // Check to see if the buffer is full and we need to output line(s) // output lines as necessary while(!minvalid || !maxvalid){ // Check to see if we need a line that has already been written // (throws error) if( !single_burst_mode && !ignore_gaps_mode && ((grid.lonIncreasing() && !minvalid) || (!grid.lonIncreasing() && !maxvalid))){ ErrorMessage e("BIDR::stripProcessAndWrite Previously Written Longitude Line Needed for Burst#"+toStr(burst_no)+"\nTry increasing BIDR_LON_BUFFER_SIZE default 9.0 degrees, needs to be a factor of 360"); e.throwMe(); } if(dbg.level){ dbg.file << "Minvalid " << minvalid << " Maxvalid " << maxvalid << " outputting line and shifting buffer ..." << endl; } outputLine(spp); minvalid =grid.checkValidLongitude(i_min); maxvalid =grid.checkValidLongitude(i_max); } // output bounding box to standard info line spp.cout_line+=toStr(j_min); spp.cout_line+=" "; spp.cout_line+=toStr(j_max); spp.cout_line+=" "; spp.cout_line+=toStr(grid.absIndexToLineNumber(i_min)); spp.cout_line+=" "; spp.cout_line+=toStr(grid.absIndexToLineNumber(i_max)); spp.cout_line+=" "; int valid_pixels_found=0; // loop over grid points within boundaries double burst_resolution=l1i.resolutionArea(spp); for(int abs_i=i_min;abs_i<=i_max;abs_i++){ int i=grid.relLonIndex(abs_i); // set bursts_since_update to 0 // A longitude Line is still needed if it is within the LatLon boundary of a burst // even if it is not in the useable area bursts_since_update[i]=0; // indicate beam bn+1 has been found for this longitude line. // for single beam mode this is unnecessary but harmless. beams_found[i][bn]=true; for(int j=j_min;j<=j_max;j++){ // compute doppler and range at point double fdop_in_Hz, range_in_km; float slat = slat_bfr[i][j]; float slon = slon_bfr[i][j]; // get doppler and range for pixel // may change this to operate on projected lat and lon for speed l1i.latLonToDopplerAndRange(slon,slat, fdop_in_Hz, range_in_km); // check to see if pixel is on same side of nadir as boresight. bool goodlook = l1i.goodSideOfNadir(slon,slat); bool inbounds = false; //#define DEBUG_FIX_REROUTE #ifdef DEBUG_FIX_REROUTE if(fabs(range_in_km-57105.4)< 1 && fabs(fdop_in_Hz-764348)<2 && goodlook){ cout << range_in_km << " " << fdop_in_Hz << " " << goodlook << " " << inbounds << endl; } #endif // check to see if pixel is in useable area and initialize Interpolation if(goodlook) inbounds=l1i.initInterpolate(fdop_in_Hz, range_in_km); bool max_looks_exceeded = enable_max_looks && (num_looks[i][bn][j]>=max_looks_allowed+num_looks_to_skip); if(inbounds) valid_pixels_found++; // if doppler/range within processor window if(inbounds && !max_looks_exceeded){ // if edges are useable we do not have enough margin // throw an error if(j==j_min || j==j_max || abs_i==i_min || abs_i== i_max){ bad_margin=true; } // this code allows the first N looks of a pixel to be skipped // add to num_looks num_looks[i][bn][j]++; if(num_looks[i][bn][j]<num_looks_to_skip){ // this code allows the first N looks of a pixel to be skipped continue; } // interpolate s0 to point, add to s0_uncorr_bfr[beamnum-1] float s0=l1i.sigma0Interpolate(fdop_in_Hz, range_in_km); if(mark_nadir_amb){ if(l1i.nadirAmb(fdop_in_Hz,range_in_km)){ s0=-1000; } } s0_uncorr_bfr[i][bn][j]+=s0; // interpolate X to point, add to X_bfr[beamnum-1] float X = l1i.XInterpolate(); float s0ns= (s0*X-spp.quant_noise_offset-spp.thermal_noise_offset*spp.quant_noise_scale)/spp.quant_noise_scale; s0ns/=X; float s0ne= spp.quant_noise_offset/(X*spp.quant_noise_scale)+spp.thermal_noise_offset/X; s0_nsub_uncorr_bfr[i][bn][j]+=s0ns; s0ne_bfr[i][bn][j]+=s0ne; if(procMode==STEREO){ if(max_X_bfr[i][bn][j]<X){ max_X_bfr[i][bn][j]=X; nom_burst_num[i][bn][j]=burst_no; range_bfr[i][bn][j]=l1i.rawRange(fdop_in_Hz,range_in_km); dop_bfr[i][bn][j]=l1i.rawDoppler(fdop_in_Hz); } } else{ // compute incidence angle at point, add to inc_bfr[beam_num-1] float inc = l1i.getIncidenceAngle(slat,slon); inc_bfr[i][bn][j] += inc; } if(procMode==TOPO || procMode==TOPO_PLUS){ resfactor[i][bn][j]+=area_pixel[j]/burst_resolution; noise_equiv_s0[i][bn][j]+=(spp.thermal_noise_offset*spp.quant_noise_scale+spp.quant_noise_offset)/X/spp.quant_noise_scale; Xambig_bfr[i][bn][j]+=l1i.XAmbigInterpolate(); } if(procMode==NORMAL){ // update start and end_burst_num if(start_burst_num[i][bn][j]<0) start_burst_num[i][bn][j]=burst_no; end_burst_num[i][bn][j]=burst_no; } if(replace_X_mode) X=replace_X_value; X_bfr[i][bn][j]+=X; if(dbg.level>1 && j==dbg.level){ dbg.file << "Pixel abs_i=" << abs_i << " i=" << i << " j=" << j << " bn=" << bn << " num_looks=" << num_looks[i][bn][j] << endl; } } } } // warn if no valid pixels were found if(valid_pixels_found==0){ cerr << endl; cerr << "Warning BIDR::stripProcessAndWrite found no valid pixels for burst# " << burst_no << endl; } if(dbg.level){ dbg.file << "BIDR::stripProcessAndWrite:Burst #" << burst_no << " " << valid_pixels_found << " Valid pixels were found."<< endl; } // warn if usable area is clipped in processing if(bad_margin){ cerr << endl; cerr << "Warning: BIDR::stripProcessAndWrite: Not enough margin for burst# " +toStr(burst_no) << endl; cerr << "Warning(cont.): Examine L1I::computeLatLonBounds and increase the BURST_PAD_FACTOR" << endl; cerr << "Warning(cont) L1I::boundaryReport follows ...." << endl; l1i.reportBoundary(proj); } // add 1 to all valid bursts_since_update data. incrementBurstsSinceUpdate(); } // output oldest Longitude Line to BIDR files void BIDR::outputLine(const SARProcParams& spp){ static DebugInfo dbg("BIDR::outputLine"); // get oldest index int first_i=grid.firstValidLongitudeIndex(); unsigned int numlats=grid.numLats(); // No output in the event that BIDR region forcing is employed // and we are outside the forced region if(!spp.force_bidr_region || (num_lines_of_output >= spp.forced_first_line && num_lines_of_output <= spp.forced_last_line)){ if(output_beam_deltas) outputBeamDeltas(spp); if(dbg.level){ dbg.file << "BIDR::outputLine" << num_lines_of_output+1 << " out of " << grid.totalNumLons() << " Relative index =" << first_i << " Absolute index =" << grid.absStartValidIndex() << endl; float lon_in_rad=grid.lineNumberToLonInRad(num_lines_of_output); float lat_in_rad=grid.latInRad(grid.numLats()/2); float slat = proj.standardLatInRad(lon_in_rad,lat_in_rad); float slon = proj.standardLonInRad(lon_in_rad,lat_in_rad); dbg.file << "Oblique Lon,Lat of center pixel is: ( " << lon_in_rad*radtodeg << "," << lat_in_rad*radtodeg << endl; dbg.file << "PE Lon,Lat of center pixel is: ( " << slon*radtodeg << "," << slat*radtodeg << endl; } // for each latitude pixel in line for(unsigned int j=0;j<numlats;j++){ // foreach beam (NUM_REQUIRED_LOOKS must be obtained for each beam // regardless of feathering) for(int b=0;b<num_beams;b++){ num_looks[first_i][b][j]-=num_looks_to_skip; if(dbg.level>1 && j==(unsigned int)dbg.level){ dbg.file << "Pixel first_i=" << first_i << " j=" << j << " b=" << b << " num_looks=" << num_looks[first_i][b][j] << endl; } if(num_looks[first_i][b][j]<num_looks_required || isnan(s0_uncorr_bfr[first_i][b][j])){ s0_uncorr_bfr[first_i][b][j]=BAD_VALUE; s0_nsub_uncorr_bfr[first_i][b][j]=BAD_VALUE; s0ne_bfr[first_i][b][j]=BAD_VALUE; if(output_enable_[INC])inc_bfr[first_i][b][j]=BAD_VALUE; X_bfr[first_i][b][j]=BAD_VALUE; if(output_enable_[RANGE])range_bfr[first_i][b][j]=BAD_VALUE; if(output_enable_[DOPPLER])dop_bfr[first_i][b][j]=BAD_VALUE; if(output_enable_[NOMINAL_BURST_NUM])nom_burst_num[first_i][b][j]=-1; if(output_enable_[START_BURST_NUM])start_burst_num[first_i][b][j]=-1; if(output_enable_[END_BURST_NUM])end_burst_num[first_i][b][j]=-1; if(procMode==TOPO || procMode==TOPO_PLUS){ resfactor[first_i][b][j]=0; noise_equiv_s0[first_i][b][j]=BAD_VALUE; Xambig_bfr[first_i][b][j]=BAD_VALUE; } } // normalize pixel for each beam (divide by num_looks) else{ X_bfr[first_i][b][j]/=num_looks[first_i][b][j]; s0_uncorr_bfr[first_i][b][j]/=num_looks[first_i][b][j]; s0_nsub_uncorr_bfr[first_i][b][j]/=num_looks[first_i][b][j]; s0ne_bfr[first_i][b][j]/=num_looks[first_i][b][j]; if(output_enable_[INC])inc_bfr[first_i][b][j]/=num_looks[first_i][b][j]; if(procMode==TOPO || procMode==TOPO_PLUS){ resfactor[first_i][b][j]/=num_looks[first_i][b][j]; noise_equiv_s0[first_i][b][j]/=num_looks[first_i][b][j]; Xambig_bfr[first_i][b][j]/=num_looks[first_i][b][j]; } } } // End of beam loop // merge multiple beams and computed beam mask // may handle multiple strategies using up to // all of longitude line X values for each beam // and parameters in spp object // Appropriately handles BAD_VALUES; // perform beam to beam weighting and // compute beam mask unsigned char beam_mask=0; float s0_uncorr=BAD_VALUE, X=BAD_VALUE, s0ns=BAD_VALUE, s0ne=BAD_VALUE; float inc=BAD_VALUE; int burst_num_1=0,burst_num_2=0; int numlooks=0; float range=BAD_VALUE,doppler=BAD_VALUE; multipleBeamMerge(spp,first_i,j,beam_mask,s0_uncorr,inc,burst_num_1, burst_num_2,numlooks,X,s0ns,s0ne,doppler,range); // update topoplus arrays if(procMode==TOPO_PLUS & overlap_set){ // determine relevant indices into topoplus arrays // (place in overlap and profile number) for(int pn=0;pn<4;pn++){ if((int)j<=overlap_col[pn][num_lines_of_output]+overlap_width[pn][num_lines_of_output] && (int)j>=overlap_col[pn][num_lines_of_output]-overlap_width[pn][num_lines_of_output] && overlap_width[pn][num_lines_of_output] > 0){ int j2=(int)j-overlap_col[pn][num_lines_of_output]+overlap_width[pn][num_lines_of_output]; updateTopoPlusArrays(spp,first_i,j,pn,num_lines_of_output,j2); } } } // fetch latitude and longitude in standard projection // in radians float slat = slat_bfr[first_i][j]; float slon = slon_bfr[first_i][j]; // compute incidence angle corrected sigma0 // appropriately handle BAD_VALUES float s0_corr=BAD_VALUE; if(output_enable_[S0_CORR]){ if(spp.noise_subtraction_on) s0_corr = incAngleCorrect(s0ns,inc,slat,slon,inc_correction_model); else s0_corr = incAngleCorrect(s0_uncorr,inc,slat,slon,inc_correction_model); } // update checksum checksum_[BEAMMASK] += beam_mask; // All lats and lon in radians until output in degrees by multiplying // by rtd float slat_in_degrees=slat*radtodeg; float slon_in_degrees=slon*radtodeg; float inc_in_degrees=inc*radtodeg; if(numlooks<num_looks_required || !output_enable_[INC]) inc_in_degrees=BAD_VALUE; // write pixel to appropriate io buffers beammask_io_bfr[j]=beam_mask; s0_corr_io_bfr[j]=s0_corr; lat_io_bfr[j]=slat_in_degrees; lon_io_bfr[j]=positiveWestLon(slon_in_degrees); inc_io_bfr[j]=inc_in_degrees; range_io_bfr[j]=range; dop_io_bfr[j]=doppler; s0_uncorr_io_bfr[j]=s0_uncorr; start_burst_num_io_bfr[j]=burst_num_1; nom_burst_num_io_bfr[j]=burst_num_1; end_burst_num_io_bfr[j]=burst_num_2; if(numlooks>=255){ num_looks_io_bfr[j]=(unsigned char)255; } else{ num_looks_io_bfr[j]=(unsigned char)numlooks; } X_io_bfr[j]=X; // HACK to output s0_nsub_uncorr to X file until we add the new file if(spp.noise_subtraction_on) X_io_bfr[j]=s0ns; s0ne_io_bfr[j]=s0ne; float s0std; if(s0ne==BAD_VALUE || s0ns==BAD_VALUE) s0std=BAD_VALUE; else s0std=sqrt((fabs(s0ns)*fabs(s0ns)+2*fabs(s0ns)*s0ne+s0ne*s0ne)/numlooks); std_io_bfr[j]=s0std; // Update values to be written to PDS label if (minimum_latitude_ > slat_in_degrees) minimum_latitude_ = slat_in_degrees; if (maximum_latitude_ < slat_in_degrees) maximum_latitude_ = slat_in_degrees; // Shift slon_in_degrees to [-180, 180) to avoid discontinuity at 0 degrees if (dbg.level==2) { dbg.file << "BIDR::outputLine: "; dbg.file << "min, max lon and slon_in_degrees before shift:" << minimum_longitude_ << " " << maximum_longitude_ << " " << slon_in_degrees << endl; } // set first_longitude for first pixel if(first_longitude_==-1000){ first_longitude_=slon_in_degrees; minimum_longitude_=slon_in_degrees+180.0; maximum_longitude_=slon_in_degrees-180.0; } while (slon_in_degrees >= first_longitude_+180.0) { slon_in_degrees -= 360.0; } while (slon_in_degrees < first_longitude_-180.0) { slon_in_degrees += 360.0; } if (minimum_longitude_ > slon_in_degrees) minimum_longitude_ = slon_in_degrees; if (maximum_longitude_ < slon_in_degrees) maximum_longitude_ = slon_in_degrees; if (dbg.level==2) { dbg.file << "BIDR::outputLine: "; dbg.file << "min, max lon and slon_in_degrees after shift:" << minimum_longitude_ << " " << maximum_longitude_ << " " << slon_in_degrees << endl; } } // end of latitude loop // output i/o buffers to the BIDR files switch (procMode){ case NORMAL: if( (fwrite((void*)beammask_io_bfr,sizeof(char),numlats,beammask_file)!=numlats) || (fwrite((void*)s0_corr_io_bfr,sizeof(float),numlats,s0_corr_file)!=numlats) || (fwrite((void*)lat_io_bfr,sizeof(float),numlats,lat_file)!=numlats) || (fwrite((void*)lon_io_bfr,sizeof(float),numlats,lon_file)!=numlats) || (fwrite((void*)inc_io_bfr,sizeof(float),numlats,inc_file)!=numlats) || (fwrite((void*)s0_uncorr_io_bfr,sizeof(float),numlats,s0_uncorr_file)!=numlats) || (fwrite((void*)start_burst_num_io_bfr,sizeof(int),numlats,start_burst_num_file)!=numlats) || (fwrite((void*)end_burst_num_io_bfr,sizeof(int),numlats,end_burst_num_file)!=numlats) || (fwrite((void*)num_looks_io_bfr,sizeof(unsigned char),numlats,num_looks_file)!=numlats) || (fwrite((void*)X_io_bfr,sizeof(float),numlats,X_file)!=numlats) || (fwrite((void*)std_io_bfr,sizeof(float),numlats,std_file)!=numlats) || (fwrite((void*)s0ne_io_bfr,sizeof(float),numlats,s0ne_file)!=numlats) ){ cerr << "BIDR::outputLine error writing BIDR files." << endl; exit(1); } break; case TOPO: case TOPO_PLUS: updateTopoArrays(first_i); if( (fwrite((void*)beammask_io_bfr,sizeof(char),numlats,beammask_file)!=numlats) || (fwrite((void*)s0_uncorr_io_bfr,sizeof(float),numlats,s0_uncorr_file)!=numlats) || (fwrite((void*)num_looks_io_bfr,sizeof(unsigned char),numlats,num_looks_file)!=numlats) || (fwrite((void*)X_io_bfr,sizeof(float),numlats,X_file)!=numlats) ){ cerr << "BIDR::outputLine error writing BIDR files." << endl; exit(1); } break; case STEREO: if( (fwrite((void*)beammask_io_bfr,sizeof(char),numlats,beammask_file)!=numlats) || (fwrite((void*)range_io_bfr,sizeof(float),numlats,range_file)!=numlats) || (fwrite((void*)dop_io_bfr,sizeof(float),numlats,dop_file)!=numlats) || (fwrite((void*)s0_uncorr_io_bfr,sizeof(float),numlats,s0_uncorr_file)!=numlats) || (fwrite((void*)nom_burst_num_io_bfr,sizeof(int),numlats,nom_burst_num_file)!=numlats) || (fwrite((void*)X_io_bfr,sizeof(float),numlats,X_file)!=numlats) ){ cerr << "BIDR::outputLine error writing BIDR files." << endl; exit(1); } break; default: cerr << "Bad BIDR::procMode in BIDR::outputLine" << endl; exit(1); } // end of procMode switch } // end of forced region conditional // advance Grid valid region by one longitude index grid.advance(); num_lines_of_output++; // reinitialize the line which was just written initLongitudeLine(first_i); // calculate a new line of standard lat/lon values int numlons=grid.numLons(); for(unsigned int j=0;j<numlats;j++){ double lon_in_rad=grid.lineNumberToLonInRad(num_lines_of_output+numlons-1); double lat_in_rad=grid.latInRad(j); slat_bfr[first_i][j]=proj.standardLatInRad(lon_in_rad,lat_in_rad); slon_bfr[first_i][j]=proj.standardLonInRad(lon_in_rad,lat_in_rad); } if (dbg.level) { dbg.file << "BIDR::outputLine:" << endl; dbg.file << "Maximum latitude (deg): " << maximum_latitude_ << endl; dbg.file << "Minimum latitude (deg): " << minimum_latitude_ << endl; dbg.file << "PE Maximum longitude (deg): " << maximum_longitude_ << endl; dbg.file << "PE Minimum longitude (deg): " << minimum_longitude_ << endl; } } void BIDR::outputBeamDeltas(const SARProcParams& spp){ if(procMode==STEREO || procMode==TOPO || procMode==TOPO_PLUS){ cerr << "BIDR::outputBeamDeltas fails in STEREO or TOPO mode" << endl; exit(1); } int i=grid.firstValidLongitudeIndex(); int rowno=num_lines_of_output+1; // compute SABs int sab[5]; int n=grid.numLats(); if(spp.single_beam_mode){ ErrorMessage e("Cannot Output Beam Deltas in single_beam_mode"); e.throwMe(); } for(int b=0;b<5;b++){ int max_sab=-1; int min_sab=1000000; for(int j=0;j<n;j++){ if(start_burst_num[i][b][j]>=0 && start_burst_num[i][b][j]<min_sab) min_sab=start_burst_num[i][b][j]; if(end_burst_num[i][b][j]>max_sab) max_sab=end_burst_num[i][b][j]; } int k=(max_sab-min_sab)/5; k=k/2; sab[b]=min_sab+k*5; if(sab[b]>200000) return; } // compute range_offsets (needs spp.set_burst_range_dop = true ) float roff[5]; if(!spp.set_burst_range_dop){ ErrorMessage e("Cannot Output Beam Deltas unless spp.set_burst_range_dop is true"); e.throwMe(); } for(int b=0;b<5;b++) roff[b]=spp.range_offset[sab[b]]; // compute deltas and js float dbeam[4],dbeam_top[4],dbeam_bot[4],inc[4]; float joverlap[4]; int jno[4]; for(int k=0;k<4;k++){ float dval1=0,dval2=0; int dnum=0; float jval=0; int jnum=0; float incval=0; for(int j=0;j<n;j++){ if(num_looks[i][k][j]>=num_looks_required && num_looks[i][k+1][j]>=num_looks_required){ jnum++; jval+=j; dnum++; float s01=s0_uncorr_bfr[i][k][j]/num_looks[i][k][j]; float s02=s0_uncorr_bfr[i][k+1][j]/num_looks[i][k+1][j]; dval1+=s01; dval2+=s02; incval+=(inc_bfr[i][k][j]/num_looks[i][k][j])*radtodeg; #define DEBUGBD #ifdef DEBUGBD int n1=num_looks[i][k][j]; int n2=num_looks[i][k+1][j]; float inc1=(inc_bfr[i][k][j]/num_looks[i][k][j])*radtodeg; float inc2=(inc_bfr[i][k+1][j]/num_looks[i][k+1][j])*radtodeg; float x1=X_bfr[i][k][j]/n1; float x2=X_bfr[i][k+1][j]/n2; int iinc1=(int)(floor(inc1*1000+0.5)); int iinc2=(int)(floor(inc2*1000+0.5)); int is01=(int)(floor(s01*1000+0.5)); int is02=(int)(floor(s02*1000+0.5)); int ix1=(int)(floor(x1+0.5)); int ix2=(int)(floor(x2+0.5)); if(fwrite(&rowno,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&j,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&k,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&is01,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&is02,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&ix1,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&ix2,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&iinc1,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&iinc2,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&n1,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&n2,sizeof(int),1,beam_deltas_file)!=1) { ErrorMessage e("Cannot write to beam_deltas_file"); e.throwMe(); } #endif } } joverlap[k]=jval/jnum; dbeam[k]=dval1/dval2; jno[k]=jnum; dbeam_top[k]=dval1; dbeam_bot[k]=dval2; inc[k]=incval/jnum; } // write to file int iroff[5],ij[4],idbeam[4],itop[4],ibot[4],iinc[4]; for(int k=0;k<5;k++) iroff[k]=int(floor(roff[k]*1000 + 0.5)); for(int k=0;k<4;k++){ ij[k]=int(floor(joverlap[k]*1000 + 0.5)); idbeam[k]=int(floor(dbeam[k]*1000 + 0.5)); iinc[k]=int(floor(inc[k]*1000 + 0.5)); itop[k]=int(floor(dbeam_top[k]*10000 + 0.5)); ibot[k]=int(floor(dbeam_bot[k]*10000 + 0.5)); } #ifndef DEBUGBD if(fwrite(&rowno,sizeof(int),1,beam_deltas_file)!=1 ||fwrite(&(sab[0]),sizeof(int),5,beam_deltas_file)!=5 || fwrite(&(iroff[0]),sizeof(int),5,beam_deltas_file)!=5 || fwrite(&(ij[0]),sizeof(int),4,beam_deltas_file)!=4 || fwrite(&(idbeam[0]),sizeof(int),4,beam_deltas_file)!=4 || fwrite(&(itop[0]),sizeof(int),4,beam_deltas_file)!=4 || fwrite(&(ibot[0]),sizeof(int),4,beam_deltas_file)!=4 || fwrite(&(iinc[0]),sizeof(int),4,beam_deltas_file)!=4 || fwrite(&(jno[0]),sizeof(int),4,beam_deltas_file)!=4){ ErrorMessage e("Cannot write to beam_deltas_file"); e.throwMe(); } #endif printf("ROW %d SABS %d %d %d %d %d ROFF %g %g %g %g %g\n", rowno,sab[0],sab[1],sab[2],sab[3],sab[4],roff[0],roff[1], roff[2],roff[3],roff[4]); printf("JS %g %g %g %g DBEAMS %g %g %g %g INC %g %g %g %g \n", joverlap[0],joverlap[1],joverlap[2],joverlap[3], dbeam[0],dbeam[1],dbeam[2],dbeam[3],inc[0],inc[1],inc[2],inc[3]); } void BIDR::initLongitudeLine(int i) { int num_lats=grid.numLats(); for(int b=0;b<num_beams;b++){ for(int j=0;j<num_lats;j++){ if(output_enable_[START_BURST_NUM])start_burst_num[i][b][j]=-1; if(output_enable_[END_BURST_NUM])end_burst_num[i][b][j]=-1; num_looks[i][b][j]=0; if(output_enable_[INC])inc_bfr[i][b][j]=0; if(procMode==STEREO) max_X_bfr[i][b][j]=0; X_bfr[i][b][j]=0; s0_uncorr_bfr[i][b][j]=0; s0_nsub_uncorr_bfr[i][b][j]=0; s0ne_bfr[i][b][j]=0; if(procMode==TOPO || procMode==TOPO_PLUS){ noise_equiv_s0[i][b][j]=0; resfactor[i][b][j]=0; Xambig_bfr[i][b][j]=0; } } } bursts_since_update[i]=0; for(int b=0;b<num_beams;b++){ beams_found[i][b]=false; } for(int j=0;j<num_lats;j++){ slat_bfr[i][j]=0; slon_bfr[i][j]=0; } } BIDR::~BIDR() { int num_lons=grid.numLons(); int num_lats=grid.numLats(); free(area_pixel); free_array((void*)s0_uncorr_bfr,3,num_lons,num_beams,num_lats); free_array((void*)s0_nsub_uncorr_bfr,3,num_lons,num_beams,num_lats); free_array((void*)s0ne_bfr,3,num_lons,num_beams,num_lats); free_array((void*)X_bfr,3,num_lons,num_beams,num_lats); free_array((void*)bursts_since_update,1,num_lons); free_array((void*)beams_found,2,num_lons,num_beams); free_array((void*)num_looks,3,num_lons,num_beams,num_lats); free_array((void*)slat_bfr,2,num_lons,num_lats); free_array((void*)slon_bfr,2,num_lons,num_lats); free_array((void*)checksum_,1,BIDRTYPECOUNT); free_array((void*)beammask_io_bfr,1,num_lats); free_array((void*)s0_corr_io_bfr,1,num_lats); free_array((void*)lat_io_bfr,1,num_lats); free_array((void*)lon_io_bfr,1,num_lats); free_array((void*)inc_io_bfr,1,num_lats); free_array((void*)range_io_bfr,1,num_lats); free_array((void*)dop_io_bfr,1,num_lats); free_array((void*)s0_uncorr_io_bfr,1,num_lats); free_array((void*)start_burst_num_io_bfr,1,num_lats); free_array((void*)end_burst_num_io_bfr,1,num_lats); free_array((void*)nom_burst_num_io_bfr,1,num_lats); free_array((void*)num_looks_io_bfr,1,num_lats); if(procMode==NORMAL){ free_array((void*)inc_bfr,3,num_lons,num_beams,num_lats); free_array((void*)start_burst_num,3,num_lons,num_beams,num_lats); free_array((void*)end_burst_num,3,num_lons,num_beams,num_lats); } if(procMode==STEREO){ free_array((void*)range_bfr,3,num_lons,num_beams,num_lats); free_array((void*)dop_bfr,3,num_lons,num_beams,num_lats); free_array((void*)max_X_bfr,3,num_lons,num_beams,num_lats); free_array((void*)nom_burst_num,3,num_lons,num_beams,num_lats); } if(procMode==TOPO || procMode==TOPO_PLUS){ free_array((void*)inc_bfr,3,num_lons,num_beams,num_lats); free_array(dsigma0,2,4,MAX_BIDR_LINES); free_array(topo_inc1,2,4,MAX_BIDR_LINES); free_array(topo_inc2,2,4,MAX_BIDR_LINES); free_array(topo_lat,2,4,MAX_BIDR_LINES); free_array(topo_lon,2,4,MAX_BIDR_LINES); free_array(topo_wnl,2,4,MAX_BIDR_LINES); free_array(mid_ds0,2,4,MAX_BIDR_LINES); free_array(slope_ds0,2,4,MAX_BIDR_LINES); free_array(rms_ds0,2,4,MAX_BIDR_LINES); free_array(power1,2,4,MAX_BIDR_LINES); free_array(power2,2,4,MAX_BIDR_LINES); free_array(noisefloor1,2,4,MAX_BIDR_LINES); free_array(noisefloor2,2,4,MAX_BIDR_LINES); free_array(ambrat1,2,4,MAX_BIDR_LINES); free_array(ambrat2,2,4,MAX_BIDR_LINES); free_array(dsigma0std,2,4,MAX_BIDR_LINES); free_array(dsigma0bias,2,4,MAX_BIDR_LINES); free_array(sumsigma0,2,4,MAX_BIDR_LINES); free_array(overlap_col,2,4,MAX_BIDR_LINES); free_array(overlap_width,2,4,MAX_BIDR_LINES); free_array((void*)resfactor,3,num_lons,num_beams,num_lats); free_array((void*)noise_equiv_s0,3,num_lons,num_beams,num_lats); free_array((void*)Xambig_bfr,3,num_lons,num_beams,num_lats); } if(procMode==TOPO_PLUS){ free_array(topoplus_s01,3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); free_array(topoplus_s02,3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); free_array(topoplus_s0ne1,3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); free_array(topoplus_s0ne2,3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); free_array(topoplus_s0baqscale1,3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); free_array(topoplus_s0baqscale2,3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); free_array(topoplus_s0amb1,3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); free_array(topoplus_s0amb2,3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH); } closeFiles(); } void BIDR::closeFiles(){ if(beam_deltas_file)fclose(beam_deltas_file); if(beammask_file) fclose(beammask_file); if(X_file) fclose(X_file); if(std_file) fclose(std_file); if(s0ne_file) fclose(s0ne_file); if(s0_corr_file) fclose(s0_corr_file); if(lat_file) fclose(lat_file); if(lon_file) fclose(lon_file); if(range_file) fclose(range_file); if(dop_file) fclose(dop_file); if(inc_file) fclose(inc_file); if(s0_uncorr_file) fclose(s0_uncorr_file); if(start_burst_num_file) fclose(start_burst_num_file); if(end_burst_num_file) fclose(end_burst_num_file); if(nom_burst_num_file) fclose(nom_burst_num_file); if(num_looks_file) fclose(num_looks_file); if(topoplus_file) fclose(topoplus_file); } bool BIDR::longitudeLineComplete(int i, const SARProcParams& spp){ bool retval=false; DebugInfo dbg("BIDR::longitudeLineComplete"); if(dbg.level){ dbg.file << "BIDR::LongitudeLineComplete called for index="<<i << endl; dbg.file << " burst_since_update="<< bursts_since_update[i] << " beams_found=["; for(int c=0;c<num_beams;c++) dbg.file << " " << beams_found[i][c]; dbg.file << " ]" << endl; } // need to not have been updated for last 10 bursts to be complete if(bursts_since_update[i]>10){ retval=true; } return(retval); } void BIDR::multipleBeamMerge(const SARProcParams& spp, int i, int j, unsigned char& beam_mask, float& s0_uncorr, float& inc, int& burstno1, int& burstno2, int& numlooks, float& X, float& s0ns, float& s0ne, float& doppler, float& range){ int b=0; // selected beam index 0-4 // Single beam mode := only 1 beam available select that beam if (spp.single_beam_mode){ b=0; // allows less memory usage for single beam mode } // Pick the best beam, does not do a weighted sum // best beam definition is currently // must looks, and if looks are equal highest Xfactor // this should handle BAD_VALUES correctly since it just passes the values // for the selected beam else if(!feather_beams){ b=-1; int most_looks=0; float bestX=-1e99; if(Xcheckdir==-1) bestX=1e99; if((procMode==TOPO || procMode==TOPO_PLUS) && overlap_set){ int k=num_lines_of_output; bool beam1_left=(overlap_col[0][k]<overlap_col[1][k]); if(beam1_left==true){ if(j<overlap_col[0][k]-overlap_width[0][k]) b=0; else if(j<overlap_col[0][k]) b=1; else if(j<=overlap_col[0][k]+overlap_width[0][k]) b=0; else if(j<overlap_col[1][k]-overlap_width[1][k]) b=1; else if(j<overlap_col[1][k]) b=2; else if(j<=overlap_col[1][k]+overlap_width[1][k]) b=1; else if(j<overlap_col[2][k]-overlap_width[2][k]) b=2; else if(j<overlap_col[2][k]) b=3; else if(j<=overlap_col[2][k]+overlap_width[2][k]) b=2; else if(j<overlap_col[3][k]-overlap_width[3][k] ) b=3; else if(j<overlap_col[3][k]) b=4; else if(j<=overlap_col[3][k]+overlap_width[3][k] ) b=3; else b=4; } else{ if(j>overlap_col[0][k]+overlap_width[0][k]) b=0; else if(j>overlap_col[0][k]) b=1; else if(j>=overlap_col[0][k]-overlap_width[0][k]) b=0; else if(j>overlap_col[1][k]+overlap_width[1][k]) b=1; else if(j>overlap_col[1][k]) b=2; else if(j>=overlap_col[1][k]-overlap_width[1][k]) b=1; else if(j>overlap_col[2][k]+overlap_width[2][k]) b=2; else if(j>overlap_col[2][k]) b=3; else if(j>=overlap_col[2][k]-overlap_width[2][k]) b=2; else if(j>overlap_col[3][k]+overlap_width[3][k]) b=3; else if(j>overlap_col[3][k]) b=4; else if(j>=overlap_col[3][k]-overlap_width[3][k]) b=3; else b=4; } if(num_looks[i][b][j]==0) b=-1; } if(dominant_beam3 && num_looks[i][2][j]>num_looks_required){ b=2; } // nominal beam selection is used if neither special cases applies // or TOPO beam selection fails due to nonoverlapping case. if(b==-1){ b=0; for(int t=0;t<num_beams;t++){ if(num_looks[i][t][j]>most_looks){ most_looks=num_looks[i][t][j]; b=t; bestX=X_bfr[i][t][j]; } else if(num_looks[i][t][j]==most_looks){ if(Xcheckdir>0 && X_bfr[i][t][j]>bestX){ b=t; bestX=X_bfr[i][t][j]; } else if(Xcheckdir<0 && X_bfr[i][t][j]<bestX){ b=t; bestX=X_bfr[i][t][j]; } } } } } if(!feather_beams){ // Compute output quantities from selected beam if(spp.single_beam_mode) beam_mask=0x01 << spp.beam_number-1; else beam_mask=0x01 << b; s0_uncorr=s0_uncorr_bfr[i][b][j]; if(procMode==NORMAL){ inc=inc_bfr[i][b][j]; burstno1=start_burst_num[i][b][j]; burstno2=end_burst_num[i][b][j]; } if(procMode==TOPO || procMode==TOPO_PLUS){ inc=inc_bfr[i][b][j]; } if(procMode==STEREO){ range=range_bfr[i][b][j]; doppler=dop_bfr[i][b][j]; burstno1=nom_burst_num[i][b][j]; } numlooks=num_looks[i][b][j]; X=X_bfr[i][b][j]; s0ns=s0_nsub_uncorr_bfr[i][b][j]; s0ne=s0ne_bfr[i][b][j]; // if numlooks is zero set beam mask to zero as well // (all other bad values should automatically be handled // Notice that for nonzero numlooks some beam is selected even if // there are not enough looks to produce a valid s0 if(numlooks==0) beam_mask=0; } // beam feathering code if(feather_beams){ if(procMode==STEREO || procMode==TOPO || procMode==TOPO_PLUS){ cerr << "BIDR::multipleBeamMerge Beam Feathering incompatible with STEREO or TOPO mode" << endl; exit(1); } // loop through beams bool isvalid=false; // boolean to check if any beam is valid float sumw=0.0; // sum of weights normailiztion constant float w; int bmsk; // intialize pixel value quantities beam_mask=0; s0_uncorr=0; inc=0; int burstno1=100000000; int burstno2=-1; X=0; s0ns=0; s0ne=0; numlooks=0; for(int b=0;b<5;b++){ if(num_looks[i][b][j]>=num_looks_required){ isvalid=true; w=1.0/sqrt((float)num_looks[i][b][j]); // per beam weight sumw+=w; // keep track of sum of weight bmsk=0x01 << b; // compute bit for beam mask // accumulate backplane and image pixel values over beams beam_mask= beam_mask | bmsk; s0_uncorr+=s0_uncorr_bfr[i][b][j]*w; inc+=inc_bfr[i][b][j]*w; // for completeness (could just take first // valid value) if(start_burst_num[i][b][j] < burstno1) burstno1=start_burst_num[i][b][j]; if(end_burst_num[i][b][j] > burstno2) burstno2=end_burst_num[i][b][j]; numlooks+=num_looks[i][b][j]; X+=X_bfr[i][b][j]*w; s0ns+=s0_nsub_uncorr_bfr[i][b][j]*w; s0ne+=s0ne_bfr[i][b][j]*w; } } // handle no looks case if(!isvalid){ beam_mask=0; s0_uncorr=BAD_VALUE; s0ns=BAD_VALUE; s0ne=BAD_VALUE; inc=BAD_VALUE; X=BAD_VALUE; numlooks=0; // looks for beams with less than the required number of // looks are not counted when feathering is applied burstno1=-1; burstno2=-1; } else{ // normalize pixel values inc=inc/sumw; s0_uncorr=s0_uncorr/sumw; s0ns=s0ns/sumw; s0ne=s0ne/sumw; X=X/sumw; } } // end beam feathering case } void BIDR::updateTopoPlusArrays(const SARProcParams& spp, int i, int j, int pn, int abs_i, int col){ topoplus_s01[pn][abs_i][col]=s0_nsub_uncorr_bfr[i][pn][j]; topoplus_s02[pn][abs_i][col]=s0_nsub_uncorr_bfr[i][pn+1][j]; topoplus_s0ne1[pn][abs_i][col]=noise_equiv_s0[i][pn][j]; topoplus_s0ne2[pn][abs_i][col]=noise_equiv_s0[i][pn+1][j]; topoplus_s0baqscale1[pn][abs_i][col]=s0_nsub_uncorr_bfr[i][pn][j]/(s0_uncorr_bfr[i][pn][j]-noise_equiv_s0[i][pn][j]); topoplus_s0baqscale2[pn][abs_i][col]=s0_nsub_uncorr_bfr[i][pn+1][j]/(s0_uncorr_bfr[i][pn+1][j]-noise_equiv_s0[i][pn+1][j]); // need to fix these topoplus_s0amb1[pn][abs_i][col]=BAD_VALUE; topoplus_s0amb2[pn][abs_i][col]=BAD_VALUE; } float incAngleCorrect(float s0_uncorr, float inc, float slat, float slon, corrTypeE inc_correction_model){ float retval, s,c,s2,c4,f1,f2,f3; static int val=BAD_VALUE_HEX; static float* ptr=(float*) &val; static float BAD_VALUE=*ptr; if(s0_uncorr==BAD_VALUE || inc == BAD_VALUE){ retval=BAD_VALUE; } else if(inc_correction_model==RKIRK01TA){ retval=s0_uncorr*sqrt(2)*sin(inc); } else if(inc_correction_model==ENCELADUS_WYE1){ retval=s0_uncorr*2.9165/(3.71*pow(cos(inc),1.46)); } else if(inc_correction_model==RHEA_WYE1){ retval=s0_uncorr*1.6930/(2.15*pow(cos(inc),1.45)); } else if(inc_correction_model==DIONE_WYE1){ retval=s0_uncorr*1.4253/(1.825*pow(cos(inc),1.5)); } else if(inc_correction_model==HAGHAG){ /** old version s=sin(inc); s2=s*s; c=cos(inc); c4=c*c*c*c; f1=(c4+771.3241*s2); f1=3.3167/sqrt(f1*f1*f1); f2=(c4+18.6535*s2); f2=0.3749/sqrt(f2*f2*f2); f3=0.3456*pow(c,1.7531); retval=s0_uncorr*0.2013/(f1+f2+f3); ***/ s=sin(inc); s2=s*s; c=cos(inc); c4=c*c*c*c; f1=(c4+893.9677*s2); f1=2.8126/sqrt(f1*f1*f1); f2=(c4+34.1366*s2); f2=0.5824/sqrt(f2*f2*f2); f3=0.3767*pow(c,1.9782); retval=s0_uncorr*0.2907/(f1+f2+f3); } /** else if(inc_correction_model==DBLINE041104){ retval=s0_uncorr*dbline_s045/ (pow(10,0.1*(dbline_slope*inc+dbline_offset))); } else if(inc_correction_model==VENUS){ retval=s0_uncorr*venus_s045/muhleman_backscatter(venus_k1,venus_k2,inc); } **/ else retval=BAD_VALUE; return(retval); } float theorBackscatter(float inc, corrTypeE inc_correction_model){ float retval, s,c,s2,c4,f1,f2,f3; static int val=BAD_VALUE_HEX; static float* ptr=(float*) &val; static float BAD_VALUE=*ptr; // avoid numerical problems for inc angles near 90 if(inc>= 0.99999*pi/2) return(0.0); if(inc == BAD_VALUE){ retval=BAD_VALUE; } else if(inc_correction_model==RKIRK01TA){ retval=1/sin(inc); } else if(inc_correction_model==ENCELADUS_WYE1){ retval=(3.71*pow(cos(inc),1.46)); } else if(inc_correction_model==RHEA_WYE1){ retval=(2.15*pow(cos(inc),1.45)); } else if(inc_correction_model==DIONE_WYE1){ retval=(1.825*pow(cos(inc),1.5)); } else if(inc_correction_model==HAGHAG){ s=sin(inc); s2=s*s; c=cos(inc); c4=c*c*c*c; f1=(c4+893.9677*s2); f1=2.8126/sqrt(f1*f1*f1); f2=(c4+34.1366*s2); f2=0.5824/sqrt(f2*f2*f2); f3=0.3767*pow(c,1.9782); retval=f1+f2+f3; } else retval=BAD_VALUE; return(retval); } void BIDR::flush(const SARProcParams& spp){ static DebugInfo dbg("BIDR::flush"); // output remaining valid longitude lines and extra lines so that longitude boundary is in integer degrees. while(num_lines_of_output<grid.totalNumLons()){ outputLine(spp); } if(procMode==TOPO_PLUS && overlap_set){ int n1=4, n2=MAX_BIDR_LINES, n3=MAX_TOPO_OVERLAP_WIDTH; if(!fwrite(&n1,1,sizeof(int),topoplus_file) || !fwrite(&n2,1,sizeof(int),topoplus_file) || !fwrite(&n3,1,sizeof(int),topoplus_file) || !write_array(topoplus_file,topoplus_s01,sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH) || !write_array(topoplus_file,topoplus_s02,sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH) || !write_array(topoplus_file,topoplus_s0ne1,sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH) || !write_array(topoplus_file,topoplus_s0ne2,sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH) || !write_array(topoplus_file,topoplus_s0baqscale1,sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH) || !write_array(topoplus_file,topoplus_s0baqscale2,sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH) || !write_array(topoplus_file,topoplus_s0amb1,sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH) || !write_array(topoplus_file,topoplus_s0amb2,sizeof(float),3,4,MAX_BIDR_LINES,MAX_TOPO_OVERLAP_WIDTH)){ cerr << "Error writing TOPOPLUS file\n" << endl; exit(1); } // debugging tools //cout << "I MADE IT" << endl; //fclose(topoplus_file); //exit(1); } if (dbg.level) { dbg.file << "BIDR::flush:" << endl; dbg.file << "Maximum latitude (deg): " << maximum_latitude_ << endl; dbg.file << "Minimum latitude (deg): " << minimum_latitude_ << endl; dbg.file << "PE Maximum longitude (deg): " << maximum_longitude_ << endl; dbg.file << "PE Minimum longitude (deg): " << minimum_longitude_ << endl; } } void BIDR::incrementBurstsSinceUpdate(){ int numlons=grid.numLons();; for(int i=0;i<=numlons;i++) bursts_since_update[i]++; } //===================================================================== // writeHeaders() // // Write PDS labels to each output BIDR product. //===================================================================== void BIDR::writeHeaders() { writeHeader(inc_file, INC); writeHeader(beammask_file, BEAMMASK); writeHeader(s0_uncorr_file, S0_UNCORR); writeHeader(X_file, S0NSQT_UNCORR); writeHeader(std_file, S0_STD); writeHeader(s0ne_file, S0_NOISE_EQUIV); writeHeader(s0_corr_file, S0_CORR); writeHeader(lat_file, LAT); writeHeader(lon_file, LON); writeHeader(dop_file, DOPPLER); writeHeader(range_file, RANGE); writeHeader(start_burst_num_file, START_BURST_NUM); writeHeader(end_burst_num_file, END_BURST_NUM); writeHeader(nom_burst_num_file, NOMINAL_BURST_NUM); writeHeader(num_looks_file, NUM_LOOKS); } //===================================================================== // rewriteHeaders() // // Rewrite the PDS labels in each output BIDR product with updated // values. //===================================================================== void BIDR::rewriteHeaders() { rewriteHeader(inc_file, INC); rewriteHeader(beammask_file, BEAMMASK); rewriteHeader(s0_uncorr_file, S0_UNCORR); rewriteHeader(X_file, S0NSQT_UNCORR); rewriteHeader(std_file, S0_STD); rewriteHeader(s0ne_file, S0_NOISE_EQUIV); rewriteHeader(s0_corr_file, S0_CORR); rewriteHeader(lat_file, LAT); rewriteHeader(lon_file, LON); rewriteHeader(range_file, RANGE); rewriteHeader(dop_file, DOPPLER); rewriteHeader(start_burst_num_file, START_BURST_NUM); rewriteHeader(end_burst_num_file, END_BURST_NUM); rewriteHeader(nom_burst_num_file, NOMINAL_BURST_NUM); rewriteHeader(num_looks_file, NUM_LOOKS); } //===================================================================== // writeHeader() // // Write a PDS label to a BIDR output file. The file pointer is // assumed to point to the beginning of the file. //===================================================================== void BIDR::writeHeader(FILE* f, BIDRTypeE bidr_type) { if(!output_enable_[bidr_type]) return; string bidr_label = constructLabel(bidr_type); if (bidr_label == EMPTY_STRING) { ErrorMessage e("BIDR::writeHeader: PDS label creation failed"); e.throwMe(); } if(fwrite((void*)bidr_label.c_str(),sizeof(char),bidr_label.length(),f)!=bidr_label.length()){ ErrorMessage e("Error rewriting BIDR label"); e.throwMe(); } } //===================================================================== // rewriteHeader() // // Update the PDS label in a BIDR output file. This method is intended // for use when some of the values in the PDS label need to be updated // and after some (if not all) of the data has been written to the output // file after the original label. rewriteHeader() does not update the // label on a per-value basis; instead, it regenerates the label and // overwrites all of the existing label. The actual recalculation of // new values is contained within constructLabel(). rewriteHeader() also // assumes that constructLabel() will return a label of exactly the same // length (in bytes) as the original label. //===================================================================== void BIDR::rewriteHeader(FILE* f, BIDRTypeE bidr_type) { if(!output_enable_[bidr_type]) return; // Save the current position in the output file and reset the file // pointer to the beginning of the file. After the new label has // been written, restore the file pointer to its original position. int pos = ftell(f); rewind(f); string bidr_label = constructLabel(bidr_type); if (bidr_label == EMPTY_STRING) { ErrorMessage e("BIDR::rewriteHeader: PDS label creation failed"); e.throwMe(); } if(fwrite((void*)bidr_label.c_str(),sizeof(char),bidr_label.length(),f)!=bidr_label.length()){ ErrorMessage e("Error rewriting BIDR label"); e.throwMe(); } if(fseek(f,pos,0)!=0){ ErrorMessage e("BIDR::rewriteHeader: unable to seek back to original file pointer"); e.throwMe(); } } //===================================================================== // constructLabel() // // This method defines the actual keywords and values that appear in // the PDS labels of the BIDR products. The keywords and values are // specific to the BIDR products. The string returned by this method // contains a properly formatted PDS label for the specified type of // BIDR data and is to be prepended to the output data. //===================================================================== string BIDR::constructLabel(BIDRTypeE bidr_type) { // // Construct list of keyword-value pairs for BIDR PDS label // KeyValSeq list; int data_records = grid.totalNumLons(); int record_length = grid.numLats(); string product_creation_time = Time::getCurrentUtcDOYTime(); stringstream buf(ios::out); double line_projection_offset; double sample_projection_offset; double radii[3]; double rotation_matrix[3][3]; DebugInfo dbg("BIDR::constructLabel"); if (check_pds_string_lengths_) { // Populate the table that holds the limits on the lengths of PDS // character values. (The actual checking is done within the // constructor for KeyValPair().) PDSLabel::setPDSCharValLimits(); } // // Calculate values before beginning to construct the label. // // A_AXIS_RADIUS, B_AXIS_RADIUS, C_AXIS_RADIUS // For the general case, the A, B, and C radii are ordered from longest // to shortest radii[0] = default_target_radii[PositionVector::X].km(); radii[1] = default_target_radii[PositionVector::Y].km(); radii[2] = default_target_radii[PositionVector::Z].km(); sort(radii, radii+3); // LINE_PROJECTION_OFFSET, SAMPLE_PROJECTION_OFFSET // start_lon and min_lat are values at the edges of the grid, while // the line and sample projection offsets are calculated relative to // the center of the first pixel in the grid. As a result, calculations // with start_lon and min_lat must apply a half-pixel offset. double pixel_offset = 0.5/pixelsperdegree; double start_lon = grid.startLon() * radtodeg; double min_lat = grid.minLat() * radtodeg; double lon_firstpix = start_lon + pixel_offset; double lat_firstpix = min_lat + pixel_offset; // Wrap longitude to range [-180, 180) degrees while (lon_firstpix < -180.0) lon_firstpix += 360.0; while (lon_firstpix >= 180.0) lon_firstpix -= 360.0; if (dbg.level) { dbg.file << "BIDR::constructLabel:" << endl; dbg.file << "Start lon of grid (deg): " << setprecision(9) << std::fixed << start_lon << endl; dbg.file << "Minimum lat of grid (deg): " << setprecision(9) << std::fixed << min_lat << endl; dbg.file << "Pixel (1,1) center lat (deg): " << setprecision(9) << std::fixed << lat_firstpix << endl; dbg.file << "Pixel (1,1) center lon (deg): " << setprecision(9) << std::fixed << lon_firstpix << endl; } line_projection_offset = -lon_firstpix * pixelsperdegree; sample_projection_offset = -lat_firstpix * pixelsperdegree; // OBLIQUE_PROJ_X_AXIS_VECTOR, OBLIQUE_PROJ_Y_AXIS_VECTOR, // OBLIQUE_PROJ_Z_AXIS_VECTOR proj.rotationMatrix(rotation_matrix); // // Create the list of keyword-value pairs in the order in which they // are to be written to the label. // list.push_back(KeyValPair("PDS_VERSION_ID", pds_version_id_, !IS_ODL_STRING)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair("/* FILE FORMAT AND LENGTH */", EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair("RECORD_TYPE", record_type_, !IS_ODL_STRING)); list.push_back(KeyValPair("RECORD_BYTES", record_length*sample_bits_[bidr_type]/BITS_PER_BYTE)); // // Initialize the next two values to their smallest possible values. // list.push_back(KeyValPair("FILE_RECORDS", data_records+1)); list.push_back(KeyValPair("LABEL_RECORDS", 1)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair( "/* POINTERS TO START RECORDS OF OBJECTS IN FILE */", EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); // // Initialize the next value to its smallest possible value. // list.push_back(KeyValPair("^IMAGE", 2)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair("/* IMAGE DESCRIPTION */", EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair("DATA_SET_ID", data_set_id_, IS_ODL_STRING)); list.push_back(KeyValPair("DATA_SET_NAME", data_set_name_, IS_ODL_STRING)); list.push_back(KeyValPair("PRODUCER_INSTITUTION_NAME", producer_institution_name_, IS_ODL_STRING)); list.push_back(KeyValPair("PRODUCER_ID", producer_id_, !IS_ODL_STRING)); list.push_back(KeyValPair("PRODUCER_FULL_NAME", producer_full_name_, IS_ODL_STRING)); list.push_back(KeyValPair("PRODUCT_ID", productID(bidr_type), !IS_ODL_STRING)); list.push_back(KeyValPair("PRODUCT_VERSION_ID", product_version_, 2, NO_UNITS)); list.push_back(KeyValPair("INSTRUMENT_HOST_NAME", instrument_host_name_, IS_ODL_STRING)); list.push_back(KeyValPair("INSTRUMENT_HOST_ID", instrument_host_id_, !IS_ODL_STRING)); list.push_back(KeyValPair("INSTRUMENT_NAME", instrument_name_, IS_ODL_STRING)); list.push_back(KeyValPair("INSTRUMENT_ID", instrument_id_, !IS_ODL_STRING)); list.push_back(KeyValPair("TARGET_NAME", PDSLabel::toUpper(target_name_), !IS_ODL_STRING)); // // Leave fractional seconds in for now // list.push_back(KeyValPair("START_TIME", sclk_start_.utc("ISOD"), !IS_ODL_STRING)); // // Leave fractional seconds in for now // list.push_back(KeyValPair("STOP_TIME", sclk_stop_.utc("ISOD"), !IS_ODL_STRING)); // // Since PDS defines SPACECRAFT_CLOCK_START_COUNT and // SPACECRAFT_CLOCK_STOP_COUNT as character-valued, format both values as // strings so that their lengths can be limit-checked. // buf << std::setw(9) << std::setfill('0') << sclk_start_.sclk(cassini_str); list.push_back(KeyValPair("SPACECRAFT_CLOCK_START_COUNT", buf.str(), !IS_ODL_STRING)); buf.seekp(0, ios::beg); buf << std::setw(9) << std::setfill('0') << sclk_stop_.sclk(cassini_str); list.push_back(KeyValPair("SPACECRAFT_CLOCK_STOP_COUNT", buf.str(), !IS_ODL_STRING)); // // Leave fractional seconds in for now // list.push_back(KeyValPair("PRODUCT_CREATION_TIME", product_creation_time, !IS_ODL_STRING)); list.push_back(KeyValPair("SOURCE_PRODUCT_ID", source_product_id_, !IS_ODL_STRING)); list.push_back(KeyValPair("MISSION_PHASE_NAME", mission_phase_name_, !IS_ODL_STRING)); list.push_back(KeyValPair("MISSION_NAME", mission_name_, IS_ODL_STRING)); list.push_back(KeyValPair("SOFTWARE_VERSION_ID", software_version_, IS_ODL_STRING)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair( "/* DESCRIPTION OF OBJECTS CONTAINED IN FILE */", EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair("OBJECT", "IMAGE", !IS_ODL_STRING)); list.push_back(KeyValPair("LINES", data_records)); list.push_back(KeyValPair("LINE_SAMPLES", record_length)); list.push_back(KeyValPair("SAMPLE_TYPE", sample_type_[bidr_type], IS_ODL_STRING)); list.push_back(KeyValPair("SAMPLE_BITS", sample_bits_[bidr_type])); list.push_back(KeyValPair("CHECKSUM", checksum(bidr_type), 9, NO_UNITS)); list.push_back(KeyValPair("SCALING_FACTOR", scaling_factor_, 8)); list.push_back(KeyValPair("OFFSET", offset_, 8)); list.push_back(KeyValPair("MISSING_CONSTANT", missing_constant_[bidr_type], IS_ODL_STRING)); list.push_back(KeyValPair("NOTE", note_[bidr_type], IS_ODL_STRING)); list.push_back(KeyValPair("END_OBJECT", "IMAGE", !IS_ODL_STRING)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair("OBJECT", "IMAGE_MAP_PROJECTION", !IS_ODL_STRING)); list.push_back(KeyValPair("^DATA_SET_MAP_PROJECTION", data_set_map_projection_catalog_, IS_ODL_STRING)); list.push_back(KeyValPair("MAP_PROJECTION_TYPE", map_projection_type_, IS_ODL_STRING)); list.push_back(KeyValPair("A_AXIS_RADIUS", radii[0], 6, "km")); list.push_back(KeyValPair("B_AXIS_RADIUS", radii[1], 6, "km")); list.push_back(KeyValPair("C_AXIS_RADIUS", radii[2], 6, "km")); list.push_back(KeyValPair("FIRST_STANDARD_PARALLEL", first_standard_parallel_, IS_ODL_STRING)); list.push_back(KeyValPair("SECOND_STANDARD_PARALLEL", second_standard_parallel_, IS_ODL_STRING)); list.push_back(KeyValPair("POSITIVE_LONGITUDE_DIRECTION", positive_longitude_direction_, !IS_ODL_STRING)); list.push_back(KeyValPair("CENTER_LATITUDE", proj_center_latitude_, 6, "deg")); list.push_back(KeyValPair("CENTER_LONGITUDE", proj_center_longitude_, 6, "deg")); list.push_back(KeyValPair("REFERENCE_LATITUDE", proj.referenceLatitude(), 6, "deg")); list.push_back(KeyValPair("REFERENCE_LONGITUDE", proj.referenceLongitude(), 6, "deg")); list.push_back(KeyValPair("LINE_FIRST_PIXEL", line_first_pixel_)); list.push_back(KeyValPair("LINE_LAST_PIXEL", data_records)); list.push_back(KeyValPair("SAMPLE_FIRST_PIXEL", sample_first_pixel_)); list.push_back(KeyValPair("SAMPLE_LAST_PIXEL", record_length)); list.push_back(KeyValPair("MAP_PROJECTION_ROTATION", map_projection_rotation_, 1, NO_UNITS)); list.push_back(KeyValPair("MAP_RESOLUTION", (double) pixelsperdegree, 1, "pix/deg")); list.push_back(KeyValPair("MAP_SCALE", mapScale(), 8, "km/pix")); list.push_back(KeyValPair("MAXIMUM_LATITUDE", maximum_latitude_, 8, 12, "deg")); list.push_back(KeyValPair("MINIMUM_LATITUDE", minimum_latitude_, 8, 12, "deg")); // Shift longitudes to [0, 360) before positive-west coordinate conversion. // Define extra variables for the shifted longitudes so that we don't // change the initial value of maximum_longitude_ before BIDR::outputLine // is called for the first time. float easternmost_longitude = maximum_longitude_; float westernmost_longitude = minimum_longitude_; while (easternmost_longitude >= 360.0) { easternmost_longitude -= 360.0; } while (easternmost_longitude < 0.0) { easternmost_longitude += 360.0; } while (westernmost_longitude >= 360.0) { westernmost_longitude -= 360.0; } while (westernmost_longitude < 0.0) { westernmost_longitude += 360.0; } list.push_back(KeyValPair("EASTERNMOST_LONGITUDE", positiveWestLon(easternmost_longitude), 8, 12, "deg")); list.push_back(KeyValPair("WESTERNMOST_LONGITUDE", positiveWestLon(westernmost_longitude), 8, 12, "deg")); list.push_back(KeyValPair("LINE_PROJECTION_OFFSET", line_projection_offset, 3, NO_UNITS)); list.push_back(KeyValPair("SAMPLE_PROJECTION_OFFSET", sample_projection_offset, 3, NO_UNITS)); list.push_back(KeyValPair("OBLIQUE_PROJ_POLE_LATITUDE", proj.poleLatitude(), 6, "deg")); list.push_back(KeyValPair("OBLIQUE_PROJ_POLE_LONGITUDE", proj.poleLongitude(), 6, "deg")); list.push_back(KeyValPair("OBLIQUE_PROJ_POLE_ROTATION", proj.poleRotation(), 6, "deg")); list.push_back(KeyValPair("OBLIQUE_PROJ_X_AXIS_VECTOR", rotation_matrix[0], 3, 8, NO_UNITS)); list.push_back(KeyValPair("OBLIQUE_PROJ_Y_AXIS_VECTOR", rotation_matrix[1], 3, 8, NO_UNITS)); list.push_back(KeyValPair("OBLIQUE_PROJ_Z_AXIS_VECTOR", rotation_matrix[2], 3, 8, NO_UNITS)); list.push_back(KeyValPair("LOOK_DIRECTION", PDSLabel::toUpper(look_direction_), !IS_ODL_STRING)); list.push_back(KeyValPair("COORDINATE_SYSTEM_TYPE", coordinate_system_type_, IS_ODL_STRING)); list.push_back(KeyValPair("COORDINATE_SYSTEM_NAME", coordinate_system_name_, IS_ODL_STRING)); list.push_back(KeyValPair("END_OBJECT", "IMAGE_MAP_PROJECTION", !IS_ODL_STRING)); list.push_back(KeyValPair(EMPTY_STRING, EMPTY_STRING, !IS_ODL_STRING)); list.push_back(KeyValPair("END", EMPTY_STRING, !IS_ODL_STRING)); // // Create the PDS label in the proper format. // PDSLabel label(list, record_length*sample_bits_[bidr_type]/BITS_PER_BYTE, data_records, "^IMAGE"); if (dbg.level) { if (bidr_type == LAT) { dbg.file << "BIDR::constructLabel: PDS label for LAT file is" << endl; dbg.file << label.label() << endl; } } return(label.label()); } //===================================================================== // mapScale() // // Return the value of the MAP_SCALE keyword in the PDS label. // The calculation assumes that Titan is a sphere; i.e., its x-, y-, // and z-axes have the same lengths. //===================================================================== double BIDR::mapScale() { double target_radius = (default_target_radii.magnitude()).km()/sqrt(3.0); return(target_radius/(pixelsperdegree * radtodeg)); } //===================================================================== // productID() // // Determine the value of the PRODUCT_ID keyword in the BIDR PDS label. // This value is dependent upon the BIDR data type, the map resolution, // the (standard) latitude, longitude, and hemisphere at the center of // the file, the data take ID, the (Titan) flyby ID, and the product // version. //===================================================================== string BIDR::productID(const BIDRTypeE bidr_type) { string product_id = "BI"; double lat_centerrad, lon_centerrad, slat_center, slon_center; int clat, clon; stringstream buf_stream(ios::app|ios::out); DebugInfo dbg("BIDR::productID"); // BIDR data type // Naming conventions are included for the internal (nondeliverable) // products to avoid problems with the output filenames. switch(bidr_type) { case S0_CORR: product_id += "F"; break; case S0_CORR_DB: product_id += "B"; break; case S0_UNCORR: product_id += "U"; break; case S0NSQT_UNCORR: product_id += "S"; break; case S0_STD: product_id += "D"; break; case S0_NOISE_EQUIV: product_id += "X"; break; case INC: product_id += "E"; break; case LAT: product_id += "T"; break; case LON: product_id += "N"; break; case BEAMMASK: product_id += "M"; break; case START_BURST_NUM: product_id += "J"; break; case END_BURST_NUM: product_id += "K"; break; case NUM_LOOKS: product_id += "L"; break; case NOMINAL_BURST_NUM: case RANGE: case DOPPLER: product_id+= "Z"; break; default: ErrorMessage e("BIDR::productID: unknown BIDR type " + toStr(bidr_type)); e.throwMe(); break; } product_id+= "Q"; // Map resolution switch(pixelsperdegree) { case 1: product_id += "A"; break; case 2: product_id += "B"; break; case 4: product_id += "C"; break; case 8: product_id += "D"; break; case 16: product_id += "E"; break; case 32: product_id += "F"; break; case 64: product_id += "G"; break; case 128: product_id += "H"; break; case 256: product_id += "I"; break; case 512: product_id += "J"; break; default: product_id += "X"; } // Determine the latitude, hemisphere (N/S), and longitude at the center // of the file. The oblique cylindrical center latitude is the average of // the minimum and maximum oblique cylindrical latitudes in the file. The // center longitude is calculated similarly. (The calculation does not need // to account for wraparound, as the grid longitudes are either monotonically // increasing or monotonically decreasing.) Convert the center latitude and // longitude to standard coordinates to obtain the characters needed for // the product ID. double maxlatrad = grid.latInRad(grid.numLats()-1); lat_centerrad = (grid.minLat() + maxlatrad)/2; double endlon; if (grid.lonIncreasing()) { endlon = grid.startLon() + grid.totalNumLons()*degtorad/pixelsperdegree; } else { endlon = grid.startLon() - grid.totalNumLons()*degtorad/pixelsperdegree; } lon_centerrad = (grid.startLon() + endlon)/2; slat_center = radtodeg * proj.standardLatInRad(lon_centerrad, lat_centerrad); slon_center = radtodeg * proj.standardLonInRad(lon_centerrad, lat_centerrad); clat = round_double(slat_center); clon = round_double(positiveWestLon(slon_center)); if (dbg.level) { dbg.file << "BIDR::productID:" << endl; dbg.file << "Center lat (deg): " << slat_center << endl; dbg.file << "PW center lon (deg): " << positiveWestLon(slon_center) << endl; dbg.file << "Min lat (rad): " << grid.minLat() << endl; dbg.file << "Max lat (rad): " << maxlatrad << endl; dbg.file << "Start lon (rad): " << grid.startLon() << endl; dbg.file << "End lon (rad): " << endlon << endl; } buf_stream << std::setw(2) << std::setfill('0') << fabs(clat); if (clat > 0) { buf_stream << "N"; } else { buf_stream << "S"; } // clon is already in the range [0, 360) from proj.standardLonInRad() buf_stream << std::setw(3) << std::setfill('0') << clon; // Data take ID buf_stream << "_D" << std::setw(3) << std::setfill('0') << data_take_id_; // Flyby ID // flyby_id_pass_ is the string following the "T" in the flyby ID. // flyby_id_pass_ is set by BIDR::config, which checks the string for // validity, strips leading zeroes, and converts it to upper-case when // needed. buf_stream << "_T"; for (unsigned int i = 0; i < 3-flyby_id_pass_.length(); i++) { buf_stream << "0"; } buf_stream << flyby_id_pass_; buf_stream << "S" << std::setw(2) << std::setfill('0') << segment_id_; // Product version buf_stream << "_V" << std::setw(2) << std::setfill('0') << product_version_; product_id += buf_stream.str(); return product_id; } //===================================================================== // checksum() // // Return the value of the CHECKSUM keyword in the PDS label for the // specified type of BIDR data. //===================================================================== int BIDR::checksum(const BIDRTypeE bidr_type) { return checksum_[bidr_type]; } //---------------------------------------------------------------------- // filePrefix() // // Assumes UNIX-style directory specifications //---------------------------------------------------------------------- string BIDR::filePrefix(const string filename) { size_t len = filename.length(); size_t i, j; // Find the last occurrence of the directory separator in the input // filename. If the string doesn't contain a separator, point to the // beginning of the string. if ((i = filename.rfind("/")) == string::npos) { i = 0; } else { i++; } string basename = filename.substr(i, len); len = basename.length(); // Find the "." that terminates the file prefix. if ((j = basename.rfind(".")) == string::npos) { j = len; } return(basename.substr(0, j)); } void BIDR::initProcMode(){ for(int c=0;c<BIDRTYPECOUNT;c++) output_enable_[c]=false; switch(procMode){ case NORMAL: output_enable_[INC]=true; output_enable_[BEAMMASK]=true; output_enable_[S0_UNCORR]=true; output_enable_[S0NSQT_UNCORR]=true; output_enable_[S0_STD]=true; output_enable_[S0_NOISE_EQUIV]=true; output_enable_[S0_CORR]=true; output_enable_[LAT]=true; output_enable_[LON]=true; output_enable_[START_BURST_NUM]=true; output_enable_[END_BURST_NUM]=true; output_enable_[NUM_LOOKS]=true; break; case TOPO: case TOPO_PLUS: output_enable_[INC]=true; output_enable_[BEAMMASK]=true; output_enable_[S0_UNCORR]=true; output_enable_[S0NSQT_UNCORR]=true; output_enable_[NUM_LOOKS]=true; break; case STEREO: output_enable_[BEAMMASK]=true; output_enable_[S0_UNCORR]=true; output_enable_[S0NSQT_UNCORR]=true; output_enable_[DOPPLER]=true; output_enable_[RANGE]=true; output_enable_[NOMINAL_BURST_NUM]=true; break; default: cerr << "Fatal error: BIDR has bad procMode" << endl; exit(1); break; } }
35.757346
356
0.673656
[ "geometry", "object", "vector", "model" ]
b44bae5e851c9f13a7936addb71638611acf4158
6,209
cpp
C++
lib/render/OSPRay.cpp
RemiLacroix-IDRIS/VAPOR
33c787b6089ad845f6f989176d839e117fcdb03f
[ "BSD-3-Clause" ]
null
null
null
lib/render/OSPRay.cpp
RemiLacroix-IDRIS/VAPOR
33c787b6089ad845f6f989176d839e117fcdb03f
[ "BSD-3-Clause" ]
null
null
null
lib/render/OSPRay.cpp
RemiLacroix-IDRIS/VAPOR
33c787b6089ad845f6f989176d839e117fcdb03f
[ "BSD-3-Clause" ]
1
2021-12-04T15:35:46.000Z
2021-12-04T15:35:46.000Z
#ifdef WIN32 #define _USE_MATH_DEFINES #include <cmath> #endif #include <vapor/OSPRay.h> #include <stdio.h> #include <stdlib.h> using namespace VOSP; #ifdef BUILD_OSPRAY static int _initialized = false; void ospErrorCallback(OSPError error, const char *msg) { fprintf(stderr, "OSP error "); switch (error) { #define STRINGIFY(x) case x: fprintf(stderr, #x); break; STRINGIFY(OSP_NO_ERROR) STRINGIFY(OSP_UNKNOWN_ERROR) STRINGIFY(OSP_INVALID_ARGUMENT) STRINGIFY(OSP_INVALID_OPERATION) STRINGIFY(OSP_OUT_OF_MEMORY) STRINGIFY(OSP_UNSUPPORTED_CPU) STRINGIFY(OSP_VERSION_MISMATCH) #undef STRINGIFY } fprintf(stderr, ": %s\n", msg); // exit(1); } #endif int VOSP::Initialize(int *argc, char **argv) { #ifdef BUILD_OSPRAY if (_initialized) return 0; OSPError init_error = ospInit(argc, (const char **)argv); if (init_error != OSP_NO_ERROR) return init_error; // Hide deprecated warning. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // If this is not set, OSPRay will crash upon shutdown ospDeviceSetErrorFunc(ospGetCurrentDevice(), ospErrorCallback); #pragma GCC diagnostic pop _initialized = true; return 0; #else return 0; #endif } int VOSP::Shutdown() { // ospShutdown(); // Broken. Do not use. return 0; } std::string VOSP::Version() { #ifdef BUILD_OSPRAY long major = ospDeviceGetProperty(ospGetCurrentDevice(), OSP_DEVICE_VERSION_MAJOR); long minor = ospDeviceGetProperty(ospGetCurrentDevice(), OSP_DEVICE_VERSION_MINOR); long patch = ospDeviceGetProperty(ospGetCurrentDevice(), OSP_DEVICE_VERSION_PATCH); return std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch); #else return "0.0.0"; #endif } bool VOSP::IsVersionAtLeast(int testMajor, int testMinor) { #ifdef BUILD_OSPRAY long major = ospDeviceGetProperty(ospGetCurrentDevice(), OSP_DEVICE_VERSION_MAJOR); long minor = ospDeviceGetProperty(ospGetCurrentDevice(), OSP_DEVICE_VERSION_MINOR); if (major > testMajor || (major == testMajor && minor >= testMinor)) return true; return false; #else return false; #endif } #ifdef BUILD_OSPRAY OSPData VOSP::NewCopiedData(const void *data, OSPDataType type, uint64_t numItems1, uint64_t numItems2, uint64_t numItems3) { OSPData shared = ospNewSharedData(data, type, numItems1, 0, numItems2, 0, numItems3, 0); ospCommit(shared); OSPData opaque = ospNewData(type, numItems1, numItems2, numItems3); ospCommit(opaque); ospCopyData(shared, opaque); ospCommit(opaque); ospRelease(shared); return opaque; } OSPTexture VOSP::OSPDepthFromGLPerspective(float fovy, float aspect, float zNear, float zFar, glm::vec3 cameraDir, glm::vec3 cameraUp, const float *glDepthBuffer, int width, int height) { float *ospDepth = new float[width * height]; // transform OpenGL depth to linear depth for (size_t i=0; i<width*height; i++) { const double z_n = 2.0 * glDepthBuffer[i] - 1.0; ospDepth[i] = 2.0 * zNear * zFar / (zFar + zNear - z_n * (zFar - zNear)); } // transform from orthogonal Z depth to ray distance t glm::vec3 dir_du = normalize(cross(cameraDir, cameraUp)); glm::vec3 dir_dv = normalize(cross(dir_du, cameraDir)); const float imagePlaneSizeY = 2.f * tanf(fovy/2.f * M_PI/180.f); const float imagePlaneSizeX = imagePlaneSizeY * aspect; dir_du *= imagePlaneSizeX; dir_dv *= imagePlaneSizeY; const glm::vec3 dir_00 = cameraDir - .5f * dir_du - .5f * dir_dv; for (size_t j=0; j<height; j++) { for (size_t i=0; i<width; i++) { const glm::vec3 dir_ij = normalize(dir_00 + float(i)/float(width-1) * dir_du + float(j)/float(height-1) * dir_dv); const float t = ospDepth[j*width+i] / dot(cameraDir, dir_ij); ospDepth[j*width+i] = t; } } OSPTexture depthTexture = ospNewTexture("texture2d"); ospSetInt(depthTexture, "format", OSP_TEXTURE_R32F); ospSetInt(depthTexture, "filter", OSP_TEXTURE_FILTER_NEAREST); OSPData data = VOSP::NewCopiedData(ospDepth, OSP_FLOAT, width, height); ospCommit(data); ospSetObject(depthTexture, "data", data); ospRelease(data); delete[] ospDepth; ospCommit(depthTexture); return depthTexture; } // triangle mesh data namespace TriData { float translation[] = {0,0,0}; float vertex[] = { -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f}; float color[] = { 0.9f, 0.5f, 0.5f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.5f, 0.9f, 0.5f, 1.0f}; int32_t index[] = {0, 1, 2, 1, 2, 3}; } OSPGeometricModel Test::LoadTriangle(glm::vec3 scale, const std::string &rendererType) { // Translate Triangle float pos[4*3]; for (int i = 0; i < 4*3; i++) { pos[i] = TriData::vertex[i] * scale[i%3] + TriData::translation[i%3]; } // create and setup model and mesh OSPGeometry mesh = ospNewGeometry("mesh"); OSPData data = NewCopiedData(pos, OSP_VEC3F, 4); // alternatively with an OSPRay managed OSPData // OSPData managed = ospNewData1D(OSP_VEC3F, 4); // ospCopyData1D(data, managed, 0); ospCommit(data); ospSetObject(mesh, "vertex.position", data); ospRelease(data); // we are done using this handle data = ospNewSharedData1D(TriData::color, OSP_VEC4F, 4); ospCommit(data); ospSetObject(mesh, "vertex.color", data); ospRelease(data); data = ospNewSharedData1D(TriData::index, OSP_VEC3UI, 2); ospCommit(data); ospSetObject(mesh, "index", data); ospRelease(data); ospCommit(mesh); OSPMaterial mat = ospNewMaterial(rendererType.c_str(), "obj"); ospCommit(mat); // put the mesh into a model OSPGeometricModel model = ospNewGeometricModel(mesh); ospSetObject(model, "material", mat); ospCommit(model); ospRelease(mesh); ospRelease(mat); return model; } #endif
28.095023
126
0.651957
[ "mesh", "model", "transform" ]
b44f5170f2950f67da0754cea076290ea3d81da8
22,214
cpp
C++
sakura_core/dlg/CDialog.cpp
zlatantan/sakura
a722f9c86f2860606b3f9e7dc79bb169294cfaea
[ "Zlib" ]
1
2019-03-15T16:55:33.000Z
2019-03-15T16:55:33.000Z
sakura_core/dlg/CDialog.cpp
zlatantan/sakura
a722f9c86f2860606b3f9e7dc79bb169294cfaea
[ "Zlib" ]
null
null
null
sakura_core/dlg/CDialog.cpp
zlatantan/sakura
a722f9c86f2860606b3f9e7dc79bb169294cfaea
[ "Zlib" ]
null
null
null
/*! @file @brief Dialog Boxの基底クラス @author Norio Nakatani */ /* Copyright (C) 1998-2001, Norio Nakatani Copyright (C) 2000, jepro Copyright (C) 2001, jepro, Stonee Copyright (C) 2002, aroka, YAZAKI Copyright (C) 2003, MIK, KEITA Copyright (C) 2005, MIK Copyright (C) 2006, ryoji Copyright (C) 2009, ryoji Copyright (C) 2011, nasukoji Copyright (C) 2012, Uchi This source code is designed for sakura editor. Please contact the copyright holder to use this code for other purpose. */ #include "StdAfx.h" #include "dlg/CDialog.h" #include "CEditApp.h" #include "env/CShareData.h" #include "env/DLLSHAREDATA.h" #include "recent/CRecent.h" #include "util/os.h" #include "util/shell.h" #include "util/module.h" /* ダイアログプロシージャ */ INT_PTR CALLBACK MyDialogProc( HWND hwndDlg, // handle to dialog box UINT uMsg, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { CDialog* pCDialog; switch( uMsg ){ case WM_INITDIALOG: pCDialog = ( CDialog* )lParam; if( NULL != pCDialog ){ return pCDialog->DispatchEvent( hwndDlg, uMsg, wParam, lParam ); }else{ return FALSE; } default: // Modified by KEITA for WIN64 2003.9.6 pCDialog = ( CDialog* )::GetWindowLongPtr( hwndDlg, DWLP_USER ); if( NULL != pCDialog ){ return pCDialog->DispatchEvent( hwndDlg, uMsg, wParam, lParam ); }else{ return FALSE; } } } /*! コンストラクタ @date 2002.2.17 YAZAKI CShareDataのインスタンスは、CProcessにひとつあるのみ。 */ CDialog::CDialog(bool bSizable, bool bCheckShareData) { // MYTRACE( _T("CDialog::CDialog()\n") ); /* 共有データ構造体のアドレスを返す */ m_pShareData = &GetDllShareData(bCheckShareData); m_hInstance = NULL; /* アプリケーションインスタンスのハンドル */ m_hwndParent = NULL; /* オーナーウィンドウのハンドル */ m_hWnd = NULL; /* このダイアログのハンドル */ m_hwndSizeBox = NULL; m_bSizable = bSizable; m_lParam = (LPARAM)NULL; m_nShowCmd = SW_SHOW; m_xPos = -1; m_yPos = -1; m_nWidth = -1; m_nHeight = -1; return; } CDialog::~CDialog() { // MYTRACE( _T("CDialog::~CDialog()\n") ); CloseDialog( 0 ); return; } //! モーダルダイアログの表示 /*! @param hInstance [in] アプリケーションインスタンスのハンドル @param hwndParent [in] オーナーウィンドウのハンドル @date 2011.04.10 nasukoji 各国語メッセージリソース対応 */ INT_PTR CDialog::DoModal( HINSTANCE hInstance, HWND hwndParent, int nDlgTemplete, LPARAM lParam ) { m_bInited = FALSE; m_bModal = TRUE; m_hInstance = hInstance; /* アプリケーションインスタンスのハンドル */ m_hwndParent = hwndParent; /* オーナーウィンドウのハンドル */ m_lParam = lParam; m_hLangRsrcInstance = CSelectLang::getLangRsrcInstance(); // メッセージリソースDLLのインスタンスハンドル return ::DialogBoxParam( m_hLangRsrcInstance, MAKEINTRESOURCE( nDlgTemplete ), m_hwndParent, MyDialogProc, (LPARAM)this ); } //! モードレスダイアログの表示 /*! @param hInstance [in] アプリケーションインスタンスのハンドル @param hwndParent [in] オーナーウィンドウのハンドル @date 2011.04.10 nasukoji 各国語メッセージリソース対応 */ HWND CDialog::DoModeless( HINSTANCE hInstance, HWND hwndParent, int nDlgTemplete, LPARAM lParam, int nCmdShow ) { m_bInited = FALSE; m_bModal = FALSE; m_hInstance = hInstance; /* アプリケーションインスタンスのハンドル */ m_hwndParent = hwndParent; /* オーナーウィンドウのハンドル */ m_lParam = lParam; m_hLangRsrcInstance = CSelectLang::getLangRsrcInstance(); // メッセージリソースDLLのインスタンスハンドル m_hWnd = ::CreateDialogParam( m_hLangRsrcInstance, MAKEINTRESOURCE( nDlgTemplete ), m_hwndParent, MyDialogProc, (LPARAM)this ); if( NULL != m_hWnd ){ ::ShowWindow( m_hWnd, nCmdShow ); } return m_hWnd; } HWND CDialog::DoModeless( HINSTANCE hInstance, HWND hwndParent, LPCDLGTEMPLATE lpTemplate, LPARAM lParam, int nCmdShow ) { m_bInited = FALSE; m_bModal = FALSE; m_hInstance = hInstance; /* アプリケーションインスタンスのハンドル */ m_hwndParent = hwndParent; /* オーナーウィンドウのハンドル */ m_lParam = lParam; m_hWnd = ::CreateDialogIndirectParam( m_hInstance, lpTemplate, m_hwndParent, MyDialogProc, (LPARAM)this ); if( NULL != m_hWnd ){ ::ShowWindow( m_hWnd, nCmdShow ); } return m_hWnd; } void CDialog::CloseDialog( INT_PTR nModalRetVal ) { if( NULL != m_hWnd ){ if( m_bModal ){ ::EndDialog( m_hWnd, nModalRetVal ); }else{ ::DestroyWindow( m_hWnd ); } m_hWnd = NULL; } return; } BOOL CDialog::OnInitDialog( HWND hwndDlg, WPARAM wParam, LPARAM lParam ) { m_hWnd = hwndDlg; // Modified by KEITA for WIN64 2003.9.6 ::SetWindowLongPtr( m_hWnd, DWLP_USER, lParam ); /* ダイアログデータの設定 */ SetData(); SetDialogPosSize(); m_bInited = TRUE; return TRUE; } void CDialog::SetDialogPosSize() { #if 0 /* ダイアログのサイズ、位置の再現 */ if( -1 != m_xPos && -1 != m_yPos ){ ::SetWindowPos( m_hWnd, NULL, m_xPos, m_yPos, 0, 0, SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER ); DEBUG_TRACE( _T("CDialog::OnInitDialog() m_xPos=%d m_yPos=%d\n"), m_xPos, m_yPos ); } if( -1 != m_nWidth && -1 != m_nHeight ){ ::SetWindowPos( m_hWnd, NULL, 0, 0, m_nWidth, m_nHeight, SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER ); } #endif if( -1 != m_xPos && -1 != m_yPos ){ /* ウィンドウ位置・サイズを再現 */ // 2014.11.28 フォント変更対応 if( m_nWidth == -1 && m_nHeight == -1 ){ RECT rc; ::GetWindowRect( m_hWnd, &rc ); m_nWidth = rc.right - rc.left; m_nHeight = rc.bottom - rc.top; } if( !(::GetWindowLongPtr( m_hWnd, GWL_STYLE ) & WS_CHILD) ){ // 2006.06.09 ryoji // モニタのワーク領域よりも左右上下に1ドット小さい領域内に全体が収まるように位置調整する // // note: ダイアログをワーク領域境界にぴったり合わせようとすると、 // 強制的に親の中央に移動させられてしまうときがある // (マルチモニタ環境で親が非プライマリモニタにある場合だけ?) // 状況に合わせて処理を変えるのは厄介なので、一律、1ドットの空きを入れる RECT rc; RECT rcWork; rc.left = m_xPos; rc.top = m_yPos; rc.right = m_xPos + m_nWidth; rc.bottom = m_yPos + m_nHeight; GetMonitorWorkRect(&rc, &rcWork); rcWork.top += 1; rcWork.bottom -= 1; rcWork.left += 1; rcWork.right -= 1; if( rc.bottom > rcWork.bottom ){ rc.top -= (rc.bottom - rcWork.bottom); rc.bottom = rcWork.bottom; } if( rc.right > rcWork.right ){ rc.left -= (rc.right - rcWork.right); rc.right = rcWork.right; } if( rc.top < rcWork.top ){ rc.bottom += (rcWork.top - rc.top); rc.top = rcWork.top; } if( rc.left < rcWork.left ){ rc.right += (rcWork.left - rc.left); rc.left = rcWork.left; } m_xPos = rc.left; m_yPos = rc.top; m_nWidth = rc.right - rc.left; m_nHeight = rc.bottom - rc.top; } WINDOWPLACEMENT cWindowPlacement; cWindowPlacement.length = sizeof( cWindowPlacement ); cWindowPlacement.showCmd = m_nShowCmd; // 最大化・最小化 cWindowPlacement.rcNormalPosition.left = m_xPos; cWindowPlacement.rcNormalPosition.top = m_yPos; cWindowPlacement.rcNormalPosition.right = m_nWidth + m_xPos; cWindowPlacement.rcNormalPosition.bottom = m_nHeight + m_yPos; ::SetWindowPlacement( m_hWnd, &cWindowPlacement ); } } BOOL CDialog::OnDestroy( void ) { /* ウィンドウ位置・サイズを記憶 */ WINDOWPLACEMENT cWindowPlacement; cWindowPlacement.length = sizeof( cWindowPlacement ); if (::GetWindowPlacement( m_hWnd, &cWindowPlacement )){ m_nShowCmd = cWindowPlacement.showCmd; // 最大化・最小化 m_xPos = cWindowPlacement.rcNormalPosition.left; m_yPos = cWindowPlacement.rcNormalPosition.top; m_nWidth = cWindowPlacement.rcNormalPosition.right - cWindowPlacement.rcNormalPosition.left; m_nHeight = cWindowPlacement.rcNormalPosition.bottom - cWindowPlacement.rcNormalPosition.top; } if( !m_bSizable ){ m_nWidth = -1; m_nHeight = -1; } /* 破棄 */ if( NULL != m_hwndSizeBox ){ ::DestroyWindow( m_hwndSizeBox ); m_hwndSizeBox = NULL; } m_hWnd = NULL; return TRUE; } BOOL CDialog::OnBnClicked( int wID ) { switch( wID ){ case IDCANCEL: // Fall through. case IDOK: CloseDialog( wID ); return TRUE; } return FALSE; } BOOL CDialog::OnSize() { return CDialog::OnSize( 0, 0 ); } BOOL CDialog::OnSize( WPARAM wParam, LPARAM lParam ) { RECT rc; ::GetWindowRect( m_hWnd, &rc ); /* ダイアログのサイズの記憶 */ m_xPos = rc.left; m_yPos = rc.top; m_nWidth = rc.right - rc.left; m_nHeight = rc.bottom - rc.top; /* サイズボックスの移動 */ if( NULL != m_hwndSizeBox ){ ::GetClientRect( m_hWnd, &rc ); // ::SetWindowPos( m_hwndSizeBox, NULL, // Sept. 17, 2000 JEPRO_16thdot アイコンの16dot目が表示されるように次行を変更する必要ある? // Jan. 12, 2001 JEPRO (directed by stonee) 15を16に変更するとアウトライン解析のダイアログの右下にある // グリップサイズに`遊び'ができてしまい(移動する!)、ダイアログを大きくできないという障害が発生するので // 変更しないことにした(要するに原作版に戻しただけ) // rc.right - rc.left - 15, rc.bottom - rc.top - 15, // 13, 13, // SWP_NOOWNERZORDER | SWP_NOZORDER // ); // Jan. 12, 2001 Stonee (suggested by genta) // "13"という固定値ではなくシステムから取得したスクロールバーサイズを使うように修正 ::SetWindowPos( m_hwndSizeBox, NULL, rc.right - rc.left - GetSystemMetrics(SM_CXVSCROLL), //<-- stonee rc.bottom - rc.top - GetSystemMetrics(SM_CYHSCROLL), //<-- stonee GetSystemMetrics(SM_CXVSCROLL), //<-- stonee GetSystemMetrics(SM_CYHSCROLL), //<-- stonee SWP_NOOWNERZORDER | SWP_NOZORDER ); // SizeBox問題テスト if( wParam == SIZE_MAXIMIZED ){ ::ShowWindow( m_hwndSizeBox, SW_HIDE ); }else{ ::ShowWindow( m_hwndSizeBox, SW_SHOW ); } ::InvalidateRect( m_hwndSizeBox, NULL, TRUE ); } return FALSE; } BOOL CDialog::OnMove( WPARAM wParam, LPARAM lParam ) { /* ダイアログの位置の記憶 */ if( !m_bInited ){ return TRUE; } RECT rc; ::GetWindowRect( m_hWnd, &rc ); /* ダイアログのサイズの記憶 */ m_xPos = rc.left; m_yPos = rc.top; m_nWidth = rc.right - rc.left; m_nHeight = rc.bottom - rc.top; DEBUG_TRACE( _T("CDialog::OnMove() m_xPos=%d m_yPos=%d\n"), m_xPos, m_yPos ); return TRUE; } void CDialog::CreateSizeBox( void ) { /* サイズボックス */ m_hwndSizeBox = ::CreateWindowEx( WS_EX_CONTROLPARENT, /* no extended styles */ _T("SCROLLBAR"), /* scroll bar control class */ NULL, /* text for window title bar */ WS_VISIBLE | WS_CHILD | SBS_SIZEBOX | SBS_SIZEGRIP, /* scroll bar styles */ 0, /* horizontal position */ 0, /* vertical position */ 0, /* width of the scroll bar */ 0, /* default height */ m_hWnd/*hdlg*/, /* handle of main window */ (HMENU) NULL, /* no menu for a scroll bar */ CSelectLang::getLangRsrcInstance(), /* instance owning this window */ (LPVOID) NULL /* pointer not needed */ ); ::ShowWindow( m_hwndSizeBox, SW_SHOW ); } /* ダイアログのメッセージ処理 */ INT_PTR CDialog::DispatchEvent( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { // DEBUG_TRACE( _T("CDialog::DispatchEvent() uMsg == %xh\n"), uMsg ); switch( uMsg ){ case WM_INITDIALOG: return OnInitDialog( hwndDlg, wParam, lParam ); case WM_DESTROY: return OnDestroy(); case WM_COMMAND: return OnCommand( wParam, lParam ); case WM_NOTIFY: return OnNotify( wParam, lParam ); case WM_SIZE: m_hWnd = hwndDlg; return OnSize( wParam, lParam ); case WM_MOVE: m_hWnd = hwndDlg; return OnMove( wParam, lParam ); case WM_DRAWITEM: return OnDrawItem( wParam, lParam ); case WM_TIMER: return OnTimer( wParam ); case WM_KEYDOWN: return OnKeyDown( wParam, lParam ); case WM_KILLFOCUS: return OnKillFocus( wParam, lParam ); case WM_ACTIVATE: return OnActivate( wParam, lParam ); //@@@ 2003.04.08 MIK case WM_VKEYTOITEM: return OnVKeyToItem( wParam, lParam ); case WM_CHARTOITEM: return OnCharToItem( wParam, lParam ); case WM_HELP: return OnPopupHelp( wParam, lParam ); //@@@ 2002.01.18 add case WM_CONTEXTMENU:return OnContextMenu( wParam, lParam ); //@@@ 2002.01.18 add } return FALSE; } BOOL CDialog::OnCommand( WPARAM wParam, LPARAM lParam ) { WORD wNotifyCode; WORD wID; HWND hwndCtl; wNotifyCode = HIWORD(wParam); /* 通知コード */ wID = LOWORD(wParam); /* 項目ID、 コントロールID、 またはアクセラレータID */ hwndCtl = (HWND) lParam; /* コントロールのハンドル */ TCHAR szClass[32]; // IDOK と IDCANCEL はボタンからでなくても同じ扱い // MSDN [Windows Management] "Dialog Box Programming Considerations" if( wID == IDOK || wID == IDCANCEL ){ return OnBnClicked( wID ); } // 通知元がコントロールだった場合の処理 if( hwndCtl ){ ::GetClassName(hwndCtl, szClass, _countof(szClass)); if( ::lstrcmpi(szClass, _T("Button")) == 0 ){ switch( wNotifyCode ){ /* ボタン/チェックボックスがクリックされた */ case BN_CLICKED: return OnBnClicked( wID ); } }else if( ::lstrcmpi(szClass, _T("Static")) == 0 ){ switch( wNotifyCode ){ case STN_CLICKED: return OnStnClicked( wID ); } }else if( ::lstrcmpi(szClass, _T("Edit")) == 0 ){ switch( wNotifyCode ){ case EN_CHANGE: return OnEnChange( hwndCtl, wID ); case EN_KILLFOCUS: return OnEnKillFocus( hwndCtl, wID ); } }else if( ::lstrcmpi(szClass, _T("ListBox")) == 0 ){ switch( wNotifyCode ){ case LBN_SELCHANGE: return OnLbnSelChange( hwndCtl, wID ); case LBN_DBLCLK: return OnLbnDblclk( wID ); } }else if( ::lstrcmpi(szClass, _T("ComboBox")) == 0 ){ switch( wNotifyCode ){ /* コンボボックス用メッセージ */ case CBN_SELCHANGE: return OnCbnSelChange( hwndCtl, wID ); // @@2005.03.31 MIK タグジャンプDialogで使うので追加 case CBN_EDITCHANGE: return OnCbnEditChange( hwndCtl, wID ); case CBN_DROPDOWN: return OnCbnDropDown( hwndCtl, wID ); // case CBN_CLOSEUP: return OnCbnCloseUp( hwndCtl, wID ); case CBN_SELENDOK: return OnCbnSelEndOk( hwndCtl, wID ); } } } return FALSE; } //@@@ 2002.01.18 add start BOOL CDialog::OnPopupHelp( WPARAM wPara, LPARAM lParam ) { HELPINFO *p = (HELPINFO *)lParam; MyWinHelp( (HWND)p->hItemHandle, HELP_WM_HELP, (ULONG_PTR)GetHelpIdTable() ); // 2006.10.10 ryoji MyWinHelpに変更に変更 return TRUE; } BOOL CDialog::OnContextMenu( WPARAM wPara, LPARAM lParam ) { MyWinHelp( m_hWnd, HELP_CONTEXTMENU, (ULONG_PTR)GetHelpIdTable() ); // 2006.10.10 ryoji MyWinHelpに変更に変更 return TRUE; } const DWORD p_helpids[] = { 0, 0 }; LPVOID CDialog::GetHelpIdTable(void) { return (LPVOID)p_helpids; } //@@@ 2002.01.18 add end BOOL CDialog::OnCbnSelEndOk( HWND hwndCtl, int wID ) { //コンボボックスのリストを表示したまま文字列を編集し、Enterキーを //押すと文字列が消える現象の対策。 //Enterキーを押してこの関数に入ったら、リストを非表示にしてしまう。 //リストを非表示にすると前方一致する文字列を選んでしまうので、 //事前に文字列を退避し、リスト非表示後に復元する。 int nLength; LPTSTR sBuf; //文字列を退避 nLength = ::GetWindowTextLength( hwndCtl ); sBuf = new TCHAR[nLength + 1]; ::GetWindowText( hwndCtl, sBuf, nLength+1 ); sBuf[nLength] = _T('\0'); //リストを非表示にする Combo_ShowDropdown( hwndCtl, FALSE ); //文字列を復元・全選択 ::SetWindowText( hwndCtl, sBuf ); Combo_SetEditSel( hwndCtl, 0, -1 ); delete[] sBuf; return TRUE; } BOOL CDialog::OnCbnDropDown( HWND hwndCtl, int wID ) { return OnCbnDropDown( hwndCtl, false ); } /** コンボボックスのドロップダウン時処理 コンボボックスがドロップダウンされる時に ドロップダウンリストの幅をアイテム文字列の最大表示幅に合わせる @param hwndCtl [in] コンボボックスのウィンドウハンドル @param wID [in] コンボボックスのID @author ryoji @date 2009.03.29 新規作成 */ BOOL CDialog::OnCbnDropDown( HWND hwndCtl, bool scrollBar ) { HDC hDC; HFONT hFont; LONG nWidth; RECT rc; SIZE sizeText; int nTextLen; int iItem; int nItem; const int nMargin = 8; int nScrollWidth = scrollBar ? ::GetSystemMetrics( SM_CXVSCROLL ) + 2 : 2; hDC = ::GetDC( hwndCtl ); if( NULL == hDC ) return FALSE; hFont = (HFONT)::SendMessageAny( hwndCtl, WM_GETFONT, 0, (LPARAM)NULL ); hFont = (HFONT)::SelectObject( hDC, hFont ); nItem = Combo_GetCount( hwndCtl ); ::GetWindowRect( hwndCtl, &rc ); nWidth = rc.right - rc.left - nMargin + nScrollWidth; for( iItem = 0; iItem < nItem; iItem++ ){ nTextLen = Combo_GetLBTextLen( hwndCtl, iItem ); if( 0 < nTextLen ) { TCHAR* pszText = new TCHAR[nTextLen + 1]; Combo_GetLBText( hwndCtl, iItem, pszText ); if( ::GetTextExtentPoint32( hDC, pszText, nTextLen, &sizeText ) ){ if ( nWidth < sizeText.cx + nScrollWidth ) nWidth = sizeText.cx + nScrollWidth; } delete []pszText; } } Combo_SetDroppedWidth( hwndCtl, nWidth + nMargin ); ::SelectObject( hDC, hFont ); ::ReleaseDC( hwndCtl, hDC ); return TRUE; } // static bool CDialog::DirectoryUp( TCHAR* szDir ) { size_t nLen = auto_strlen( szDir ); if( 3 < nLen ){ // X:\ や\\. より長い CutLastYenFromDirectoryPath( szDir ); const TCHAR *p = GetFileTitlePointer(szDir); if( 0 < p - szDir){ if( 3 < p - szDir ){ szDir[p - szDir - 1] = '\0'; // \を削るので-1 }else{ // 「C:\」の\を残す szDir[p - szDir] = '\0'; } } return true; } return false; } // コントロールに画面のフォントを設定 2012/11/27 Uchi HFONT CDialog::SetMainFont( HWND hTarget ) { if (hTarget == NULL) return NULL; HFONT hFont; LOGFONT lf; // 設定するフォントの高さを取得 hFont = (HFONT)::SendMessage(hTarget, WM_GETFONT, 0, 0); GetObject(hFont, sizeof(lf), &lf); LONG nfHeight = lf.lfHeight; // LOGFONTの作成 lf = m_pShareData->m_Common.m_sView.m_lf; lf.lfHeight = nfHeight; lf.lfWidth = 0; lf.lfEscapement = 0; lf.lfOrientation = 0; lf.lfWeight = FW_NORMAL; lf.lfItalic = FALSE; lf.lfUnderline = FALSE; lf.lfStrikeOut = FALSE; //lf.lfCharSet = lf.lfCharSet; lf.lfOutPrecision = OUT_TT_ONLY_PRECIS; // Raster Font を使わないように //lf.lfClipPrecision = lf.lfClipPrecision; //lf.lfQuality = lf.lfQuality; //lf.lfPitchAndFamily = lf.lfPitchAndFamily; //_tcsncpy( lf.lfFaceName, lf.lfFaceName, _countof(lf.lfFaceName)); // 画面のフォントに設定 2012/11/27 Uchi // フォントを作成 hFont = ::CreateFontIndirect(&lf); if (hFont) { // フォントの設定 ::SendMessage(hTarget, WM_SETFONT, (WPARAM)hFont, MAKELPARAM(FALSE, 0)); } return hFont; } void CDialog::ResizeItem( HWND hTarget, const POINT& ptDlgDefault, const POINT& ptDlgNew, const RECT& rcItemDefault, EAnchorStyle anchor, bool bUpdate) { POINT pt; int height, width; pt.x = rcItemDefault.left; pt.y = rcItemDefault.top; width = rcItemDefault.right - rcItemDefault.left; height = rcItemDefault.bottom - rcItemDefault.top; if( (anchor & (ANCHOR_LEFT | ANCHOR_RIGHT)) == ANCHOR_LEFT ){ // なし } else if( (anchor & (ANCHOR_LEFT | ANCHOR_RIGHT)) == ANCHOR_RIGHT ){ /* [<- rcItemDefault.left ->[ ] ] [<- rcItemDefault.right [ ->] ] [<- ptDlgDefault.x ->] [<- ptDlgNew.x [ ] ->] [<- pt.x ->[ ] ] */ pt.x = rcItemDefault.left + (ptDlgNew.x - ptDlgDefault.x); } else if( (anchor & (ANCHOR_LEFT | ANCHOR_RIGHT)) == (ANCHOR_LEFT | ANCHOR_RIGHT) ){ /* [<- ptDlgNew.x [ ] ->] [ [<-width->] ] */ width = ptDlgNew.x - rcItemDefault.left - (ptDlgDefault.x - rcItemDefault.right); } if( (anchor & (ANCHOR_TOP | ANCHOR_BOTTOM) ) == ANCHOR_TOP ){ // なし } else if( (anchor & (ANCHOR_TOP | ANCHOR_BOTTOM) ) == ANCHOR_BOTTOM ){ pt.y = rcItemDefault.top + (ptDlgNew.y - ptDlgDefault.y); } else if( (anchor & (ANCHOR_TOP | ANCHOR_BOTTOM) ) == (ANCHOR_TOP | ANCHOR_BOTTOM) ){ height = ptDlgNew.y - rcItemDefault.top - (ptDlgDefault.y - rcItemDefault.bottom); } // ::MoveWindow( hTarget, pt.x, pt.y, width, height, FALSE ); ::SetWindowPos( hTarget, NULL, pt.x, pt.y, width, height, SWP_NOOWNERZORDER | SWP_NOZORDER ); if( bUpdate ){ ::InvalidateRect( hTarget, NULL, TRUE ); } } void CDialog::GetItemClientRect( int wID, RECT& rc ) { POINT po; ::GetWindowRect( GetItemHwnd(wID), &rc ); po.x = rc.left; po.y = rc.top; ::ScreenToClient( GetHwnd(), &po ); rc.left = po.x; rc.top = po.y; po.x = rc.right; po.y = rc.bottom; ::ScreenToClient( GetHwnd(), &po ); rc.right = po.x; rc.bottom = po.y; } static const TCHAR* TSTR_SUBCOMBOBOXDATA = _T("SubComboBoxData"); static void DeleteItem(HWND hwnd, CRecent* pRecent) { int nIndex = Combo_GetCurSel(hwnd); if( 0 <= nIndex ){ std::vector<TCHAR> szText; szText.resize(Combo_GetLBTextLen(hwnd, nIndex) + 1); Combo_GetLBText(hwnd, nIndex, &szText[0]); Combo_DeleteString(hwnd, nIndex); int nRecentIndex = pRecent->FindItemByText(&szText[0]); if( 0 <= nRecentIndex ){ pRecent->DeleteItem(nRecentIndex); } } } LRESULT CALLBACK SubEditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { SComboBoxItemDeleter* data = (SComboBoxItemDeleter*)::GetProp( hwnd, TSTR_SUBCOMBOBOXDATA ); switch( uMsg ){ case WM_KEYDOWN: { if( wParam == VK_DELETE ){ HWND hwndCombo = data->hwndCombo; BOOL bShow = Combo_GetDroppedState(hwndCombo); if( bShow ){ DeleteItem(hwndCombo, data->pRecent); return 0; } } break; } case WM_DESTROY: { ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)data->pEditWndProc); ::RemoveProp(hwnd, TSTR_SUBCOMBOBOXDATA); data->pEditWndProc = NULL; break; } default: break; } return CallWindowProc(data->pEditWndProc, hwnd, uMsg, wParam, lParam); } LRESULT CALLBACK SubListBoxProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { SComboBoxItemDeleter* data = (SComboBoxItemDeleter*)::GetProp( hwnd, TSTR_SUBCOMBOBOXDATA ); switch( uMsg ){ case WM_KEYDOWN: { if( wParam == VK_DELETE ){ HWND hwndCombo = data->hwndCombo; BOOL bShow = Combo_GetDroppedState(hwndCombo); if( bShow ){ DeleteItem(hwndCombo, data->pRecent); return 0; } } break; } case WM_DESTROY: { ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)data->pListBoxWndProc); ::RemoveProp(hwnd, TSTR_SUBCOMBOBOXDATA); data->pListBoxWndProc = NULL; break; } default: break; } return CallWindowProc(data->pListBoxWndProc, hwnd, uMsg, wParam, lParam); } LRESULT CALLBACK SubComboBoxProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { SComboBoxItemDeleter* data = (SComboBoxItemDeleter*)::GetProp( hwnd, TSTR_SUBCOMBOBOXDATA ); switch( uMsg ){ case WM_CTLCOLOREDIT: { if( NULL == data->pEditWndProc ){ HWND hwndCtl = (HWND)lParam; data->pEditWndProc = (WNDPROC)::GetWindowLongPtr(hwndCtl, GWLP_WNDPROC); ::SetProp(hwndCtl, TSTR_SUBCOMBOBOXDATA, data); ::SetWindowLongPtr(hwndCtl, GWLP_WNDPROC, (LONG_PTR)SubEditProc); } break; } case WM_CTLCOLORLISTBOX: { if( NULL == data->pListBoxWndProc ){ HWND hwndCtl = (HWND)lParam; data->pListBoxWndProc = (WNDPROC)::GetWindowLongPtr(hwndCtl, GWLP_WNDPROC); ::SetProp(hwndCtl, TSTR_SUBCOMBOBOXDATA, data); ::SetWindowLongPtr(hwndCtl, GWLP_WNDPROC, (LONG_PTR)SubListBoxProc); } break; } case WM_DESTROY: { ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)data->pComboBoxWndProc); ::RemoveProp(hwnd, TSTR_SUBCOMBOBOXDATA); data->pComboBoxWndProc = NULL; break; } default: break; } return CallWindowProc(data->pComboBoxWndProc, hwnd, uMsg, wParam, lParam); } void CDialog::SetComboBoxDeleter( HWND hwndCtl, SComboBoxItemDeleter* data ) { if( NULL == data->pRecent ){ return; } data->hwndCombo = hwndCtl; data->pComboBoxWndProc = (WNDPROC)::GetWindowLongPtr(hwndCtl, GWLP_WNDPROC); ::SetProp(hwndCtl, TSTR_SUBCOMBOBOXDATA, data); ::SetWindowLongPtr(hwndCtl, GWLP_WNDPROC, (LONG_PTR)SubComboBoxProc); }
26.958738
151
0.681777
[ "vector" ]
b4531292dabe3ff12cf08a40c8fdb8fdda6f06b3
18,587
cpp
C++
Library/Ogre/OgreMain/src/OgreRenderTarget.cpp
Joda89/xsilium-engine
3ffb8adb4537386735b6a3023823173515aff965
[ "MIT" ]
241
2015-01-04T00:36:58.000Z
2022-01-06T19:19:23.000Z
Library/Ogre/OgreMain/src/OgreRenderTarget.cpp
Joda89/xsilium-engine
3ffb8adb4537386735b6a3023823173515aff965
[ "MIT" ]
10
2015-07-10T18:27:17.000Z
2019-06-26T20:59:59.000Z
Library/Ogre/OgreMain/src/OgreRenderTarget.cpp
Joda89/xsilium-engine
3ffb8adb4537386735b6a3023823173515aff965
[ "MIT" ]
82
2015-01-25T18:02:35.000Z
2022-03-05T12:28:17.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgreRenderTarget.h" #include "OgreStringConverter.h" #include "OgreViewport.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreRenderTargetListener.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreDepthBuffer.h" #include "OgreProfiler.h" namespace Ogre { RenderTarget::RenderTarget() : mPriority(OGRE_DEFAULT_RT_GROUP) , mDepthBufferPoolId(DepthBuffer::POOL_DEFAULT) , mDepthBuffer(0) , mActive(true) , mAutoUpdate(true) , mHwGamma(false) , mFSAA(0) { mTimer = Root::getSingleton().getTimer(); resetStatistics(); } RenderTarget::~RenderTarget() { // Delete viewports for (ViewportList::iterator i = mViewportList.begin(); i != mViewportList.end(); ++i) { fireViewportRemoved(i->second); OGRE_DELETE (*i).second; } //DepthBuffer keeps track of us, avoid a dangling pointer detachDepthBuffer(); // Write closing message LogManager::getSingleton().stream(LML_TRIVIAL) << "Render Target '" << mName << "' " << "Average FPS: " << mStats.avgFPS << " " << "Best FPS: " << mStats.bestFPS << " " << "Worst FPS: " << mStats.worstFPS; } const String& RenderTarget::getName(void) const { return mName; } void RenderTarget::getMetrics(unsigned int& width, unsigned int& height, unsigned int& colourDepth) { width = mWidth; height = mHeight; colourDepth = mColourDepth; } unsigned int RenderTarget::getWidth(void) const { return mWidth; } unsigned int RenderTarget::getHeight(void) const { return mHeight; } unsigned int RenderTarget::getColourDepth(void) const { return mColourDepth; } //----------------------------------------------------------------------- void RenderTarget::setDepthBufferPool( uint16 poolId ) { if( mDepthBufferPoolId != poolId ) { mDepthBufferPoolId = poolId; detachDepthBuffer(); } } //----------------------------------------------------------------------- uint16 RenderTarget::getDepthBufferPool() const { return mDepthBufferPoolId; } //----------------------------------------------------------------------- DepthBuffer* RenderTarget::getDepthBuffer() const { return mDepthBuffer; } //----------------------------------------------------------------------- bool RenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) { bool retVal = false; if( (retVal = depthBuffer->isCompatible( this )) ) { detachDepthBuffer(); mDepthBuffer = depthBuffer; mDepthBuffer->_notifyRenderTargetAttached( this ); } return retVal; } //----------------------------------------------------------------------- void RenderTarget::detachDepthBuffer() { if( mDepthBuffer ) { mDepthBuffer->_notifyRenderTargetDetached( this ); mDepthBuffer = 0; } } //----------------------------------------------------------------------- void RenderTarget::_detachDepthBuffer() { mDepthBuffer = 0; } void RenderTarget::updateImpl(void) { _beginUpdate(); _updateAutoUpdatedViewports(true); _endUpdate(); } void RenderTarget::_beginUpdate() { // notify listeners (pre) firePreUpdate(); mStats.triangleCount = 0; mStats.batchCount = 0; } void RenderTarget::_updateAutoUpdatedViewports(bool updateStatistics) { // Go through viewports in Z-order // Tell each to refresh ViewportList::iterator it = mViewportList.begin(); while (it != mViewportList.end()) { Viewport* viewport = (*it).second; if(viewport->isAutoUpdated()) { _updateViewport(viewport,updateStatistics); } ++it; } } void RenderTarget::_endUpdate() { // notify listeners (post) firePostUpdate(); // Update statistics (always on top) updateStats(); } void RenderTarget::_updateViewport(Viewport* viewport, bool updateStatistics) { assert(viewport->getTarget() == this && "RenderTarget::_updateViewport the requested viewport is " "not bound to the rendertarget!"); fireViewportPreUpdate(viewport); viewport->update(); if(updateStatistics) { mStats.triangleCount += viewport->_getNumRenderedFaces(); mStats.batchCount += viewport->_getNumRenderedBatches(); } fireViewportPostUpdate(viewport); } void RenderTarget::_updateViewport(int zorder, bool updateStatistics) { ViewportList::iterator it = mViewportList.find(zorder); if (it != mViewportList.end()) { _updateViewport((*it).second,updateStatistics); } else { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,"No viewport with given zorder : " + StringConverter::toString(zorder), "RenderTarget::_updateViewport"); } } Viewport* RenderTarget::addViewport(Camera* cam, int ZOrder, float left, float top , float width , float height) { // Check no existing viewport with this Z-order ViewportList::iterator it = mViewportList.find(ZOrder); if (it != mViewportList.end()) { StringUtil::StrStreamType str; str << "Can't create another viewport for " << mName << " with Z-order " << ZOrder << " because a viewport exists with this Z-order already."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, str.str(), "RenderTarget::addViewport"); } // Add viewport to list // Order based on Z-order Viewport* vp = OGRE_NEW Viewport(cam, this, left, top, width, height, ZOrder); mViewportList.insert(ViewportList::value_type(ZOrder, vp)); fireViewportAdded(vp); return vp; } //----------------------------------------------------------------------- void RenderTarget::removeViewport(int ZOrder) { ViewportList::iterator it = mViewportList.find(ZOrder); if (it != mViewportList.end()) { fireViewportRemoved((*it).second); OGRE_DELETE (*it).second; mViewportList.erase(ZOrder); } } void RenderTarget::removeAllViewports(void) { for (ViewportList::iterator it = mViewportList.begin(); it != mViewportList.end(); ++it) { fireViewportRemoved(it->second); OGRE_DELETE (*it).second; } mViewportList.clear(); } void RenderTarget::getStatistics(float& lastFPS, float& avgFPS, float& bestFPS, float& worstFPS) const { // Note - the will have been updated by the last render lastFPS = mStats.lastFPS; avgFPS = mStats.avgFPS; bestFPS = mStats.bestFPS; worstFPS = mStats.worstFPS; } const RenderTarget::FrameStats& RenderTarget::getStatistics(void) const { return mStats; } float RenderTarget::getLastFPS() const { return mStats.lastFPS; } float RenderTarget::getAverageFPS() const { return mStats.avgFPS; } float RenderTarget::getBestFPS() const { return mStats.bestFPS; } float RenderTarget::getWorstFPS() const { return mStats.worstFPS; } size_t RenderTarget::getTriangleCount(void) const { return mStats.triangleCount; } size_t RenderTarget::getBatchCount(void) const { return mStats.batchCount; } float RenderTarget::getBestFrameTime() const { return (float)mStats.bestFrameTime; } float RenderTarget::getWorstFrameTime() const { return (float)mStats.worstFrameTime; } void RenderTarget::resetStatistics(void) { mStats.avgFPS = 0.0; mStats.bestFPS = 0.0; mStats.lastFPS = 0.0; mStats.worstFPS = 999.0; mStats.triangleCount = 0; mStats.batchCount = 0; mStats.bestFrameTime = 999999; mStats.worstFrameTime = 0; mLastTime = mTimer->getMilliseconds(); mLastSecond = mLastTime; mFrameCount = 0; } void RenderTarget::updateStats(void) { ++mFrameCount; unsigned long thisTime = mTimer->getMilliseconds(); // check frame time unsigned long frameTime = thisTime - mLastTime ; mLastTime = thisTime ; mStats.bestFrameTime = std::min(mStats.bestFrameTime, frameTime); mStats.worstFrameTime = std::max(mStats.worstFrameTime, frameTime); // check if new second (update only once per second) if (thisTime - mLastSecond > 1000) { // new second - not 100% precise mStats.lastFPS = (float)mFrameCount / (float)(thisTime - mLastSecond) * 1000.0f; if (mStats.avgFPS == 0) mStats.avgFPS = mStats.lastFPS; else mStats.avgFPS = (mStats.avgFPS + mStats.lastFPS) / 2; // not strictly correct, but good enough mStats.bestFPS = std::max(mStats.bestFPS, mStats.lastFPS); mStats.worstFPS = std::min(mStats.worstFPS, mStats.lastFPS); mLastSecond = thisTime ; mFrameCount = 0; } } void RenderTarget::getCustomAttribute(const String& name, void* pData) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attribute not found. " + name, " RenderTarget::getCustomAttribute"); } //----------------------------------------------------------------------- void RenderTarget::addListener(RenderTargetListener* listener) { mListeners.push_back(listener); } //----------------------------------------------------------------------- void RenderTarget::removeListener(RenderTargetListener* listener) { RenderTargetListenerList::iterator i; for (i = mListeners.begin(); i != mListeners.end(); ++i) { if (*i == listener) { mListeners.erase(i); break; } } } //----------------------------------------------------------------------- void RenderTarget::removeAllListeners(void) { mListeners.clear(); } //----------------------------------------------------------------------- void RenderTarget::firePreUpdate(void) { RenderTargetEvent evt; evt.source = this; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->preRenderTargetUpdate(evt); } } //----------------------------------------------------------------------- void RenderTarget::firePostUpdate(void) { RenderTargetEvent evt; evt.source = this; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->postRenderTargetUpdate(evt); } } //----------------------------------------------------------------------- unsigned short RenderTarget::getNumViewports(void) const { return (unsigned short)mViewportList.size(); } //----------------------------------------------------------------------- Viewport* RenderTarget::getViewport(unsigned short index) { assert (index < mViewportList.size() && "Index out of bounds"); ViewportList::iterator i = mViewportList.begin(); while (index--) ++i; return i->second; } //----------------------------------------------------------------------- Viewport* RenderTarget::getViewportByZOrder(int ZOrder) { ViewportList::iterator i = mViewportList.find(ZOrder); if(i == mViewportList.end()) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,"No viewport with given Z-order: " + StringConverter::toString(ZOrder), "RenderTarget::getViewportByZOrder"); } return i->second; } //----------------------------------------------------------------------- bool RenderTarget::hasViewportWithZOrder(int ZOrder) { ViewportList::iterator i = mViewportList.find(ZOrder); return i != mViewportList.end(); } //----------------------------------------------------------------------- bool RenderTarget::isActive() const { return mActive; } //----------------------------------------------------------------------- void RenderTarget::setActive( bool state ) { mActive = state; } //----------------------------------------------------------------------- void RenderTarget::fireViewportPreUpdate(Viewport* vp) { RenderTargetViewportEvent evt; evt.source = vp; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->preViewportUpdate(evt); } } //----------------------------------------------------------------------- void RenderTarget::fireViewportPostUpdate(Viewport* vp) { RenderTargetViewportEvent evt; evt.source = vp; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->postViewportUpdate(evt); } } //----------------------------------------------------------------------- void RenderTarget::fireViewportAdded(Viewport* vp) { RenderTargetViewportEvent evt; evt.source = vp; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->viewportAdded(evt); } } //----------------------------------------------------------------------- void RenderTarget::fireViewportRemoved(Viewport* vp) { RenderTargetViewportEvent evt; evt.source = vp; // Make a temp copy of the listeners // some will want to remove themselves as listeners when they get this RenderTargetListenerList tempList = mListeners; RenderTargetListenerList::iterator i, iend; i = tempList.begin(); iend = tempList.end(); for(; i != iend; ++i) { (*i)->viewportRemoved(evt); } } //----------------------------------------------------------------------- String RenderTarget::writeContentsToTimestampedFile(const String& filenamePrefix, const String& filenameSuffix) { struct tm *pTime; time_t ctTime; time(&ctTime); pTime = localtime( &ctTime ); Ogre::StringStream oss; oss << std::setw(2) << std::setfill('0') << (pTime->tm_mon + 1) << std::setw(2) << std::setfill('0') << pTime->tm_mday << std::setw(2) << std::setfill('0') << (pTime->tm_year + 1900) << "_" << std::setw(2) << std::setfill('0') << pTime->tm_hour << std::setw(2) << std::setfill('0') << pTime->tm_min << std::setw(2) << std::setfill('0') << pTime->tm_sec << std::setw(3) << std::setfill('0') << (mTimer->getMilliseconds() % 1000); String filename = filenamePrefix + oss.str() + filenameSuffix; writeContentsToFile(filename); return filename; } //----------------------------------------------------------------------- void RenderTarget::writeContentsToFile(const String& filename) { PixelFormat pf = suggestPixelFormat(); uchar *data = OGRE_ALLOC_T(uchar, mWidth * mHeight * PixelUtil::getNumElemBytes(pf), MEMCATEGORY_RENDERSYS); PixelBox pb(mWidth, mHeight, 1, pf, data); copyContentsToMemory(pb); Image().loadDynamicImage(data, mWidth, mHeight, 1, pf, false, 1, 0).save(filename); OGRE_FREE(data, MEMCATEGORY_RENDERSYS); } //----------------------------------------------------------------------- void RenderTarget::_notifyCameraRemoved(const Camera* cam) { ViewportList::iterator i, iend; iend = mViewportList.end(); for (i = mViewportList.begin(); i != iend; ++i) { Viewport* v = i->second; if (v->getCamera() == cam) { // disable camera link v->setCamera(0); } } } //----------------------------------------------------------------------- void RenderTarget::setAutoUpdated(bool autoup) { mAutoUpdate = autoup; } //----------------------------------------------------------------------- bool RenderTarget::isAutoUpdated(void) const { return mAutoUpdate; } //----------------------------------------------------------------------- bool RenderTarget::isPrimary(void) const { // RenderWindow will override and return true for the primary window return false; } //----------------------------------------------------------------------- RenderTarget::Impl *RenderTarget::_getImpl() { return 0; } //----------------------------------------------------------------------- void RenderTarget::update(bool swap) { OgreProfileBeginGPUEvent("RenderTarget: " + getName()); // call implementation updateImpl(); if (swap) { // Swap buffers swapBuffers(); } OgreProfileEndGPUEvent("RenderTarget: " + getName()); } }
29.691693
119
0.545758
[ "render", "object" ]
b457a77d73b304a1bec166ac027fa528742fa221
10,855
cpp
C++
Source/CodeQOR/ErrorSystem/Error.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/CodeQOR/ErrorSystem/Error.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/CodeQOR/ErrorSystem/Error.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//Error.cpp: implementation of the CError class. // Copyright Querysoft Limited 2013 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "CompilerQOR.h" #include "CodeQOR/Tracing/FunctionContextBase.h" #include "CodeQOR/ErrorSystem/Error.h" #include "CodeQOR/ErrorSystem/What.h" #include "CodeQOR/ErrorSystem/Where.h" #include "CodeQOR/ErrorSystem/When.h" #include "CodeQOR/Modules/ProcessBase.h" #include "CodeQOR/Instancing/TInstancePtr.h" #include "CodeQOR/ErrorSystem/DefaultHandler.h" #include "CodeQOR/Text/Char.h" #include "CodeQOR/ErrorSystem/BaseErrorDomain.h" #include <string.h> #include <stdarg.h> #pragma TODO("All allocation and deallocation must deal with the Error heap, if there is one, through an allocator" ) //-------------------------------------------------------------------------------- namespace nsCodeQOR { //------------------------------------------------------------------------------ CError::CBaseErrorParams::CBaseErrorParams( CError::CBaseErrorParams const& cSrc ) : m_uiCode( cSrc.m_uiCode ) { CError::CBaseErrorParams& Src = const_cast< CError::CBaseErrorParams& >( cSrc ); if( &Src != this ) { unsigned int uiParam = 0; for( ;uiParam < sMaxParams; uiParam++ ) { m_pParams[ uiParam ] = Src.m_pParams[ uiParam ]; Src.m_pParams[ uiParam ] = 0; } } } //------------------------------------------------------------------------------ CError::CBaseErrorParams::CBaseErrorParams() : m_uiCode( 0 ) { for( unsigned char ucCount = 0; ucCount < sMaxParams; ucCount++ ) { m_pParams[ ucCount ] = 0; } } //------------------------------------------------------------------------------ CError::CBaseErrorParams::CBaseErrorParams( unsigned int uiCode, ... ) : m_uiCode( uiCode ) { va_list args; va_start(args, uiCode); m_uiCode = uiCode; unsigned int iParam = 0; void* pParam = 0; do { pParam = va_arg( args, void* ); if( pParam ) { m_pParams[ iParam++ ] = pParam; } }while( pParam != 0 && iParam < sMaxParams ); while( iParam < sMaxParams ) { m_pParams[ iParam++ ] = 0; } va_end(args); } //------------------------------------------------------------------------------ CError::CBaseErrorParams::~CBaseErrorParams() { } //-------------------------------------------------------------------------------- void* CError::CBaseErrorParams::operator[]( unsigned int uiIndex ) { void* pParam = 0; if( uiIndex < sMaxParams ) { pParam = m_pParams[ uiIndex ]; } return pParam; } //-------------------------------------------------------------------------------- unsigned int CError::CBaseErrorParams::Code() { return m_uiCode; } //------------------------------------------------------------------------------ CString CError::ErrorLevel[] = { _TXT("Note").str(), _TXT("Warning").str(), _TXT("Continuable Error").str(), _TXT("Serious Error").str(), _TXT("Fatal Error").str() }; //-------------------------------------------------------------------------------- void CError::Resolved( bool bResolved ) { if( bResolved ) { delete this; } else { #if __QOR_CPP_EXCEPTIONS throw( this ); #else abort(); #endif } } //------------------------------------------------------------------------------ CError::CError() { } //------------------------------------------------------------------------------ CError::CError( const CError& src ) { if( &src != this ) { *this = src; } } //------------------------------------------------------------------------------ CError& CError::operator = ( const CError& csrc ) { CError& src = const_cast< CError& >( csrc ); m_What.Configure( src.What().Clone() ); m_Where.Configure( src.Where().Clone() ); m_When.Configure( src.When().Clone() ); return *this; } //------------------------------------------------------------------------------ CError::~CError() { } //------------------------------------------------------------------------------ void CError::Raise( const char* szFile, int iLine, const char* szFunc, CObjectContextBase& ObjContext, CBaseErrorParams Params, CBaseErrorDomain* pDomain, Level eLevel ) { CError* pError = new CError; //Construct the parts of the error //When pError->m_When.Configure( new CWhen() ); //What pError->m_What.Configure( new CWhat() ); pError->What().SetParams( Params ); pError->What().SetLevel( eLevel ); pError->What().SetCode( Params.Code() ); //Where pError->m_Where.Configure( new CWhere() ); pError->Where().SetLine( static_cast< unsigned int >( iLine ) ); pError->Where().SetFunction( szFunc ); pError->Where().SetFile( szFile ); pError->Where().SetDomain( pDomain ); pError->Where().SetObjectContext( ObjContext ); //Attempt to resolve the error pError->Resolved( pError->Handle() ); } //------------------------------------------------------------------------------ void CError::Raise( unsigned int uiErrCode, CBaseErrorDomain* pDomain, CError::Level eLevel ) { if( !nsCodeQOR::CFunctionContextBase::Booted( false ) ) { return;//Don't allow errors to be raised before static initialization completes } CFunctionContextBase* pFunctionContext = CFunctionContextBase::GetCurrent(); if( pFunctionContext ) { CObjectContextBase& ObjRef( pFunctionContext->ObjectContextPointer() ? *(pFunctionContext->ObjectContextPointer()) : CObjectContextBase::NullContext() ); Raise( pFunctionContext->File(), (int)pFunctionContext->Line(), pFunctionContext->Name(), ObjRef, uiErrCode, pDomain, eLevel ); } else { Raise( "Unknown file", 0, "Unknown function", CObjectContextBase::NullContext(), uiErrCode, pDomain, eLevel ); } } //------------------------------------------------------------------------------ void CError::Raise( const char* szFile, int iLine, const char* strFunc, CObjectContextBase& ObjContext, unsigned int uiCode, CBaseErrorDomain* pDomain, CError::Level eLevel ) { CError* pError = new CError; //Construct the parts of the error //When pError->m_When.Configure( new CWhen() ); //Where pError->m_Where.Configure( new CWhere() ); pError->Where().SetLine( static_cast< unsigned int >( iLine ) ); pError->Where().SetFunction( strFunc ); pError->Where().SetFile( szFile ); pError->Where().SetDomain( pDomain ); pError->Where().SetObjectContext( ObjContext ); //What pError->m_What.Configure( new CWhat() ); pError->What().SetCode( uiCode ); pError->What().SetLevel( eLevel ); *( pError->What().Params() ) = new CBaseErrorParams(); //Attempt to resolve the error pError->Resolved( pError->Handle() ); } //------------------------------------------------------------------------------ void CError::Catch() { #if ( __QCMP_SUPPORTS( __QCMP_FEATURE_TEMPLATE_PARTIAL_SPECIALIZATION ) ) m_Where.operator()< CWhere >().SetInException( true ); #else dynamic_cast< CWhere* >( m_Where.Base() )->SetInException( true ); #endif Resolved( Handle() ); } //------------------------------------------------------------------------------ //Handle Errors by invoking the appropriate Error handler bool CError::Handle() { bool bHandled = false; #if ( __QCMP_SUPPORTS( __QCMP_FEATURE_TEMPLATE_PARTIAL_SPECIALIZATION ) ) switch ( m_What.operator()< CWhat >().GetLevel() ) #else switch ( dynamic_cast< CWhat* >( m_What.Base() )->GetLevel() ) #endif { case ERR_LVL_NOTE: { CTInstancePtr< CDefaultNoteHandler > pHandler; if( pHandler.operator->() ) { pHandler->Handle( *this ); } bHandled = true;//Notes are not allowed to escalate } break; case ERR_LVL_WARNING: { CTInstancePtr< CDefaultWarningHandler > pHandler; bHandled = pHandler.operator->() && pHandler->Handle( *this ); } break; case ERR_LVL_CONTINUE: { CTInstancePtr< CDefaultContinuableHandler > pHandler; bHandled = pHandler.operator->() && pHandler->Handle( *this ); } break; case ERR_LVL_SERIOUS: { CTInstancePtr< CDefaultSeriousHandler > pHandler; bHandled = pHandler.operator->() && pHandler->Handle( *this ); } break; case ERR_LVL_FATAL: { CTInstancePtr< CDefaultFatalHandler > pHandler; if( pHandler.operator->() ) { pHandler->Handle( *this ); } bHandled = false;//Fatal errors cannot be resolved } break; } return bHandled; } //------------------------------------------------------------------------------ CWhere& CError::Where() { #if ( __QCMP_SUPPORTS( __QCMP_FEATURE_TEMPLATE_PARTIAL_SPECIALIZATION ) ) return m_Where.operator()< CWhere >(); #else return *( dynamic_cast< CWhere* >( m_Where.Base() ) ); #endif } //------------------------------------------------------------------------------ CWhat& CError::What() { #if ( __QCMP_SUPPORTS( __QCMP_FEATURE_TEMPLATE_PARTIAL_SPECIALIZATION ) ) return m_What.operator()< CWhat >(); #else return *( dynamic_cast< CWhat* >( m_What.Base() ) ); #endif } //------------------------------------------------------------------------------ CWhen& CError::When() { #if ( __QCMP_SUPPORTS( __QCMP_FEATURE_TEMPLATE_PARTIAL_SPECIALIZATION ) ) return m_When.operator()< CWhen >(); #else return *( dynamic_cast< CWhen* >( m_When.Base() ) ); #endif } //------------------------------------------------------------------------------ CString CError::Description() { CString strDescription = _TXT("Failed to get error description").str(); Where().GetDomain()->GetDescription( strDescription, this ); return strDescription; } }//nsCodeQOR
30.069252
175
0.574482
[ "object" ]
b460f23ebcb09c3ebf9e3911fff2f51299885998
10,132
cc
C++
chromium/components/gcm_driver/crypto/encryption_header_parsers_unittest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
components/gcm_driver/crypto/encryption_header_parsers_unittest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
components/gcm_driver/crypto/encryption_header_parsers_unittest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// 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 "components/gcm_driver/crypto/encryption_header_parsers.h" #include <stddef.h> #include <stdint.h> #include <vector> #include "base/macros.h" #include "base/strings/string_number_conversions.h" #include "testing/gtest/include/gtest/gtest.h" namespace gcm { namespace { const uint64_t kDefaultRecordSize = 4096; TEST(EncryptionHeaderParsersTest, ParseValidEncryptionHeaders) { struct { const char* const header; const char* const parsed_keyid; const char* const parsed_salt; uint64_t parsed_rs; } expected_results[] = { { "keyid=foo;salt=c2l4dGVlbmNvb2xieXRlcw;rs=1024", "foo", "sixteencoolbytes", 1024 }, { "keyid=foo; salt=c2l4dGVlbmNvb2xieXRlcw; rs=1024", "foo", "sixteencoolbytes", 1024 }, { "KEYID=foo;SALT=c2l4dGVlbmNvb2xieXRlcw;RS=1024", "foo", "sixteencoolbytes", 1024 }, { " keyid = foo ; salt = c2l4dGVlbmNvb2xieXRlcw ; rs = 1024 ", "foo", "sixteencoolbytes", 1024 }, { "keyid=foo", "foo", "", kDefaultRecordSize }, { "keyid=foo;", "foo", "", kDefaultRecordSize }, { "keyid=\"foo\"", "foo", "", kDefaultRecordSize }, { "keyid='foo'", "foo", "", kDefaultRecordSize }, { "salt=c2l4dGVlbmNvb2xieXRlcw", "", "sixteencoolbytes", kDefaultRecordSize }, { "rs=2048", "", "", 2048 }, { "keyid=foo;someothervalue=1;rs=42", "foo", "", 42 }, { "keyid=foo;keyid=bar", "bar", "", kDefaultRecordSize }, }; for (size_t i = 0; i < arraysize(expected_results); i++) { SCOPED_TRACE(i); std::vector<EncryptionHeaderValues> values; ASSERT_TRUE(ParseEncryptionHeader(expected_results[i].header, &values)); ASSERT_EQ(1u, values.size()); EXPECT_EQ(expected_results[i].parsed_keyid, values[0].keyid); EXPECT_EQ(expected_results[i].parsed_salt, values[0].salt); EXPECT_EQ(expected_results[i].parsed_rs, values[0].rs); } } TEST(EncryptionHeaderParsersTest, ParseValidMultiValueEncryptionHeaders) { const size_t kNumberOfValues = 2u; struct { const char* const header; struct { const char* const keyid; const char* const salt; uint64_t rs; } parsed_values[kNumberOfValues]; } expected_results[] = { { "keyid=foo;salt=c2l4dGVlbmNvb2xieXRlcw;rs=1024,keyid=foo;salt=c2l4dGVlbm" "Nvb2xieXRlcw;rs=1024", { { "foo", "sixteencoolbytes", 1024 }, { "foo", "sixteencoolbytes", 1024 } } }, { "keyid=foo,salt=c2l4dGVlbmNvb2xieXRlcw;rs=1024", { { "foo", "", kDefaultRecordSize }, { "", "sixteencoolbytes", 1024 } } }, { "keyid=foo,keyid=bar;salt=c2l4dGVlbmNvb2xieXRlcw;rs=1024", { { "foo", "", kDefaultRecordSize }, { "bar", "sixteencoolbytes", 1024 } } }, { "keyid=\"foo,keyid=bar\",salt=c2l4dGVlbmNvb2xieXRlcw", { { "foo,keyid=bar", "", kDefaultRecordSize }, { "", "sixteencoolbytes", kDefaultRecordSize } } }, }; for (size_t i = 0; i < arraysize(expected_results); i++) { SCOPED_TRACE(i); std::vector<EncryptionHeaderValues> values; ASSERT_TRUE(ParseEncryptionHeader(expected_results[i].header, &values)); ASSERT_EQ(kNumberOfValues, values.size()); for (size_t j = 0; j < kNumberOfValues; ++j) { EXPECT_EQ(expected_results[i].parsed_values[j].keyid, values[j].keyid); EXPECT_EQ(expected_results[i].parsed_values[j].salt, values[j].salt); EXPECT_EQ(expected_results[i].parsed_values[j].rs, values[j].rs); } } } TEST(EncryptionHeaderParsersTest, ParseInvalidEncryptionHeaders) { const char* const expected_failures[] = { "keyid", "keyid=", "keyid=foo;novaluekey", "keyid=foo,keyid", "salt", "salt=", "salt=YmV/2ZXJ-sMDA", "salt=dHdlbHZlY29vbGJ5dGVz=====", "salt=123$xyz", "salt=c2l4dGVlbmNvb2xieXRlcw,salt=123$xyz", "rs", "rs=", "rs=0", "rs=0x13", "rs=1", "rs=-1", "rs=+5", "rs=99999999999999999999999999999999", "rs=2,rs=0", "rs=foobar", }; for (size_t i = 0; i < arraysize(expected_failures); i++) { SCOPED_TRACE(i); std::vector<EncryptionHeaderValues> values; EXPECT_FALSE(ParseEncryptionHeader(expected_failures[i], &values)); EXPECT_EQ(0u, values.size()); } } TEST(EncryptionHeaderParsersTest, ParseValidCryptoKeyHeaders) { struct { const char* const header; const char* const parsed_keyid; const char* const parsed_aesgcm128; const char* const parsed_dh; } expected_results[] = { { "keyid=foo;aesgcm128=c2l4dGVlbmNvb2xieXRlcw;dh=dHdlbHZlY29vbGJ5dGVz", "foo", "sixteencoolbytes", "twelvecoolbytes" }, { "keyid=foo; aesgcm128=c2l4dGVlbmNvb2xieXRlcw; dh=dHdlbHZlY29vbGJ5dGVz", "foo", "sixteencoolbytes", "twelvecoolbytes" }, { "keyid = foo ; aesgcm128 = c2l4dGVlbmNvb2xieXRlcw ; dh = dHdlbHZlY29vbGJ5" "dGVz ", "foo", "sixteencoolbytes", "twelvecoolbytes" }, { "KEYID=foo;AESGCM128=c2l4dGVlbmNvb2xieXRlcw;DH=dHdlbHZlY29vbGJ5dGVz", "foo", "sixteencoolbytes", "twelvecoolbytes" }, { "keyid=foo", "foo", "", "" }, { "aesgcm128=c2l4dGVlbmNvb2xieXRlcw", "", "sixteencoolbytes", "" }, { "aesgcm128=\"c2l4dGVlbmNvb2xieXRlcw\"", "", "sixteencoolbytes", "" }, { "aesgcm128='c2l4dGVlbmNvb2xieXRlcw'", "", "sixteencoolbytes", "" }, { "dh=dHdlbHZlY29vbGJ5dGVz", "", "", "twelvecoolbytes" }, { "keyid=foo;someothervalue=bar;aesgcm128=dHdlbHZlY29vbGJ5dGVz", "foo", "twelvecoolbytes", "" }, { "keyid=foo;keyid=bar", "bar", "", "" }, }; for (size_t i = 0; i < arraysize(expected_results); i++) { SCOPED_TRACE(i); std::vector<CryptoKeyHeaderValues> values; ASSERT_TRUE(ParseCryptoKeyHeader(expected_results[i].header, &values)); ASSERT_EQ(1u, values.size()); EXPECT_EQ(expected_results[i].parsed_keyid, values[0].keyid); EXPECT_EQ(expected_results[i].parsed_aesgcm128, values[0].aesgcm128); EXPECT_EQ(expected_results[i].parsed_dh, values[0].dh); } } TEST(EncryptionHeaderParsersTest, ParseValidMultiValueCryptoKeyHeaders) { const size_t kNumberOfValues = 2u; struct { const char* const header; struct { const char* const keyid; const char* const aesgcm128; const char* const dh; } parsed_values[kNumberOfValues]; } expected_results[] = { { "keyid=foo;aesgcm128=c2l4dGVlbmNvb2xieXRlcw;dh=dHdlbHZlY29vbGJ5dGVz," "keyid=bar;aesgcm128=dHdlbHZlY29vbGJ5dGVz;dh=c2l4dGVlbmNvb2xieXRlcw", { { "foo", "sixteencoolbytes", "twelvecoolbytes" }, { "bar", "twelvecoolbytes", "sixteencoolbytes" } } }, { "keyid=foo,aesgcm128=c2l4dGVlbmNvb2xieXRlcw", { { "foo", "", "" }, { "", "sixteencoolbytes", "" } } }, { "keyid=foo,keyid=bar;dh=dHdlbHZlY29vbGJ5dGVz", { { "foo", "", "" }, { "bar", "", "twelvecoolbytes" } } }, { "keyid=\"foo,keyid=bar\",aesgcm128=c2l4dGVlbmNvb2xieXRlcw", { { "foo,keyid=bar", "", "" }, { "", "sixteencoolbytes", "" } } }, }; for (size_t i = 0; i < arraysize(expected_results); i++) { SCOPED_TRACE(i); std::vector<CryptoKeyHeaderValues> values; ASSERT_TRUE(ParseCryptoKeyHeader(expected_results[i].header, &values)); ASSERT_EQ(kNumberOfValues, values.size()); for (size_t j = 0; j < kNumberOfValues; ++j) { EXPECT_EQ(expected_results[i].parsed_values[j].keyid, values[j].keyid); EXPECT_EQ(expected_results[i].parsed_values[j].aesgcm128, values[j].aesgcm128); EXPECT_EQ(expected_results[i].parsed_values[j].dh, values[j].dh); } } } TEST(EncryptionHeaderParsersTest, ParseInvalidCryptoKeyHeaders) { const char* const expected_failures[] = { "keyid", "keyid=", "keyid=foo,keyid", "keyid=foo;novaluekey", "aesgcm128", "aesgcm128=", "aesgcm128=123$xyz", "aesgcm128=foobar,aesgcm128=123$xyz", "dh", "dh=", "dh=YmV/2ZXJ-sMDA", "dh=dHdlbHZlY29vbGJ5dGVz=====", "dh=123$xyz", }; for (size_t i = 0; i < arraysize(expected_failures); i++) { SCOPED_TRACE(i); std::vector<CryptoKeyHeaderValues> values; EXPECT_FALSE(ParseCryptoKeyHeader(expected_failures[i], &values)); EXPECT_EQ(0u, values.size()); } } TEST(EncryptionHeaderParsersTest, SixValueHeader) { const char* const header = "keyid=0,keyid=1,keyid=2,keyid=3,keyid=4,keyid=5"; std::vector<EncryptionHeaderValues> encryption_values; ASSERT_TRUE(ParseEncryptionHeader(header, &encryption_values)); std::vector<CryptoKeyHeaderValues> crypto_key_values; ASSERT_TRUE(ParseCryptoKeyHeader(header, &crypto_key_values)); ASSERT_EQ(6u, encryption_values.size()); ASSERT_EQ(6u, crypto_key_values.size()); for (size_t i = 0; i < encryption_values.size(); i++) { SCOPED_TRACE(i); const std::string value = base::IntToString(i); EXPECT_EQ(value, encryption_values[i].keyid); EXPECT_EQ(value, crypto_key_values[i].keyid); } } TEST(EncryptionHeaderParsersTest, InvalidHeadersDoNotModifyOutput) { EncryptionHeaderValues encryption_value; encryption_value.keyid = "mykeyid"; encryption_value.salt = "somesalt"; encryption_value.rs = 42u; std::vector<EncryptionHeaderValues> encryption_values; encryption_values.push_back(encryption_value); ASSERT_FALSE(ParseEncryptionHeader("rs=foobar", &encryption_values)); ASSERT_EQ(1u, encryption_values.size()); EXPECT_EQ("mykeyid", encryption_values[0].keyid); EXPECT_EQ("somesalt", encryption_values[0].salt); EXPECT_EQ(42u, encryption_values[0].rs); CryptoKeyHeaderValues crypto_key_value; crypto_key_value.keyid = "myotherkeyid"; crypto_key_value.aesgcm128 = "akey"; crypto_key_value.dh = "yourdh"; std::vector<CryptoKeyHeaderValues> crypto_key_values; crypto_key_values.push_back(crypto_key_value); ASSERT_FALSE(ParseCryptoKeyHeader("aesgcm128=$$$", &crypto_key_values)); ASSERT_EQ(1u, crypto_key_values.size()); EXPECT_EQ("myotherkeyid", crypto_key_values[0].keyid); EXPECT_EQ("akey", crypto_key_values[0].aesgcm128); EXPECT_EQ("yourdh", crypto_key_values[0].dh); } } // namespace } // namespace gcm
33.886288
80
0.67272
[ "vector" ]
b469c4949ba2349bc88edc4ee2999d7f42cb0707
6,696
cpp
C++
FFT/FFT3D.cpp
markmace/OVERLAP
2d26366aa862cbd36182db8ee3165d9fe4d3e704
[ "MIT" ]
1
2020-12-13T03:11:03.000Z
2020-12-13T03:11:03.000Z
FFT/FFT3D.cpp
markmace/OVERLAP
2d26366aa862cbd36182db8ee3165d9fe4d3e704
[ "MIT" ]
null
null
null
FFT/FFT3D.cpp
markmace/OVERLAP
2d26366aa862cbd36182db8ee3165d9fe4d3e704
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////// // IMPLEMENTATION OF THREE DIMENSIONAL FAST FOURIER TRANSFORM // /////////////////////////////////////////////////////////////////// #ifndef __FFT_3D_CPP__ #define __FFT_3D_CPP__ class FFT3D{ // FFTW PARAMETERS // private: static const INT MyDimension=3; INT MyNx,MyNy,MyNz; INT *MyNumberOfSites; INT MyNumberOfTransforms; INT MyOverallSize; INT MyInputMemDistance; INT MyOutputMemDistance; INT MyInputDataSpacing; INT MyOutputDataSpacing; INT *MyInEmbed; INT *MyOutEmbed; // DATA STORAGE // private: fftw_complex *XArray; fftw_complex *PArray; // INDEXING IN COORDINATE AND MOMENTUM SPACE // private: INT XIndex(INT x,INT y,INT z,INT a){ return a+MyNumberOfTransforms*(x+MyNx*(y+MyNy*z)); } INT PIndex(INT px,INT py,INT pz,INT a){ return a+MyNumberOfTransforms*(px+MyNx*(py+MyNy*pz)); } public: void SetX(INT x,INT y, INT z,INT a,DOUBLE Value){ XArray[XIndex(x,y,z,a)][0]=double(Value); XArray[XIndex(x,y,z,a)][1]=double(0.0); } void SetComplexX(INT x,INT y, INT z,INT a,COMPLEX Value){ XArray[XIndex(x,y,z,a)][0]=real(Value); XArray[XIndex(x,y,z,a)][1]=imag(Value); } void SetP(INT px,INT py, INT pz,INT a,COMPLEX Value){ PArray[PIndex(px,py,pz,a)][0]=double(real(Value)); PArray[PIndex(px,py,pz,a)][1]=double(imag(Value)); } COMPLEX GetX(INT x,INT y,INT z,INT a){ return COMPLEX(XArray[XIndex(x,y,z,a)][0],XArray[XIndex(x,y,z,a)][1]); } COMPLEX GetP(INT px,INT py,INT pz,INT a){ return COMPLEX(PArray[PIndex(px,py,pz,a)][0],PArray[PIndex(px,py,pz,a)][1]); } // FFTW PLANS // private: fftw_plan XtoP; fftw_plan PtoX; /////////////////////// // CLASS CONSTRUCTOR // /////////////////////// public: FFT3D(INT Nx,INT Ny,INT Nz,INT NumberOfTransforms){ //////////////////////// //SET FFTW PARAMETERS // //////////////////////// //NUMBER OF SITES IN EACH DIMENSION MyNx=Nx; MyNy=Ny; MyNz=Nz; // SET IN REVERSED ORDERING TO SWITCH FROM ROW-MAJOR TO COLUMN-MAJOR FORMAT // MyNumberOfSites=new INT[3]; MyNumberOfSites[0]=MyNz; MyNumberOfSites[1]=MyNy; MyNumberOfSites[2]=MyNx; //NUMBER OF INDEPENDENT TRANSFORMS MyNumberOfTransforms=NumberOfTransforms; //OVERALL DATA SIZE MyOverallSize=MyNx*MyNy*MyNz*NumberOfTransforms; //SPACING BETWEEN DATASETS MyInputMemDistance=1; MyOutputMemDistance=1; //SPACING BETWEEN POINTS OF THE SAME DATASET MyInputDataSpacing=MyNumberOfTransforms; MyOutputDataSpacing=MyNumberOfTransforms; // EMBEDDING OF INDIVIDUAL DATASETS // MyInEmbed=MyNumberOfSites; MyOutEmbed=MyNumberOfSites; //////////////////////// // ALLOCATE ARRAYS // //////////////////////// XArray=fftw_alloc_complex(MyOverallSize); PArray=fftw_alloc_complex(MyOverallSize); //////////////////////// // COMPUTE PLANS // //////////////////////// XtoP=fftw_plan_many_dft(MyDimension,MyNumberOfSites,MyNumberOfTransforms, XArray,MyInEmbed, MyInputDataSpacing, MyInputMemDistance, PArray,MyOutEmbed, MyOutputDataSpacing,MyOutputMemDistance, FFTW_FORWARD,MY_FFTW_PLANNER_FLAG); PtoX=fftw_plan_many_dft(MyDimension,MyNumberOfSites,MyNumberOfTransforms, PArray,MyOutEmbed, MyOutputDataSpacing, MyOutputMemDistance, XArray,MyInEmbed, MyInputDataSpacing, MyInputMemDistance, FFTW_BACKWARD,MY_FFTW_PLANNER_FLAG); } /////////////////////// // CLASS DESTRUCTOR // /////////////////////// ~FFT3D(){ //DESTROY PLANS// fftw_destroy_plan(XtoP); fftw_destroy_plan(PtoX); //DELETE FFTW PARAMETERS // delete[] MyNumberOfSites; //FREE MEMORY // fftw_free(XArray); fftw_free(PArray); } ////////////////////////// // EXECUTION COMMANDS // ////////////////////////// public: void ExecuteXtoP(){ fftw_execute(XtoP); } void ExecutePtoX(){ fftw_execute(PtoX); } public: void OutputX(std::string fname){ std::ofstream OutStream; OutStream.open(fname.c_str()); for(INT z=0;z<MyNz;z++){ for(INT y=0;y<MyNy;y++){ for(INT x=0;x<MyNx;x++){ OutStream << x << " " << y << " " << z << " "; for(INT a=0;a<MyNumberOfTransforms;a++){ OutStream << real(GetX(x,y,z,a)) << " " << imag(GetX(x,y,z,a)) << " "; } OutStream << std::endl; } OutStream << std::endl; } OutStream << std::endl; } OutStream.close(); } void OutputP(std::string fname){ std::ofstream OutStream; OutStream.open(fname.c_str()); for(INT pz=0;pz<MyNz;pz++){ for(INT py=0;py<MyNy;py++){ for(INT px=0;px<MyNx;px++){ OutStream << px << " " << py << " " << pz << " "; for(INT a=0;a<MyNumberOfTransforms;a++){ OutStream << real(GetP(px,py,pz,a)) << " " << imag(GetP(px,py,pz,a)) << " "; } OutStream << std::endl; } OutStream << std::endl; } OutStream << std::endl; } OutStream.close(); } }; #endif
26.784
109
0.444594
[ "transform" ]
b46c33b508906fba2dc540767b1cd884b4d958bd
100,234
cc
C++
gui/duilib/3rdparty/libcef/tests/ceftests/v8_unittest.cc
pqgarden/PQBase
fe64dc937c2d86cb6363b2c0a394f0a9d794b116
[ "MIT" ]
1
2020-12-24T16:00:57.000Z
2020-12-24T16:00:57.000Z
gui/duilib/3rdparty/libcef/tests/ceftests/v8_unittest.cc
pqgarden/PQBase
fe64dc937c2d86cb6363b2c0a394f0a9d794b116
[ "MIT" ]
null
null
null
gui/duilib/3rdparty/libcef/tests/ceftests/v8_unittest.cc
pqgarden/PQBase
fe64dc937c2d86cb6363b2c0a394f0a9d794b116
[ "MIT" ]
1
2021-01-26T13:01:36.000Z
2021-01-26T13:01:36.000Z
// Copyright (c) 2013 The Chromium Embedded Framework 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 <sstream> #include "include/base/cef_bind.h" #include "include/cef_task.h" #include "include/cef_v8.h" #include "include/wrapper/cef_closure_task.h" #include "tests/ceftests/test_handler.h" #include "tests/gtest/include/gtest/gtest.h" #include "tests/shared/browser/client_app_browser.h" #include "tests/shared/renderer/client_app_renderer.h" using client::ClientAppBrowser; using client::ClientAppRenderer; // How to add a new test: // 1. Add a new value to the V8TestMode enumeration. // 2. Add a method that implements the test in V8RendererTest. // 3. Add a case for the new enumeration value in V8RendererTest::RunTest. // 4. Add a line for the test in the "Define the tests" section at the bottom of // the file. namespace { // Unique values for V8 tests. const char kV8TestUrl[] = "http://tests/V8Test.Test"; const char kV8BindingTestUrl[] = "http://tests/V8Test.BindingTest"; const char kV8ContextParentTestUrl[] = "http://tests/V8Test.ContextParentTest"; const char kV8ContextChildTestUrl[] = "http://tests/V8Test.ContextChildTest"; const char kV8NavTestUrl[] = "http://tests/V8Test.NavTest"; const char kV8ContextEvalCspBypassUnsafeEval[] = "http://tests/V8Test.ContextEvalCspBypassUnsafeEval"; const char kV8ContextEvalCspBypassSandbox[] = "http://tests/V8Test.ContextEvalCspBypassSandbox"; const char kV8OnUncaughtExceptionTestUrl[] = "http://tests/V8Test.OnUncaughtException"; const char kV8HandlerCallOnReleasedContextUrl[] = "http://tests/V8Test.HandlerCallOnReleasedContext/main.html"; const char kV8HandlerCallOnReleasedContextChildUrl[] = "http://tests/V8Test.HandlerCallOnReleasedContext/child.html"; const char kV8TestMsg[] = "V8Test.Test"; const char kV8TestCmdKey[] = "v8-test"; const char kV8RunTestMsg[] = "V8Test.RunTest"; enum V8TestMode { V8TEST_NONE = 0, V8TEST_NULL_CREATE, V8TEST_BOOL_CREATE, V8TEST_INT_CREATE, V8TEST_UINT_CREATE, V8TEST_DOUBLE_CREATE, V8TEST_DATE_CREATE, V8TEST_STRING_CREATE, V8TEST_EMPTY_STRING_CREATE, V8TEST_ARRAY_CREATE, V8TEST_ARRAY_VALUE, V8TEST_ARRAY_BUFFER, V8TEST_ARRAY_BUFFER_VALUE, V8TEST_OBJECT_CREATE, V8TEST_OBJECT_USERDATA, V8TEST_OBJECT_ACCESSOR, V8TEST_OBJECT_ACCESSOR_EXCEPTION, V8TEST_OBJECT_ACCESSOR_FAIL, V8TEST_OBJECT_ACCESSOR_READONLY, V8TEST_OBJECT_INTERCEPTOR, V8TEST_OBJECT_INTERCEPTOR_FAIL, V8TEST_OBJECT_INTERCEPTOR_EXCEPTION, V8TEST_OBJECT_INTERCEPTOR_AND_ACCESSOR, V8TEST_OBJECT_VALUE, V8TEST_OBJECT_VALUE_READONLY, V8TEST_OBJECT_VALUE_ENUM, V8TEST_OBJECT_VALUE_DONTENUM, V8TEST_OBJECT_VALUE_DELETE, V8TEST_OBJECT_VALUE_DONTDELETE, V8TEST_OBJECT_VALUE_EMPTYKEY, V8TEST_FUNCTION_CREATE, V8TEST_FUNCTION_HANDLER, V8TEST_FUNCTION_HANDLER_EXCEPTION, V8TEST_FUNCTION_HANDLER_FAIL, V8TEST_FUNCTION_HANDLER_NO_OBJECT, V8TEST_FUNCTION_HANDLER_WITH_CONTEXT, V8TEST_FUNCTION_HANDLER_EMPTY_STRING, V8TEST_CONTEXT_EVAL, V8TEST_CONTEXT_EVAL_EXCEPTION, V8TEST_CONTEXT_EVAL_CSP_BYPASS_UNSAFE_EVAL, V8TEST_CONTEXT_EVAL_CSP_BYPASS_SANDBOX, V8TEST_CONTEXT_ENTERED, V8TEST_BINDING, V8TEST_STACK_TRACE, V8TEST_ON_UNCAUGHT_EXCEPTION, V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS, V8TEST_EXTENSION, V8TEST_HANDLER_CALL_ON_RELEASED_CONTEXT, }; // Renderer side. class V8RendererTest : public ClientAppRenderer::Delegate, public CefLoadHandler { public: V8RendererTest() : test_mode_(V8TEST_NONE) {} // Run a test when the process message is received from the browser. void RunTest() { switch (test_mode_) { case V8TEST_NULL_CREATE: RunNullCreateTest(); break; case V8TEST_BOOL_CREATE: RunBoolCreateTest(); break; case V8TEST_INT_CREATE: RunIntCreateTest(); break; case V8TEST_UINT_CREATE: RunUIntCreateTest(); break; case V8TEST_DOUBLE_CREATE: RunDoubleCreateTest(); break; case V8TEST_DATE_CREATE: RunDateCreateTest(); break; case V8TEST_STRING_CREATE: RunStringCreateTest(); break; case V8TEST_EMPTY_STRING_CREATE: RunEmptyStringCreateTest(); break; case V8TEST_ARRAY_CREATE: RunArrayCreateTest(); break; case V8TEST_ARRAY_VALUE: RunArrayValueTest(); break; case V8TEST_ARRAY_BUFFER: RunArrayBufferTest(); break; case V8TEST_ARRAY_BUFFER_VALUE: RunArrayBufferValueTest(); break; case V8TEST_OBJECT_CREATE: RunObjectCreateTest(); break; case V8TEST_OBJECT_USERDATA: RunObjectUserDataTest(); break; case V8TEST_OBJECT_ACCESSOR: RunObjectAccessorTest(); break; case V8TEST_OBJECT_ACCESSOR_EXCEPTION: RunObjectAccessorExceptionTest(); break; case V8TEST_OBJECT_ACCESSOR_FAIL: RunObjectAccessorFailTest(); break; case V8TEST_OBJECT_ACCESSOR_READONLY: RunObjectAccessorReadOnlyTest(); break; case V8TEST_OBJECT_INTERCEPTOR: RunObjectInterceptorTest(); break; case V8TEST_OBJECT_INTERCEPTOR_FAIL: RunObjectInterceptorFailTest(); break; case V8TEST_OBJECT_INTERCEPTOR_EXCEPTION: RunObjectInterceptorExceptionTest(); break; case V8TEST_OBJECT_INTERCEPTOR_AND_ACCESSOR: RunObjectInterceptorAndAccessorTest(); break; case V8TEST_OBJECT_VALUE: RunObjectValueTest(); break; case V8TEST_OBJECT_VALUE_READONLY: RunObjectValueReadOnlyTest(); break; case V8TEST_OBJECT_VALUE_ENUM: RunObjectValueEnumTest(); break; case V8TEST_OBJECT_VALUE_DONTENUM: RunObjectValueDontEnumTest(); break; case V8TEST_OBJECT_VALUE_DELETE: RunObjectValueDeleteTest(); break; case V8TEST_OBJECT_VALUE_DONTDELETE: RunObjectValueDontDeleteTest(); break; case V8TEST_OBJECT_VALUE_EMPTYKEY: RunObjectValueEmptyKeyTest(); break; case V8TEST_FUNCTION_CREATE: RunFunctionCreateTest(); break; case V8TEST_FUNCTION_HANDLER: RunFunctionHandlerTest(); break; case V8TEST_FUNCTION_HANDLER_EXCEPTION: RunFunctionHandlerExceptionTest(); break; case V8TEST_FUNCTION_HANDLER_FAIL: RunFunctionHandlerFailTest(); break; case V8TEST_FUNCTION_HANDLER_NO_OBJECT: RunFunctionHandlerNoObjectTest(); break; case V8TEST_FUNCTION_HANDLER_WITH_CONTEXT: RunFunctionHandlerWithContextTest(); break; case V8TEST_FUNCTION_HANDLER_EMPTY_STRING: RunFunctionHandlerEmptyStringTest(); break; case V8TEST_CONTEXT_EVAL: RunContextEvalTest(); break; case V8TEST_CONTEXT_EVAL_EXCEPTION: RunContextEvalExceptionTest(); break; case V8TEST_CONTEXT_EVAL_CSP_BYPASS_UNSAFE_EVAL: RunContextEvalCspBypassUnsafeEval(); break; case V8TEST_CONTEXT_EVAL_CSP_BYPASS_SANDBOX: RunContextEvalCspBypassSandbox(); break; case V8TEST_CONTEXT_ENTERED: RunContextEnteredTest(); break; case V8TEST_BINDING: RunBindingTest(); break; case V8TEST_STACK_TRACE: RunStackTraceTest(); break; case V8TEST_ON_UNCAUGHT_EXCEPTION: RunOnUncaughtExceptionTest(); break; case V8TEST_HANDLER_CALL_ON_RELEASED_CONTEXT: break; default: // Was a startup test. EXPECT_TRUE(startup_test_success_); DestroyTest(); break; } } // Run a test on render process startup. void RunStartupTest() { switch (test_mode_) { case V8TEST_EXTENSION: RunExtensionTest(); break; default: break; } } void RunNullCreateTest() { CefRefPtr<CefV8Value> value = CefV8Value::CreateNull(); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsNull()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsDouble()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsObject()); EXPECT_FALSE(value->IsString()); DestroyTest(); } void RunBoolCreateTest() { CefRefPtr<CefV8Value> value = CefV8Value::CreateBool(true); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsBool()); EXPECT_EQ(true, value->GetBoolValue()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsDouble()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsObject()); EXPECT_FALSE(value->IsString()); DestroyTest(); } void RunIntCreateTest() { CefRefPtr<CefV8Value> value = CefV8Value::CreateInt(12); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsInt()); EXPECT_TRUE(value->IsUInt()); EXPECT_TRUE(value->IsDouble()); EXPECT_EQ(12, value->GetIntValue()); EXPECT_EQ((uint32)12, value->GetUIntValue()); EXPECT_EQ(12, value->GetDoubleValue()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsObject()); EXPECT_FALSE(value->IsString()); DestroyTest(); } void RunUIntCreateTest() { CefRefPtr<CefV8Value> value = CefV8Value::CreateUInt(12); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsInt()); EXPECT_TRUE(value->IsUInt()); EXPECT_TRUE(value->IsDouble()); EXPECT_EQ(12, value->GetIntValue()); EXPECT_EQ((uint32)12, value->GetUIntValue()); EXPECT_EQ(12, value->GetDoubleValue()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsObject()); EXPECT_FALSE(value->IsString()); DestroyTest(); } void RunDoubleCreateTest() { CefRefPtr<CefV8Value> value = CefV8Value::CreateDouble(12.1223); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsDouble()); EXPECT_EQ(12.1223, value->GetDoubleValue()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsObject()); EXPECT_FALSE(value->IsString()); DestroyTest(); } void RunDateCreateTest() { CefRefPtr<CefV8Context> context = GetContext(); CefTime date; date.year = 2200; date.month = 4; #if !defined(OS_MAC) date.day_of_week = 5; #endif date.day_of_month = 11; date.hour = 20; date.minute = 15; date.second = 42; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> value = CefV8Value::CreateDate(date); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsDate()); EXPECT_EQ(date.GetTimeT(), value->GetDateValue().GetTimeT()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDouble()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsObject()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsString()); DestroyTest(); } void RunStringCreateTest() { CefRefPtr<CefV8Value> value = CefV8Value::CreateString("My string"); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsString()); EXPECT_STREQ("My string", value->GetStringValue().ToString().c_str()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsDouble()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsObject()); DestroyTest(); } void RunEmptyStringCreateTest() { CefRefPtr<CefV8Value> value = CefV8Value::CreateString(CefString()); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsString()); EXPECT_STREQ("", value->GetStringValue().ToString().c_str()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsDouble()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsObject()); DestroyTest(); } void RunArrayCreateTest() { CefRefPtr<CefV8Context> context = GetContext(); // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> value = CefV8Value::CreateArray(2); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsArray()); EXPECT_TRUE(value->IsObject()); EXPECT_EQ(2, value->GetArrayLength()); EXPECT_FALSE(value->HasValue(0)); EXPECT_FALSE(value->HasValue(1)); // Exit the V8 context. EXPECT_TRUE(context->Exit()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsDouble()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsString()); DestroyTest(); } void RunArrayValueTest() { CefRefPtr<CefV8Context> context = GetContext(); // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> value = CefV8Value::CreateArray(0); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsArray()); EXPECT_EQ(0, value->GetArrayLength()); // Test addng values. EXPECT_FALSE(value->HasValue(0)); EXPECT_FALSE(value->HasValue(1)); EXPECT_TRUE(value->SetValue(0, CefV8Value::CreateInt(10))); EXPECT_FALSE(value->HasException()); EXPECT_TRUE(value->HasValue(0)); EXPECT_FALSE(value->HasValue(1)); EXPECT_TRUE(value->GetValue(0)->IsInt()); EXPECT_EQ(10, value->GetValue(0)->GetIntValue()); EXPECT_FALSE(value->HasException()); EXPECT_EQ(1, value->GetArrayLength()); EXPECT_TRUE(value->SetValue(1, CefV8Value::CreateInt(43))); EXPECT_FALSE(value->HasException()); EXPECT_TRUE(value->HasValue(0)); EXPECT_TRUE(value->HasValue(1)); EXPECT_TRUE(value->GetValue(1)->IsInt()); EXPECT_EQ(43, value->GetValue(1)->GetIntValue()); EXPECT_FALSE(value->HasException()); EXPECT_EQ(2, value->GetArrayLength()); EXPECT_TRUE(value->DeleteValue(0)); EXPECT_FALSE(value->HasValue(0)); EXPECT_TRUE(value->HasValue(1)); EXPECT_EQ(2, value->GetArrayLength()); EXPECT_TRUE(value->DeleteValue(1)); EXPECT_FALSE(value->HasValue(0)); EXPECT_FALSE(value->HasValue(1)); EXPECT_EQ(2, value->GetArrayLength()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunArrayBufferTest() { class TestArrayBufferReleaseCallback : public CefV8ArrayBufferReleaseCallback { public: TestArrayBufferReleaseCallback(bool* destructorCalled, bool* releaseBufferCalled) : destructorCalled_(destructorCalled), releaseBufferCalled_(releaseBufferCalled) {} ~TestArrayBufferReleaseCallback() { *destructorCalled_ = true; } void ReleaseBuffer(void* buffer) override { *releaseBufferCalled_ = true; } IMPLEMENT_REFCOUNTING(TestArrayBufferReleaseCallback); private: bool* destructorCalled_; bool* releaseBufferCalled_; }; CefRefPtr<CefV8Context> context = GetContext(); bool destructorCalled = false; bool releaseBufferCalled = false; bool neuteredDestructorCalled = false; bool neuteredReleaseBufferCalled = false; // Enter the V8 context. EXPECT_TRUE(context->Enter()); { int static_data[16]; CefRefPtr<CefV8Value> value; CefRefPtr<TestArrayBufferReleaseCallback> release_callback = new TestArrayBufferReleaseCallback(&destructorCalled, &releaseBufferCalled); CefRefPtr<CefV8Value> neuteredValue; CefRefPtr<TestArrayBufferReleaseCallback> neuteredReleaseCallback = new TestArrayBufferReleaseCallback(&neuteredDestructorCalled, &neuteredReleaseBufferCalled); value = CefV8Value::CreateArrayBuffer(static_data, sizeof(static_data), release_callback); neuteredValue = CefV8Value::CreateArrayBuffer( static_data, sizeof(static_data), neuteredReleaseCallback); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsArrayBuffer()); EXPECT_TRUE(value->IsObject()); EXPECT_FALSE(value->HasValue(0)); EXPECT_FALSE(destructorCalled); EXPECT_TRUE(value->GetArrayBufferReleaseCallback().get() != nullptr); EXPECT_TRUE(((TestArrayBufferReleaseCallback*)value ->GetArrayBufferReleaseCallback() .get()) == release_callback); EXPECT_TRUE(neuteredValue->NeuterArrayBuffer()); } // Exit the V8 context. EXPECT_TRUE(destructorCalled); EXPECT_TRUE(releaseBufferCalled); EXPECT_TRUE(neuteredDestructorCalled); EXPECT_FALSE(neuteredReleaseBufferCalled); EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunArrayBufferValueTest() { class TestArrayBufferReleaseCallback : public CefV8ArrayBufferReleaseCallback { public: TestArrayBufferReleaseCallback() {} ~TestArrayBufferReleaseCallback() {} void ReleaseBuffer(void* buffer) override {} IMPLEMENT_REFCOUNTING(TestArrayBufferReleaseCallback); }; CefRefPtr<CefV8Context> context = GetContext(); // Enter the V8 context. CefRefPtr<CefV8Value> value; CefRefPtr<TestArrayBufferReleaseCallback> owner = new TestArrayBufferReleaseCallback(); EXPECT_TRUE(context->Enter()); int static_data[16]; static_data[0] = 3; value = CefV8Value::CreateArrayBuffer(static_data, sizeof(static_data), owner); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); object->SetValue("arr", value, V8_PROPERTY_ATTRIBUTE_NONE); std::string test = "let data = new Int32Array(window.arr); data[0] += data.length"; CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(context->Eval(test, CefString(), 0, retval, exception)); if (exception.get()) ADD_FAILURE() << exception->GetMessage().c_str(); EXPECT_TRUE(static_data[0] == 19); EXPECT_TRUE(value->GetArrayBufferReleaseCallback().get() != nullptr); EXPECT_TRUE(value->NeuterArrayBuffer()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectCreateTest() { CefRefPtr<CefV8Context> context = GetContext(); // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> value = CefV8Value::CreateObject(nullptr, nullptr); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsObject()); EXPECT_FALSE(value->GetUserData().get()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsDouble()); EXPECT_FALSE(value->IsFunction()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsString()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectUserDataTest() { CefRefPtr<CefV8Context> context = GetContext(); class UserData : public CefBaseRefCounted { public: explicit UserData(int value) : value_(value) {} int value_; IMPLEMENT_REFCOUNTING(UserData); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> value = CefV8Value::CreateObject(nullptr, nullptr); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->SetUserData(new UserData(10))); CefRefPtr<CefBaseRefCounted> user_data = value->GetUserData(); EXPECT_TRUE(user_data.get()); UserData* user_data_impl = static_cast<UserData*>(user_data.get()); EXPECT_EQ(10, user_data_impl->value_); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectAccessorTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "val"; static const int kValue = 20; class Accessor : public CefV8Accessor { public: Accessor() : value_(0) {} bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) override { EXPECT_STREQ(kName, name.ToString().c_str()); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->IsSame(object_)); EXPECT_FALSE(retval.get()); EXPECT_TRUE(exception.empty()); got_get_.yes(); retval = CefV8Value::CreateInt(value_); EXPECT_EQ(kValue, retval->GetIntValue()); return true; } bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) override { EXPECT_STREQ(kName, name.ToString().c_str()); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->IsSame(object_)); EXPECT_TRUE(value.get()); EXPECT_TRUE(exception.empty()); got_set_.yes(); value_ = value->GetIntValue(); EXPECT_EQ(kValue, value_); return true; } CefRefPtr<CefV8Value> object_; int value_; TrackCallback got_get_; TrackCallback got_set_; IMPLEMENT_REFCOUNTING(Accessor); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Accessor* accessor = new Accessor; CefRefPtr<CefV8Accessor> accessorPtr(accessor); CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(accessor, nullptr); EXPECT_TRUE(object.get()); accessor->object_ = object; EXPECT_FALSE(object->HasValue(kName)); EXPECT_TRUE(object->SetValue(kName, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(object->HasValue(kName)); EXPECT_TRUE(object->SetValue(kName, CefV8Value::CreateInt(kValue), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(accessor->got_set_); EXPECT_EQ(kValue, accessor->value_); CefRefPtr<CefV8Value> val = object->GetValue(kName); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(val.get()); EXPECT_TRUE(accessor->got_get_); EXPECT_TRUE(val->IsInt()); EXPECT_EQ(kValue, val->GetIntValue()); accessor->object_ = nullptr; // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectAccessorExceptionTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "val"; static const char* kGetException = "My get exception"; static const char* kSetException = "My set exception"; static const char* kGetExceptionMsg = "Uncaught Error: My get exception"; static const char* kSetExceptionMsg = "Uncaught Error: My set exception"; class Accessor : public CefV8Accessor { public: Accessor() {} bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) override { got_get_.yes(); exception = kGetException; return true; } bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) override { got_set_.yes(); exception = kSetException; return true; } TrackCallback got_get_; TrackCallback got_set_; IMPLEMENT_REFCOUNTING(Accessor); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Exception> exception; Accessor* accessor = new Accessor; CefRefPtr<CefV8Accessor> accessorPtr(accessor); CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(accessor, nullptr); EXPECT_TRUE(object.get()); EXPECT_FALSE(object->HasValue(kName)); EXPECT_TRUE(object->SetValue(kName, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(object->HasValue(kName)); EXPECT_FALSE(object->SetValue(kName, CefV8Value::CreateInt(1), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_TRUE(object->HasException()); EXPECT_TRUE(accessor->got_set_); exception = object->GetException(); EXPECT_TRUE(exception.get()); EXPECT_STREQ(kSetExceptionMsg, exception->GetMessage().ToString().c_str()); EXPECT_TRUE(object->ClearException()); EXPECT_FALSE(object->HasException()); CefRefPtr<CefV8Value> val = object->GetValue(kName); EXPECT_FALSE(val.get()); EXPECT_TRUE(object->HasException()); EXPECT_TRUE(accessor->got_get_); exception = object->GetException(); EXPECT_TRUE(exception.get()); EXPECT_STREQ(kGetExceptionMsg, exception->GetMessage().ToString().c_str()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectAccessorFailTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "val"; class Accessor : public CefV8Accessor { public: Accessor() {} bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) override { got_get_.yes(); return false; } bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) override { got_set_.yes(); return false; } TrackCallback got_get_; TrackCallback got_set_; IMPLEMENT_REFCOUNTING(Accessor); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Exception> exception; Accessor* accessor = new Accessor; CefRefPtr<CefV8Accessor> accessorPtr(accessor); CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(accessor, nullptr); EXPECT_TRUE(object.get()); EXPECT_FALSE(object->HasValue(kName)); EXPECT_TRUE(object->SetValue(kName, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(object->HasValue(kName)); EXPECT_TRUE(object->SetValue(kName, CefV8Value::CreateInt(1), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(accessor->got_set_); CefRefPtr<CefV8Value> val = object->GetValue(kName); EXPECT_TRUE(val.get()); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(accessor->got_get_); EXPECT_TRUE(val->IsUndefined()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectAccessorReadOnlyTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "val"; class Accessor : public CefV8Accessor { public: Accessor() {} bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) override { got_get_.yes(); return true; } bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) override { got_set_.yes(); return true; } TrackCallback got_get_; TrackCallback got_set_; IMPLEMENT_REFCOUNTING(Accessor); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Exception> exception; Accessor* accessor = new Accessor; CefRefPtr<CefV8Accessor> accessorPtr(accessor); CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(accessor, nullptr); EXPECT_TRUE(object.get()); EXPECT_FALSE(object->HasValue(kName)); EXPECT_TRUE(object->SetValue(kName, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_READONLY)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(object->HasValue(kName)); EXPECT_TRUE(object->SetValue(kName, CefV8Value::CreateInt(1), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_FALSE(accessor->got_set_); CefRefPtr<CefV8Value> val = object->GetValue(kName); EXPECT_TRUE(val.get()); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(accessor->got_get_); EXPECT_TRUE(val->IsUndefined()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectInterceptorTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName1 = "val1"; static const char* kName2 = "val2"; static const char* kName3 = "val3"; static const int kValue1 = 20; static const uint32 kValue2 = 30u; static const char* kValue3 = "40"; static const int kArray[] = {50, 60, 70}; class Interceptor : public CefV8Interceptor { public: Interceptor() : value1_(0), value2_(0u), array_() {} virtual bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { EXPECT_TRUE(name.ToString() == kName1 || name.ToString() == kName2 || name.ToString() == kName3); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->IsSame(object_)); EXPECT_FALSE(retval.get()); EXPECT_TRUE(exception.empty()); got_get_byname_.yes(); if (name.ToString() == kName1) { retval = CefV8Value::CreateInt(value1_); EXPECT_EQ(kValue1, retval->GetIntValue()); } else if (name.ToString() == kName2) { retval = CefV8Value::CreateUInt(value2_); EXPECT_EQ(kValue2, retval->GetUIntValue()); } else if (name.ToString() == kName3) { retval = CefV8Value::CreateString(value3_); EXPECT_STREQ(kValue3, retval->GetStringValue().ToString().c_str()); } return true; } virtual bool Get(int index, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { EXPECT_TRUE(index >= 0 && index < 3); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->IsSame(object_)); EXPECT_FALSE(retval.get()); EXPECT_TRUE(exception.empty()); got_get_byindex_.yes(); retval = CefV8Value::CreateInt(array_[index]); EXPECT_EQ(kArray[index], retval->GetIntValue()); return true; } virtual bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { EXPECT_TRUE(name.ToString() == kName1 || name.ToString() == kName2 || name.ToString() == kName3); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->IsSame(object_)); EXPECT_TRUE(value.get()); EXPECT_TRUE(exception.empty()); got_set_byname_.yes(); if (name.ToString() == kName1) { value1_ = value->GetIntValue(); EXPECT_EQ(kValue1, value1_); } else if (name.ToString() == kName2) { value2_ = value->GetUIntValue(); EXPECT_EQ(kValue2, value2_); } else if (name.ToString() == kName3) { value3_ = value->GetStringValue(); EXPECT_STREQ(kValue3, value3_.ToString().c_str()); } return true; } virtual bool Set(int index, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { EXPECT_TRUE(index >= 0 && index < 3); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->IsSame(object_)); EXPECT_TRUE(value.get()); EXPECT_TRUE(exception.empty()); got_set_byindex_.yes(); array_[index] = value->GetIntValue(); EXPECT_EQ(array_[index], kArray[index]); return true; } CefRefPtr<CefV8Value> object_; int value1_; unsigned int value2_; CefString value3_; int array_[3]; TrackCallback got_get_byname_; TrackCallback got_get_byindex_; TrackCallback got_set_byname_; TrackCallback got_set_byindex_; IMPLEMENT_REFCOUNTING(Interceptor); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Interceptor* interceptor = new Interceptor; CefRefPtr<CefV8Interceptor> interceptorPtr(interceptor); CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(nullptr, interceptor); EXPECT_TRUE(object.get()); interceptor->object_ = object; EXPECT_FALSE(object->HasException()); EXPECT_TRUE(object->SetValue(kName1, CefV8Value::CreateInt(kValue1), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_set_byname_); interceptor->got_set_byname_.reset(); EXPECT_TRUE(object->SetValue(kName2, CefV8Value::CreateUInt(kValue2), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_set_byname_); interceptor->got_set_byname_.reset(); EXPECT_TRUE(object->SetValue(kName3, CefV8Value::CreateString(kValue3), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_set_byname_); interceptor->got_set_byname_.reset(); EXPECT_EQ(kValue1, interceptor->value1_); EXPECT_EQ(kValue2, interceptor->value2_); EXPECT_STREQ(kValue3, interceptor->value3_.ToString().c_str()); for (int i = 0; i < 3; ++i) { EXPECT_TRUE(object->SetValue(i, CefV8Value::CreateInt(kArray[i]))); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_set_byindex_); interceptor->got_set_byindex_.reset(); EXPECT_EQ(kArray[i], interceptor->array_[i]); } CefRefPtr<CefV8Value> val1 = object->GetValue(kName1); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(val1.get()); EXPECT_TRUE(interceptor->got_get_byname_); interceptor->got_get_byname_.reset(); EXPECT_TRUE(val1->IsInt()); EXPECT_EQ(kValue1, val1->GetIntValue()); CefRefPtr<CefV8Value> val2 = object->GetValue(kName2); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(val2.get()); EXPECT_TRUE(interceptor->got_get_byname_); interceptor->got_get_byname_.reset(); EXPECT_TRUE(val2->IsUInt()); EXPECT_EQ(kValue2, val2->GetUIntValue()); CefRefPtr<CefV8Value> val3 = object->GetValue(kName3); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(val3.get()); EXPECT_TRUE(interceptor->got_get_byname_); interceptor->got_get_byname_.reset(); EXPECT_TRUE(val3->IsString()); EXPECT_STREQ(kValue3, val3->GetStringValue().ToString().c_str()); for (int i = 0; i < 3; ++i) { CefRefPtr<CefV8Value> val = object->GetValue(i); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(val.get()); EXPECT_TRUE(interceptor->got_get_byindex_); interceptor->got_get_byname_.reset(); EXPECT_EQ(kArray[i], val->GetIntValue()); } interceptor->object_ = nullptr; // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectInterceptorFailTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "val"; static const int kIndex = 0; static const int kValue1 = 20; static const int kValue2 = 30; class Interceptor : public CefV8Interceptor { typedef std::map<int, int> IntMap; typedef std::map<std::string, int> StringMap; public: Interceptor() {} virtual bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { got_get_byname_.yes(); StringMap::iterator it = string_map_.find(name.ToString()); if (it != string_map_.end()) { retval = CefV8Value::CreateInt(it->second); } return true; } virtual bool Get(int index, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { got_get_byindex_.yes(); IntMap::iterator it = int_map_.find(index); if (it != int_map_.end()) { retval = CefV8Value::CreateInt(it->second); } return true; } virtual bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { EXPECT_TRUE(value->IsInt()); got_set_byname_.yes(); string_map_[name.ToString()] = value->GetIntValue(); return true; } virtual bool Set(int index, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { EXPECT_TRUE(value->IsInt()); got_set_byindex_.yes(); int_map_[index] = value->GetIntValue(); return true; } IntMap int_map_; StringMap string_map_; TrackCallback got_get_byname_; TrackCallback got_get_byindex_; TrackCallback got_set_byname_; TrackCallback got_set_byindex_; IMPLEMENT_REFCOUNTING(Interceptor); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Interceptor* interceptor = new Interceptor; CefRefPtr<CefV8Interceptor> interceptorPtr(interceptor); CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(nullptr, interceptor); EXPECT_TRUE(object.get()); EXPECT_FALSE(object->HasValue(kName)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_get_byname_); interceptor->got_get_byname_.reset(); CefRefPtr<CefV8Value> val1 = object->GetValue(kName); EXPECT_TRUE(val1.get()); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_get_byname_); EXPECT_TRUE(val1->IsUndefined()); interceptor->got_get_byname_.reset(); EXPECT_TRUE(object->SetValue(kName, CefV8Value::CreateInt(kValue1), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_set_byname_); val1 = object->GetValue(kName); EXPECT_TRUE(val1.get()); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_get_byname_); EXPECT_EQ(kValue1, val1->GetIntValue()); EXPECT_FALSE(object->HasValue(kIndex)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_get_byindex_); interceptor->got_get_byindex_.reset(); CefRefPtr<CefV8Value> val2 = object->GetValue(kIndex); EXPECT_TRUE(val2.get()); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_get_byindex_); EXPECT_TRUE(val2->IsUndefined()); interceptor->got_get_byindex_.reset(); EXPECT_TRUE(object->SetValue(kIndex, CefV8Value::CreateInt(kValue2))); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_set_byindex_); val2 = object->GetValue(kIndex); EXPECT_TRUE(val2.get()); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(interceptor->got_get_byindex_); EXPECT_EQ(kValue2, val2->GetIntValue()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectInterceptorExceptionTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "val"; static const int kIndex = 1; static const char* kGetByNameException = "My get_byname exception"; static const char* kGetByIndexException = "My get_byindex exception"; static const char* kSetByNameException = "My set_byname exception"; static const char* kSetByIndexException = "My set_byindex exception"; static const char* kGetByNameExceptionMsg = "Uncaught Error: My get_byname exception"; static const char* kGetByIndexExceptionMsg = "Uncaught Error: My get_byindex exception"; static const char* kSetByNameExceptionMsg = "Uncaught Error: My set_byname exception"; static const char* kSetByIndexExceptionMsg = "Uncaught Error: My set_byindex exception"; class Interceptor : public CefV8Interceptor { public: Interceptor() {} virtual bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { got_get_byname_.yes(); exception = kGetByNameException; return true; } virtual bool Get(int index, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { got_get_byindex_.yes(); exception = kGetByIndexException; return true; } virtual bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { got_set_byname_.yes(); exception = kSetByNameException; return true; } virtual bool Set(int index, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { got_set_byindex_.yes(); exception = kSetByIndexException; return true; } TrackCallback got_get_byname_; TrackCallback got_get_byindex_; TrackCallback got_set_byname_; TrackCallback got_set_byindex_; IMPLEMENT_REFCOUNTING(Interceptor); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Exception> exception; Interceptor* interceptor = new Interceptor; CefRefPtr<CefV8Interceptor> interceptorPtr(interceptor); CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(nullptr, interceptor); EXPECT_TRUE(object.get()); EXPECT_FALSE(object->SetValue(kName, CefV8Value::CreateInt(1), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_TRUE(object->HasException()); EXPECT_TRUE(interceptor->got_set_byname_); exception = object->GetException(); EXPECT_TRUE(exception.get()); EXPECT_STREQ(kSetByNameExceptionMsg, exception->GetMessage().ToString().c_str()); EXPECT_TRUE(object->ClearException()); EXPECT_FALSE(object->HasException()); CefRefPtr<CefV8Value> val1 = object->GetValue(kName); EXPECT_FALSE(val1.get()); EXPECT_TRUE(object->HasException()); EXPECT_TRUE(interceptor->got_get_byname_); exception = object->GetException(); EXPECT_TRUE(exception.get()); EXPECT_STREQ(kGetByNameExceptionMsg, exception->GetMessage().ToString().c_str()); EXPECT_TRUE(object->ClearException()); EXPECT_FALSE(object->HasException()); EXPECT_FALSE(object->SetValue(kIndex, CefV8Value::CreateInt(1))); EXPECT_TRUE(object->HasException()); EXPECT_TRUE(interceptor->got_set_byindex_); exception = object->GetException(); EXPECT_TRUE(exception.get()); EXPECT_STREQ(kSetByIndexExceptionMsg, exception->GetMessage().ToString().c_str()); EXPECT_TRUE(object->ClearException()); EXPECT_FALSE(object->HasException()); CefRefPtr<CefV8Value> val2 = object->GetValue(kIndex); EXPECT_FALSE(val2.get()); EXPECT_TRUE(object->HasException()); EXPECT_TRUE(interceptor->got_get_byindex_); exception = object->GetException(); EXPECT_TRUE(exception.get()); EXPECT_STREQ(kGetByIndexExceptionMsg, exception->GetMessage().ToString().c_str()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectInterceptorAndAccessorTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kInterceptorName = "val1"; static const char* kAccessorName = "val2"; static const int kInterceptorValue = 20; static const int kAccessorValue = 30; class Interceptor : public CefV8Interceptor { public: Interceptor() {} virtual bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { EXPECT_FALSE(retval.get()); got_get_byname_.yes(); if (name.ToString() == kInterceptorName) { retval = CefV8Value::CreateInt(kInterceptorValue); } return true; } virtual bool Get(int index, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { got_get_byindex_.yes(); return true; } virtual bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { got_set_byname_.yes(); return true; } virtual bool Set(int index, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { got_set_byindex_.yes(); return true; } TrackCallback got_get_byname_; TrackCallback got_get_byindex_; TrackCallback got_set_byname_; TrackCallback got_set_byindex_; IMPLEMENT_REFCOUNTING(Interceptor); }; class Accessor : public CefV8Accessor { public: Accessor() {} virtual bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { got_get_.yes(); retval = CefV8Value::CreateInt(kAccessorValue); return true; } virtual bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { got_set_.yes(); return true; } TrackCallback got_get_; TrackCallback got_set_; IMPLEMENT_REFCOUNTING(Accessor); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Interceptor* interceptor = new Interceptor; CefRefPtr<CefV8Interceptor> interceptorPtr(interceptor); Accessor* accessor = new Accessor; CefRefPtr<CefV8Accessor> accessorPtr(accessor); CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(accessor, interceptor); EXPECT_TRUE(object.get()); // We register both names for accessor. EXPECT_TRUE(object->SetValue(kAccessorName, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(object->SetValue(kInterceptorName, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(object->SetValue(kAccessorName, CefV8Value::CreateInt(kAccessorValue), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(accessor->got_set_); accessor->got_set_.reset(); EXPECT_TRUE(interceptor->got_set_byname_); interceptor->got_set_byname_.reset(); EXPECT_TRUE(object->SetValue(kInterceptorName, CefV8Value::CreateInt(kInterceptorValue), V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_FALSE(object->HasException()); EXPECT_TRUE(accessor->got_set_); accessor->got_set_.reset(); EXPECT_TRUE(interceptor->got_set_byname_); interceptor->got_set_byname_.reset(); // When interceptor returns nothing, accessor's getter is called. CefRefPtr<CefV8Value> val1 = object->GetValue(kAccessorName); EXPECT_TRUE(val1.get()); EXPECT_TRUE(interceptor->got_get_byname_); interceptor->got_get_byname_.reset(); EXPECT_TRUE(accessor->got_get_); accessor->got_get_.reset(); EXPECT_EQ(kAccessorValue, val1->GetIntValue()); // When interceptor returns value, accessor's getter is not called. CefRefPtr<CefV8Value> val2 = object->GetValue(kInterceptorName); EXPECT_TRUE(val2.get()); EXPECT_TRUE(interceptor->got_get_byname_); EXPECT_FALSE(accessor->got_get_); EXPECT_EQ(kInterceptorValue, val2->GetIntValue()); EXPECT_FALSE(interceptor->got_get_byindex_); EXPECT_FALSE(interceptor->got_set_byindex_); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectValueTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "test_arg"; static const int kVal1 = 13; static const int kVal2 = 65; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); object->SetValue(kName, CefV8Value::CreateInt(kVal1), V8_PROPERTY_ATTRIBUTE_NONE); std::stringstream test; test << "if (window." << kName << " != " << kVal1 << ") throw 'Fail';\n" << "window." << kName << " = " << kVal2 << ";"; CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(context->Eval(test.str(), CefString(), 0, retval, exception)); if (exception.get()) ADD_FAILURE() << exception->GetMessage().c_str(); CefRefPtr<CefV8Value> newval = object->GetValue(kName); EXPECT_TRUE(newval.get()); EXPECT_TRUE(newval->IsInt()); EXPECT_EQ(kVal2, newval->GetIntValue()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectValueReadOnlyTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "test_arg"; static const int kVal1 = 13; static const int kVal2 = 65; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); object->SetValue(kName, CefV8Value::CreateInt(kVal1), V8_PROPERTY_ATTRIBUTE_READONLY); std::stringstream test; test << "if (window." << kName << " != " << kVal1 << ") throw 'Fail';\n" << "window." << kName << " = " << kVal2 << ";"; CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(context->Eval(test.str(), CefString(), 0, retval, exception)); if (exception.get()) ADD_FAILURE() << exception->GetMessage().c_str(); CefRefPtr<CefV8Value> newval = object->GetValue(kName); EXPECT_TRUE(newval.get()); EXPECT_TRUE(newval->IsInt()); EXPECT_EQ(kVal1, newval->GetIntValue()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectValueEnumTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kObjName = "test_obj"; static const char* kArgName = "test_arg"; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); CefRefPtr<CefV8Value> obj1 = CefV8Value::CreateObject(nullptr, nullptr); object->SetValue(kObjName, obj1, V8_PROPERTY_ATTRIBUTE_NONE); obj1->SetValue(kArgName, CefV8Value::CreateInt(0), V8_PROPERTY_ATTRIBUTE_NONE); std::stringstream test; test << "for (var i in window." << kObjName << ") {\n" "window." << kObjName << "[i]++;\n" "}"; CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(context->Eval(test.str(), CefString(), 0, retval, exception)); if (exception.get()) ADD_FAILURE() << exception->GetMessage().c_str(); CefRefPtr<CefV8Value> newval = obj1->GetValue(kArgName); EXPECT_TRUE(newval.get()); EXPECT_TRUE(newval->IsInt()); EXPECT_EQ(1, newval->GetIntValue()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectValueDontEnumTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kObjName = "test_obj"; static const char* kArgName = "test_arg"; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); CefRefPtr<CefV8Value> obj1 = CefV8Value::CreateObject(nullptr, nullptr); object->SetValue(kObjName, obj1, V8_PROPERTY_ATTRIBUTE_NONE); obj1->SetValue(kArgName, CefV8Value::CreateInt(0), V8_PROPERTY_ATTRIBUTE_DONTENUM); std::stringstream test; test << "for (var i in window." << kObjName << ") {\n" "window." << kObjName << "[i]++;\n" "}"; CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(context->Eval(test.str(), CefString(), 0, retval, exception)); if (exception.get()) ADD_FAILURE() << exception->GetMessage().c_str(); CefRefPtr<CefV8Value> newval = obj1->GetValue(kArgName); EXPECT_TRUE(newval.get()); EXPECT_TRUE(newval->IsInt()); EXPECT_EQ(0, newval->GetIntValue()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectValueDeleteTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "test_arg"; static const int kVal1 = 13; static const int kVal2 = 65; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); object->SetValue(kName, CefV8Value::CreateInt(kVal1), V8_PROPERTY_ATTRIBUTE_NONE); std::stringstream test; test << "if (window." << kName << " != " << kVal1 << ") throw 'Fail';\n" << "window." << kName << " = " << kVal2 << ";\n" "delete window." << kName << ";"; CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(context->Eval(test.str(), CefString(), 0, retval, exception)); if (exception.get()) ADD_FAILURE() << exception->GetMessage().c_str(); CefRefPtr<CefV8Value> newval = object->GetValue(kName); EXPECT_TRUE(newval.get()); EXPECT_TRUE(newval->IsUndefined()); EXPECT_FALSE(newval->IsInt()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectValueDontDeleteTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = "test_arg"; static const int kVal1 = 13; static const int kVal2 = 65; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); object->SetValue(kName, CefV8Value::CreateInt(kVal1), V8_PROPERTY_ATTRIBUTE_DONTDELETE); std::stringstream test; test << "if (window." << kName << " != " << kVal1 << ") throw 'Fail';\n" << "window." << kName << " = " << kVal2 << ";\n" "delete window." << kName << ";"; CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(context->Eval(test.str(), CefString(), 0, retval, exception)); if (exception.get()) ADD_FAILURE() << exception->GetMessage().c_str(); CefRefPtr<CefV8Value> newval = object->GetValue(kName); EXPECT_TRUE(newval.get()); EXPECT_TRUE(newval->IsInt()); EXPECT_EQ(kVal2, newval->GetIntValue()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunObjectValueEmptyKeyTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kName = ""; static const int kVal = 13; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); EXPECT_FALSE(object->HasValue(kName)); object->SetValue(kName, CefV8Value::CreateInt(kVal), V8_PROPERTY_ATTRIBUTE_NONE); EXPECT_TRUE(object->HasValue(kName)); CefRefPtr<CefV8Value> newval = object->GetValue(kName); EXPECT_TRUE(newval.get()); EXPECT_TRUE(newval->IsInt()); EXPECT_EQ(kVal, newval->GetIntValue()); EXPECT_TRUE(object->DeleteValue(kName)); EXPECT_FALSE(object->HasValue(kName)); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunFunctionCreateTest() { CefRefPtr<CefV8Context> context = GetContext(); class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { return false; } IMPLEMENT_REFCOUNTING(Handler); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> value = CefV8Value::CreateFunction("f", new Handler); // Exit the V8 context. EXPECT_TRUE(context->Exit()); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsFunction()); EXPECT_TRUE(value->IsObject()); EXPECT_FALSE(value->IsUndefined()); EXPECT_FALSE(value->IsArray()); EXPECT_FALSE(value->IsBool()); EXPECT_FALSE(value->IsDate()); EXPECT_FALSE(value->IsDouble()); EXPECT_FALSE(value->IsInt()); EXPECT_FALSE(value->IsUInt()); EXPECT_FALSE(value->IsNull()); EXPECT_FALSE(value->IsString()); DestroyTest(); } void RunFunctionHandlerTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kFuncName = "myfunc"; static const int kVal1 = 32; static const int kVal2 = 41; static const int kRetVal = 8; class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { EXPECT_STREQ(kFuncName, name.ToString().c_str()); EXPECT_TRUE(object->IsSame(object_)); EXPECT_EQ((size_t)2, arguments.size()); EXPECT_TRUE(arguments[0]->IsInt()); EXPECT_EQ(kVal1, arguments[0]->GetIntValue()); EXPECT_TRUE(arguments[1]->IsInt()); EXPECT_EQ(kVal2, arguments[1]->GetIntValue()); EXPECT_TRUE(exception.empty()); retval = CefV8Value::CreateInt(kRetVal); EXPECT_TRUE(retval.get()); EXPECT_EQ(kRetVal, retval->GetIntValue()); got_execute_.yes(); return true; } CefRefPtr<CefV8Value> object_; TrackCallback got_execute_; IMPLEMENT_REFCOUNTING(Handler); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction(kFuncName, handler); EXPECT_TRUE(func.get()); CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(nullptr, nullptr); EXPECT_TRUE(obj.get()); handler->object_ = obj; CefV8ValueList args; args.push_back(CefV8Value::CreateInt(kVal1)); args.push_back(CefV8Value::CreateInt(kVal2)); CefRefPtr<CefV8Value> retval = func->ExecuteFunction(obj, args); EXPECT_TRUE(handler->got_execute_); EXPECT_TRUE(retval.get()); EXPECT_FALSE(func->HasException()); EXPECT_TRUE(retval->IsInt()); EXPECT_EQ(kRetVal, retval->GetIntValue()); handler->object_ = nullptr; // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunFunctionHandlerExceptionTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kException = "My error"; static const char* kExceptionMsg = "Uncaught Error: My error"; class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { exception = kException; got_execute_.yes(); return true; } TrackCallback got_execute_; IMPLEMENT_REFCOUNTING(Handler); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("myfunc", handler); EXPECT_TRUE(func.get()); CefV8ValueList args; CefRefPtr<CefV8Value> retval = func->ExecuteFunction(nullptr, args); EXPECT_TRUE(handler->got_execute_); EXPECT_FALSE(retval.get()); EXPECT_TRUE(func->HasException()); CefRefPtr<CefV8Exception> exception = func->GetException(); EXPECT_TRUE(exception.get()); EXPECT_STREQ(kExceptionMsg, exception->GetMessage().ToString().c_str()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunFunctionHandlerFailTest() { CefRefPtr<CefV8Context> context = GetContext(); class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { got_execute_.yes(); return false; } TrackCallback got_execute_; IMPLEMENT_REFCOUNTING(Handler); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("myfunc", handler); EXPECT_TRUE(func.get()); CefV8ValueList args; CefRefPtr<CefV8Value> retval = func->ExecuteFunction(nullptr, args); EXPECT_TRUE(handler->got_execute_); EXPECT_TRUE(retval.get()); EXPECT_FALSE(func->HasException()); EXPECT_TRUE(retval->IsUndefined()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunFunctionHandlerNoObjectTest() { CefRefPtr<CefV8Context> context = GetContext(); class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { EXPECT_TRUE(object.get()); CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); EXPECT_TRUE(context.get()); CefRefPtr<CefV8Value> global = context->GetGlobal(); EXPECT_TRUE(global.get()); EXPECT_TRUE(global->IsSame(object)); got_execute_.yes(); return true; } TrackCallback got_execute_; IMPLEMENT_REFCOUNTING(Handler); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("myfunc", handler); EXPECT_TRUE(func.get()); CefV8ValueList args; CefRefPtr<CefV8Value> retval = func->ExecuteFunction(nullptr, args); EXPECT_TRUE(handler->got_execute_); EXPECT_TRUE(retval.get()); EXPECT_FALSE(func->HasException()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunFunctionHandlerWithContextTest() { CefRefPtr<CefV8Context> context = GetContext(); class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); EXPECT_TRUE(context.get()); EXPECT_TRUE(context->IsSame(context_)); got_execute_.yes(); return true; } CefRefPtr<CefV8Context> context_; TrackCallback got_execute_; IMPLEMENT_REFCOUNTING(Handler); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); handler->context_ = context; CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("myfunc", handler); EXPECT_TRUE(func.get()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); CefV8ValueList args; CefRefPtr<CefV8Value> retval = func->ExecuteFunctionWithContext(context, nullptr, args); EXPECT_TRUE(handler->got_execute_); EXPECT_TRUE(retval.get()); EXPECT_FALSE(func->HasException()); handler->context_ = nullptr; DestroyTest(); } void RunFunctionHandlerEmptyStringTest() { CefRefPtr<CefV8Context> context = GetContext(); class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { EXPECT_TRUE(object.get()); CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); EXPECT_TRUE(context.get()); CefRefPtr<CefV8Value> global = context->GetGlobal(); EXPECT_TRUE(global.get()); EXPECT_TRUE(global->IsSame(object)); EXPECT_EQ((size_t)1, arguments.size()); EXPECT_TRUE(arguments[0]->IsString()); EXPECT_STREQ("", arguments[0]->GetStringValue().ToString().c_str()); retval = CefV8Value::CreateString(CefString()); got_execute_.yes(); return true; } TrackCallback got_execute_; IMPLEMENT_REFCOUNTING(Handler); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("myfunc", handler); EXPECT_TRUE(func.get()); CefV8ValueList args; args.push_back(CefV8Value::CreateString(CefString())); CefRefPtr<CefV8Value> retval = func->ExecuteFunction(nullptr, args); EXPECT_TRUE(handler->got_execute_); EXPECT_TRUE(retval.get()); EXPECT_FALSE(func->HasException()); EXPECT_TRUE(retval->IsString()); EXPECT_STREQ("", retval->GetStringValue().ToString().c_str()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunContextEvalTest() { CefRefPtr<CefV8Context> context = GetContext(); CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(context->Eval("1+2", CefString(), 0, retval, exception)); EXPECT_TRUE(retval.get()); EXPECT_TRUE(retval->IsInt()); EXPECT_EQ(3, retval->GetIntValue()); EXPECT_FALSE(exception.get()); DestroyTest(); } void RunContextEvalExceptionTest() { CefRefPtr<CefV8Context> context = GetContext(); CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_FALSE( context->Eval("\n\n\n1+foo", CefString(), 0, retval, exception)); EXPECT_FALSE(retval.get()); EXPECT_TRUE(exception.get()); EXPECT_EQ(4, exception->GetLineNumber()); DestroyTest(); } void RunContextEvalCspBypassUnsafeEval() { CefRefPtr<CefV8Context> context = GetContext(); CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; bool success = context->Eval("(document.getElementById('result').innerHTML)", CefString(), 0, retval, exception); if (exception.get()) { ADD_FAILURE() << exception->GetMessage().c_str(); EXPECT_FALSE(success); } EXPECT_TRUE(success); EXPECT_TRUE(retval.get()); if (retval.get()) { EXPECT_TRUE(retval->IsString()); EXPECT_EQ(CefString("CSP_BYPASSED"), retval->GetStringValue()); } DestroyTest(); } void RunContextEvalCspBypassSandbox() { CefRefPtr<CefV8Context> context = GetContext(); CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; bool success = context->Eval("(document.getElementById('result').innerHTML)", CefString(), 0, retval, exception); if (exception.get()) { ADD_FAILURE() << exception->GetMessage().c_str(); EXPECT_FALSE(success); } EXPECT_TRUE(success); EXPECT_TRUE(retval.get()); if (retval.get()) { EXPECT_TRUE(retval->IsString()); EXPECT_EQ(CefString("CSP_BYPASSED"), retval->GetStringValue()); } DestroyTest(); } void RunContextEnteredTest() { CefRefPtr<CefV8Context> context = GetContext(); CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; // Test value defined in OnContextCreated EXPECT_TRUE(context->Eval( "document.getElementById('f').contentWindow.v8_context_entered_test()", CefString(), 0, retval, exception)); if (exception.get()) ADD_FAILURE() << exception->GetMessage().c_str(); EXPECT_TRUE(retval.get()); EXPECT_TRUE(retval->IsInt()); EXPECT_EQ(21, retval->GetIntValue()); DestroyTest(); } void RunBindingTest() { CefRefPtr<CefV8Context> context = GetContext(); // Enter the V8 context. EXPECT_TRUE(context->Enter()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); // Test value defined in OnContextCreated CefRefPtr<CefV8Value> value = object->GetValue("v8_binding_test"); EXPECT_TRUE(value.get()); EXPECT_TRUE(value->IsInt()); EXPECT_EQ(12, value->GetIntValue()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunStackTraceTest() { CefRefPtr<CefV8Context> context = GetContext(); static const char* kFuncName = "myfunc"; class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { EXPECT_STREQ(kFuncName, name.ToString().c_str()); stack_trace_ = CefV8StackTrace::GetCurrent(10); retval = CefV8Value::CreateInt(3); got_execute_.yes(); return true; } TrackCallback got_execute_; CefRefPtr<CefV8StackTrace> stack_trace_; IMPLEMENT_REFCOUNTING(Handler); }; // Enter the V8 context. EXPECT_TRUE(context->Enter()); Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction(kFuncName, handler); EXPECT_TRUE(func.get()); CefRefPtr<CefV8Value> obj = context->GetGlobal(); EXPECT_TRUE(obj.get()); obj->SetValue(kFuncName, func, V8_PROPERTY_ATTRIBUTE_NONE); CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE( context->Eval("function jsfunc() { return window.myfunc(); }\n" "jsfunc();", CefString(), 0, retval, exception)); EXPECT_TRUE(retval.get()); EXPECT_TRUE(retval->IsInt()); EXPECT_EQ(3, retval->GetIntValue()); EXPECT_FALSE(exception.get()); EXPECT_TRUE(handler->stack_trace_.get()); EXPECT_EQ(2, handler->stack_trace_->GetFrameCount()); CefRefPtr<CefV8StackFrame> frame; frame = handler->stack_trace_->GetFrame(0); EXPECT_TRUE(frame->GetScriptName().empty()); EXPECT_TRUE(frame->GetScriptNameOrSourceURL().empty()); EXPECT_STREQ("jsfunc", frame->GetFunctionName().ToString().c_str()); EXPECT_EQ(1, frame->GetLineNumber()); EXPECT_EQ(35, frame->GetColumn()); EXPECT_TRUE(frame.get()); EXPECT_FALSE(frame->IsEval()); EXPECT_FALSE(frame->IsConstructor()); frame = handler->stack_trace_->GetFrame(1); EXPECT_TRUE(frame->GetScriptName().empty()); EXPECT_TRUE(frame->GetScriptNameOrSourceURL().empty()); EXPECT_TRUE(frame->GetFunctionName().empty()); EXPECT_EQ(2, frame->GetLineNumber()); EXPECT_EQ(1, frame->GetColumn()); EXPECT_TRUE(frame.get()); EXPECT_FALSE(frame->IsEval()); EXPECT_FALSE(frame->IsConstructor()); // Exit the V8 context. EXPECT_TRUE(context->Exit()); DestroyTest(); } void RunOnUncaughtExceptionTest() { test_context_ = browser_->GetMainFrame()->GetV8Context(); browser_->GetMainFrame()->ExecuteJavaScript( "window.setTimeout(test, 0)", browser_->GetMainFrame()->GetURL(), 0); } // Test execution of a native function when the extension is loaded. void RunExtensionTest() { std::string code = "native function v8_extension_test();" "v8_extension_test();"; class Handler : public CefV8Handler { public: Handler(TrackCallback* callback) : callback_(callback) {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { EXPECT_STREQ("v8_extension_test", name.ToString().c_str()); callback_->yes(); return true; } TrackCallback* callback_; IMPLEMENT_REFCOUNTING(Handler); }; CefRegisterExtension("v8/test-extension", code, new Handler(&startup_test_success_)); } void OnBrowserCreated(CefRefPtr<ClientAppRenderer> app, CefRefPtr<CefBrowser> browser, CefRefPtr<CefDictionaryValue> extra_info) override { if (extra_info->HasKey(kV8TestCmdKey)) { test_mode_ = static_cast<V8TestMode>(extra_info->GetInt(kV8TestCmdKey)); } if (test_mode_ > V8TEST_NONE) RunStartupTest(); if (test_mode_ == V8TEST_CONTEXT_EVAL_CSP_BYPASS_UNSAFE_EVAL || test_mode_ == V8TEST_CONTEXT_EVAL_CSP_BYPASS_SANDBOX) { browser_ = browser; } } CefRefPtr<CefLoadHandler> GetLoadHandler( CefRefPtr<ClientAppRenderer> app) override { if (test_mode_ == V8TEST_NONE) return nullptr; return this; } void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) override { if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS && browser->IsPopup()) { DevToolsLoadHook(browser); } } void OnContextCreated(CefRefPtr<ClientAppRenderer> app, CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) override { if (test_mode_ == V8TEST_NONE) return; if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS) { if (!browser->IsPopup()) { app_ = app; browser_ = browser; test_context_ = context; } return; } app_ = app; browser_ = browser; std::string url = frame->GetURL(); if (url == kV8ContextChildTestUrl) { // For V8TEST_CONTEXT_ENTERED class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { // context for the sub-frame CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); EXPECT_TRUE(context.get()); // entered context should be the same as the main frame context CefRefPtr<CefV8Context> entered = CefV8Context::GetEnteredContext(); EXPECT_TRUE(entered.get()); EXPECT_TRUE(entered->IsSame(context_)); context_ = nullptr; retval = CefV8Value::CreateInt(21); return true; } CefRefPtr<CefV8Context> context_; IMPLEMENT_REFCOUNTING(Handler); }; Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); // main frame context handler->context_ = GetContext(); // Function that will be called from the parent frame context. CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("v8_context_entered_test", handler); EXPECT_TRUE(func.get()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->SetValue("v8_context_entered_test", func, V8_PROPERTY_ATTRIBUTE_NONE)); } else if (url == kV8ContextParentTestUrl) { // For V8TEST_CONTEXT_ENTERED. Do nothing. return; } else if (url == kV8BindingTestUrl) { // For V8TEST_BINDING CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->SetValue("v8_binding_test", CefV8Value::CreateInt(12), V8_PROPERTY_ATTRIBUTE_NONE)); } else if (url == kV8HandlerCallOnReleasedContextUrl) { // For V8TEST_HANDLER_CALL_ON_RELEASED_CONTEXT class Handler : public CefV8Handler { public: Handler(CefRefPtr<V8RendererTest> renderer_test) : renderer_test_(renderer_test) {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { if (name == "notify_test_done") { CefPostDelayedTask( TID_RENDERER, base::Bind(&V8RendererTest::DestroyTest, renderer_test_.get()), 1000); return true; } return false; } private: CefRefPtr<V8RendererTest> renderer_test_; IMPLEMENT_REFCOUNTING(Handler); }; Handler* handler = new Handler(this); CefRefPtr<CefV8Handler> handlerPtr(handler); // Function that will be called from the parent frame context. CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("notify_test_done", handler); EXPECT_TRUE(func.get()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->SetValue("notify_test_done", func, V8_PROPERTY_ATTRIBUTE_NONE)); } else if (url == kV8HandlerCallOnReleasedContextChildUrl) { // For V8TEST_HANDLER_CALL_ON_RELEASED_CONTEXT class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { if (name == "v8_context_is_alive") { retval = CefV8Value::CreateBool(true); return true; } return false; } IMPLEMENT_REFCOUNTING(Handler); }; Handler* handler = new Handler; CefRefPtr<CefV8Handler> handlerPtr(handler); // Function that will be called from the parent frame context. CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("v8_context_is_alive", handler); EXPECT_TRUE(func.get()); CefRefPtr<CefV8Value> object = context->GetGlobal(); EXPECT_TRUE(object.get()); EXPECT_TRUE(object->SetValue("v8_context_is_alive", func, V8_PROPERTY_ATTRIBUTE_NONE)); } } void OnUncaughtException(CefRefPtr<ClientAppRenderer> app, CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Exception> exception, CefRefPtr<CefV8StackTrace> stackTrace) override { if (test_mode_ == V8TEST_NONE) return; if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION || test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS) { EXPECT_TRUE(test_context_->IsSame(context)); EXPECT_STREQ("Uncaught ReferenceError: asd is not defined", exception->GetMessage().ToString().c_str()); std::ostringstream stackFormatted; for (int i = 0; i < stackTrace->GetFrameCount(); ++i) { stackFormatted << "at " << stackTrace->GetFrame(i)->GetFunctionName().ToString() << "() in " << stackTrace->GetFrame(i)->GetScriptName().ToString() << " on line " << stackTrace->GetFrame(i)->GetLineNumber() << "\n"; } const char* stackFormattedShouldBe = "at test2() in http://tests/V8Test.OnUncaughtException on line 3\n" "at test() in http://tests/V8Test.OnUncaughtException on line 2\n"; EXPECT_STREQ(stackFormattedShouldBe, stackFormatted.str().c_str()); DestroyTest(); } } bool OnProcessMessageReceived(CefRefPtr<ClientAppRenderer> app, CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefProcessId source_process, CefRefPtr<CefProcessMessage> message) override { if (test_mode_ == V8TEST_NONE) return false; const std::string& message_name = message->GetName(); if (message_name == kV8RunTestMsg) { // Run the test asynchronously. CefPostTask(TID_RENDERER, base::Bind(&V8RendererTest::RunTest, this)); return true; } return false; } void DevToolsLoadHook(CefRefPtr<CefBrowser> browser) { EXPECT_TRUE(browser->IsPopup()); CefRefPtr<CefFrame> frame = browser->GetMainFrame(); CefRefPtr<CefV8Context> context = frame->GetV8Context(); static const char* kFuncName = "DevToolsLoaded"; class Handler : public CefV8Handler { public: Handler() {} bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { EXPECT_STREQ(kFuncName, name.ToString().c_str()); if (name == kFuncName) { EXPECT_TRUE(exception.empty()); retval = CefV8Value::CreateNull(); EXPECT_TRUE(retval.get()); renderer_test_->DevToolsLoaded(browser_); return true; } return false; } CefRefPtr<V8RendererTest> renderer_test_; CefRefPtr<CefBrowser> browser_; IMPLEMENT_REFCOUNTING(Handler); }; EXPECT_TRUE(context->Enter()); Handler* handler = new Handler; handler->renderer_test_ = this; handler->browser_ = browser; CefRefPtr<CefV8Handler> handlerPtr(handler); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction(kFuncName, handler); EXPECT_TRUE(func.get()); EXPECT_TRUE(context->GetGlobal()->SetValue(kFuncName, func, V8_PROPERTY_ATTRIBUTE_NONE)); EXPECT_TRUE(context->Exit()); // Dismiss the DevTools window after 500ms. It would be better to hook the // DevTools JS to receive notification of when loading is complete but that // is no longer possible. CefPostDelayedTask( TID_RENDERER, base::Bind(&CefFrame::ExecuteJavaScript, frame.get(), "window.DevToolsLoaded()", frame->GetURL(), 0), 500); } void DevToolsLoaded(CefRefPtr<CefBrowser> browser) { EXPECT_TRUE(browser->IsPopup()); // |browser_| will be nullptr if the DevTools window is opened in a separate // render process. const int other_browser_id = (browser_.get() ? browser_->GetIdentifier() : -1); EXPECT_NE(browser->GetIdentifier(), other_browser_id); // Close the DevTools window. This will trigger OnBeforeClose in the browser // process. CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; EXPECT_TRUE(browser->GetMainFrame()->GetV8Context()->Eval( "window.close()", CefString(), 0, retval, exception)); } protected: // Return from the test. void DestroyTest() { EXPECT_TRUE(CefCurrentlyOn(TID_RENDERER)); // Check if the test has failed. bool result = !TestFailed(); // Return the result to the browser process. CefRefPtr<CefProcessMessage> return_msg = CefProcessMessage::Create(kV8TestMsg); EXPECT_TRUE(return_msg->GetArgumentList()->SetBool(0, result)); browser_->GetMainFrame()->SendProcessMessage(PID_BROWSER, return_msg); app_ = nullptr; browser_ = nullptr; test_context_ = nullptr; test_object_ = nullptr; } // Return the V8 context. CefRefPtr<CefV8Context> GetContext() { CefRefPtr<CefV8Context> context = browser_->GetMainFrame()->GetV8Context(); EXPECT_TRUE(context.get()); return context; } CefRefPtr<ClientAppRenderer> app_; CefRefPtr<CefBrowser> browser_; V8TestMode test_mode_; CefRefPtr<CefV8Context> test_context_; CefRefPtr<CefV8Value> test_object_; // Used by startup tests to indicate success. TrackCallback startup_test_success_; IMPLEMENT_REFCOUNTING(V8RendererTest); }; // Browser side. class V8TestHandler : public TestHandler { public: V8TestHandler(V8TestMode test_mode, const char* test_url) : test_mode_(test_mode), test_url_(test_url) {} void RunTest() override { CefRefPtr<CefDictionaryValue> extra_info = CefDictionaryValue::Create(); extra_info->SetInt(kV8TestCmdKey, test_mode_); // Nested script tag forces creation of the V8 context. if (test_mode_ == V8TEST_CONTEXT_EVAL_CSP_BYPASS_UNSAFE_EVAL || test_mode_ == V8TEST_CONTEXT_EVAL_CSP_BYPASS_SANDBOX) { std::string url; ResourceContent::HeaderMap headers; if (test_mode_ == V8TEST_CONTEXT_EVAL_CSP_BYPASS_UNSAFE_EVAL) { url = kV8ContextEvalCspBypassUnsafeEval; headers.insert(std::pair<std::string, std::string>( "Content-Security-Policy", "script-src 'self'")); } else if (test_mode_ == V8TEST_CONTEXT_EVAL_CSP_BYPASS_SANDBOX) { url = kV8ContextEvalCspBypassSandbox; headers.insert(std::pair<std::string, std::string>( "Content-Security-Policy", "sandbox")); } else { NOTREACHED(); } AddResource(url, "<html><body>" + url + "<p id='result' style='display:none'>CSP_BYPASSED</p>" "</body></html>", "text/html", headers); CreateBrowser(test_url_, nullptr, extra_info); } else if (test_mode_ == V8TEST_CONTEXT_ENTERED) { AddResource(kV8ContextParentTestUrl, "<html><body>" "<script>var i = 0;</script><iframe src=\"" + std::string(kV8ContextChildTestUrl) + "\" id=\"f\"></iframe></body>" "</html>", "text/html"); AddResource(kV8ContextChildTestUrl, "<html><body>" "<script>var i = 0;</script>CHILD</body></html>", "text/html"); CreateBrowser(kV8ContextParentTestUrl, nullptr, extra_info); } else if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION || test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS) { AddResource(kV8OnUncaughtExceptionTestUrl, "<html><body>" "<h1>OnUncaughtException</h1>" "<script>\n" "function test(){ test2(); }\n" "function test2(){ asd(); }\n" "</script>\n" "</body></html>\n", "text/html"); CreateBrowser(kV8OnUncaughtExceptionTestUrl, nullptr, extra_info); } else if (test_mode_ == V8TEST_HANDLER_CALL_ON_RELEASED_CONTEXT) { AddResource(kV8HandlerCallOnReleasedContextUrl, "<html><body onload='createFrame()'>" "(main)" "<script>" "function createFrame() {" " var el = document.createElement('iframe');" " el.id = 'child';" " el.src = '" + std::string(kV8HandlerCallOnReleasedContextChildUrl) + "';" " el.onload = function() {" " setTimeout(function() {" " try {" " el.contentWindow.removeMe();" " window.notify_test_done();" " } catch (e) { alert('Unit test error.\\n' + e); }" " }, 1000);" " };" " document.body.appendChild(el);" "}" "" "function removeFrame(id) {" " var el = document.getElementById(id);" " if (el) { el.parentElement.removeChild(el); }" " else { alert('Error in test. No element \"' + id + " "'\" found.'); }" "}" "</script>" "</body></html>", "text/html"); AddResource(kV8HandlerCallOnReleasedContextChildUrl, "<html><body>" "(child)" "<script>" "try {" " if (!window.v8_context_is_alive()) {" " throw 'v8_context_is_alive returns non-true value.';" " }" "} catch (e) {" " alert('Unit test error.\\n' + e);" "}" "" "function removeMe() {" " var w = window;" " w.parent.removeFrame('child');" " return w.v8_context_is_alive();" "}" "</script>" "</body></html>", "text/html"); CreateBrowser(kV8HandlerCallOnReleasedContextUrl, nullptr, extra_info); } else { EXPECT_TRUE(test_url_ != nullptr); AddResource(test_url_, "<html><body>" "<script>var i = 0;</script>TEST</body></html>", "text/html"); CreateBrowser(test_url_, nullptr, extra_info); } // Time out the test after a reasonable period of time. SetTestTimeout(); } void OnBeforeClose(CefRefPtr<CefBrowser> browser) override { if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS && browser->IsPopup()) { // Generate the uncaught exception in the main browser. Use a 200ms delay // because there's a bit of a lag between destroying the DevToolsAgent and // re-registering for uncaught exceptions. GetBrowser()->GetMainFrame()->ExecuteJavaScript( "window.setTimeout(test, 200);", GetBrowser()->GetMainFrame()->GetURL(), 0); } TestHandler::OnBeforeClose(browser); } void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) override { if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS) { if (!browser->IsPopup()) { // Create the DevTools window. CefWindowInfo windowInfo; CefBrowserSettings settings; #if defined(OS_WIN) windowInfo.SetAsPopup(browser->GetHost()->GetWindowHandle(), "DevTools"); #endif browser->GetHost()->ShowDevTools(windowInfo, this, settings, CefPoint()); } return; } const std::string& url = frame->GetURL(); if (url != kV8NavTestUrl && url != kV8ContextParentTestUrl && url.find("http://tests/") != std::string::npos) { // Run the test. CefRefPtr<CefProcessMessage> return_msg = CefProcessMessage::Create(kV8RunTestMsg); frame->SendProcessMessage(PID_RENDERER, return_msg); } } bool OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefProcessId source_process, CefRefPtr<CefProcessMessage> message) override { EXPECT_TRUE(browser.get()); EXPECT_TRUE(frame.get()); EXPECT_TRUE(frame->IsMain()); EXPECT_EQ(PID_RENDERER, source_process); EXPECT_TRUE(message.get()); EXPECT_TRUE(message->IsReadOnly()); const std::string& message_name = message->GetName(); EXPECT_STREQ(kV8TestMsg, message_name.c_str()); got_message_.yes(); if (message->GetArgumentList()->GetBool(0)) got_success_.yes(); // Test is complete. DestroyTest(); return true; } V8TestMode test_mode_; const char* test_url_; TrackCallback got_message_; TrackCallback got_success_; IMPLEMENT_REFCOUNTING(V8TestHandler); }; } // namespace // Entry point for creating V8 renderer test objects. // Called from client_app_delegates.cc. void CreateV8RendererTests(ClientAppRenderer::DelegateSet& delegates) { delegates.insert(new V8RendererTest); } // Helpers for defining V8 tests. #define V8_TEST_EX(name, test_mode, test_url) \ TEST(V8Test, name) { \ CefRefPtr<V8TestHandler> handler = new V8TestHandler(test_mode, test_url); \ handler->ExecuteTest(); \ EXPECT_TRUE(handler->got_message_); \ EXPECT_TRUE(handler->got_success_); \ ReleaseAndWaitForDestructor(handler); \ } #define V8_TEST(name, test_mode) V8_TEST_EX(name, test_mode, kV8TestUrl) // Define the tests. V8_TEST(NullCreate, V8TEST_NULL_CREATE) V8_TEST(BoolCreate, V8TEST_BOOL_CREATE) V8_TEST(IntCreate, V8TEST_INT_CREATE) V8_TEST(UIntCreate, V8TEST_UINT_CREATE) V8_TEST(DoubleCreate, V8TEST_DOUBLE_CREATE) V8_TEST(DateCreate, V8TEST_DATE_CREATE) V8_TEST(StringCreate, V8TEST_STRING_CREATE) V8_TEST(EmptyStringCreate, V8TEST_EMPTY_STRING_CREATE) V8_TEST(ArrayCreate, V8TEST_ARRAY_CREATE) V8_TEST(ArrayValue, V8TEST_ARRAY_VALUE) V8_TEST(ArrayBuffer, V8TEST_ARRAY_BUFFER) V8_TEST(ArrayBufferValue, V8TEST_ARRAY_BUFFER_VALUE) V8_TEST(ObjectCreate, V8TEST_OBJECT_CREATE) V8_TEST(ObjectUserData, V8TEST_OBJECT_USERDATA) V8_TEST(ObjectAccessor, V8TEST_OBJECT_ACCESSOR) V8_TEST(ObjectAccessorException, V8TEST_OBJECT_ACCESSOR_EXCEPTION) V8_TEST(ObjectAccessorFail, V8TEST_OBJECT_ACCESSOR_FAIL) V8_TEST(ObjectAccessorReadOnly, V8TEST_OBJECT_ACCESSOR_READONLY) V8_TEST(ObjectInterceptor, V8TEST_OBJECT_INTERCEPTOR) V8_TEST(ObjectInterceptorFail, V8TEST_OBJECT_INTERCEPTOR_FAIL) V8_TEST(ObjectInterceptorException, V8TEST_OBJECT_INTERCEPTOR_EXCEPTION) V8_TEST(ObjectInterceptorAndAccessor, V8TEST_OBJECT_INTERCEPTOR_AND_ACCESSOR) V8_TEST(ObjectValue, V8TEST_OBJECT_VALUE) V8_TEST(ObjectValueReadOnly, V8TEST_OBJECT_VALUE_READONLY) V8_TEST(ObjectValueEnum, V8TEST_OBJECT_VALUE_ENUM) V8_TEST(ObjectValueDontEnum, V8TEST_OBJECT_VALUE_DONTENUM) V8_TEST(ObjectValueDelete, V8TEST_OBJECT_VALUE_DELETE) V8_TEST(ObjectValueDontDelete, V8TEST_OBJECT_VALUE_DONTDELETE) V8_TEST(ObjectValueEmptyKey, V8TEST_OBJECT_VALUE_EMPTYKEY) V8_TEST(FunctionCreate, V8TEST_FUNCTION_CREATE) V8_TEST(FunctionHandler, V8TEST_FUNCTION_HANDLER) V8_TEST(FunctionHandlerException, V8TEST_FUNCTION_HANDLER_EXCEPTION) V8_TEST(FunctionHandlerFail, V8TEST_FUNCTION_HANDLER_FAIL) V8_TEST(FunctionHandlerNoObject, V8TEST_FUNCTION_HANDLER_NO_OBJECT) V8_TEST(FunctionHandlerWithContext, V8TEST_FUNCTION_HANDLER_WITH_CONTEXT) V8_TEST(FunctionHandlerEmptyString, V8TEST_FUNCTION_HANDLER_EMPTY_STRING) V8_TEST(ContextEval, V8TEST_CONTEXT_EVAL) V8_TEST(ContextEvalException, V8TEST_CONTEXT_EVAL_EXCEPTION) V8_TEST_EX(ContextEvalCspBypassUnsafeEval, V8TEST_CONTEXT_EVAL_CSP_BYPASS_UNSAFE_EVAL, kV8ContextEvalCspBypassUnsafeEval) V8_TEST_EX(ContextEvalCspBypassSandbox, V8TEST_CONTEXT_EVAL_CSP_BYPASS_SANDBOX, kV8ContextEvalCspBypassSandbox) V8_TEST_EX(ContextEntered, V8TEST_CONTEXT_ENTERED, nullptr) V8_TEST_EX(Binding, V8TEST_BINDING, kV8BindingTestUrl) V8_TEST(StackTrace, V8TEST_STACK_TRACE) V8_TEST(OnUncaughtException, V8TEST_ON_UNCAUGHT_EXCEPTION) V8_TEST(OnUncaughtExceptionDevTools, V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS) V8_TEST(Extension, V8TEST_EXTENSION) V8_TEST_EX(HandlerCallOnReleasedContext, V8TEST_HANDLER_CALL_ON_RELEASED_CONTEXT, kV8HandlerCallOnReleasedContextUrl)
32.501297
80
0.642287
[ "render", "object" ]
b4848b911fa202d4c62a8bd13499d622261cccff
3,942
hpp
C++
deps/src/boost_1_65_1/boost/tti/has_function.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
deps/src/boost_1_65_1/boost/tti/has_function.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
deps/src/boost_1_65_1/boost/tti/has_function.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// (C) Copyright Edward Diener 2012,2013 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #if !defined(BOOST_TTI_HAS_FUNCTION_HPP) #define BOOST_TTI_HAS_FUNCTION_HPP #include <boost/config.hpp> #include <boost/function_types/property_tags.hpp> #include <boost/mpl/vector.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/tti/detail/dfunction.hpp> #include <boost/tti/gen/has_function_gen.hpp> /* The succeeding comments in this file are in doxygen format. */ /** \file */ /// Expands to a metafunction which tests whether a member function or a static member function with a particular name and signature exists. /** trait = the name of the metafunction within the tti namespace. name = the name of the inner member. generates a metafunction called "trait" where 'trait' is the macro parameter. template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_R,class BOOST_TTI_TP_FS,class BOOST_TTI_TP_TAG> struct trait { static const value = unspecified; typedef mpl::bool_<true-or-false> type; }; The metafunction types and return: BOOST_TTI_TP_T = the enclosing type in which to look for our 'name'. BOOST_TTI_TP_R = the return type of the function BOOST_TTI_TP_FS = (optional) the parameters of the function as a boost::mpl forward sequence if function parameters are not empty. BOOST_TTI_TP_TAG = (optional) a boost::function_types tag to apply to the function if the need for a tag exists. returns = 'value' is true if the 'name' exists, with the appropriate static member function type, otherwise 'value' is false. */ #define BOOST_TTI_TRAIT_HAS_FUNCTION(trait,name) \ BOOST_TTI_DETAIL_TRAIT_HAS_FUNCTION(trait,name) \ template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_R,class BOOST_TTI_TP_FS = boost::mpl::vector<>,class BOOST_TTI_TP_TAG = boost::function_types::null_tag> \ struct trait \ { \ typedef typename \ BOOST_PP_CAT(trait,_detail_hf)<BOOST_TTI_TP_T,BOOST_TTI_TP_R,BOOST_TTI_TP_FS,BOOST_TTI_TP_TAG>::type type; \ BOOST_STATIC_CONSTANT(bool,value=type::value); \ }; \ /**/ /// Expands to a metafunction which tests whether a member function or a static member function with a particular name and signature exists. /** name = the name of the inner member. generates a metafunction called "has_function_name" where 'name' is the macro parameter. template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_R,class BOOST_TTI_TP_FS,class BOOST_TTI_TP_TAG> struct trait { static const value = unspecified; typedef mpl::bool_<true-or-false> type; }; The metafunction types and return: BOOST_TTI_TP_T = the enclosing type in which to look for our 'name'. BOOST_TTI_TP_R = the return type of the function BOOST_TTI_TP_FS = (optional) the parameters of the function as a boost::mpl forward sequence if function parameters are not empty. BOOST_TTI_TP_TAG = (optional) a boost::function_types tag to apply to the function if the need for a tag exists. returns = 'value' is true if the 'name' exists, with the appropriate function type, otherwise 'value' is false. */ #define BOOST_TTI_HAS_FUNCTION(name) \ BOOST_TTI_TRAIT_HAS_FUNCTION \ ( \ BOOST_TTI_HAS_FUNCTION_GEN(name), \ name \ ) \ /**/ #endif // BOOST_TTI_HAS_FUNCTION_HPP
35.836364
157
0.652207
[ "vector" ]
b4860d2a4a7f5c72d31491d30f8599b6a7cabc1a
960
cpp
C++
src/states/NotImplementedState.cpp
sharkwouter/oceanpop
d8185bca479b0f72754d565254bd4a91ccf07f33
[ "MIT" ]
11
2022-03-09T11:23:23.000Z
2022-03-27T01:31:15.000Z
src/states/NotImplementedState.cpp
sharkwouter/oceanpop
d8185bca479b0f72754d565254bd4a91ccf07f33
[ "MIT" ]
16
2022-01-16T15:09:51.000Z
2022-03-10T13:28:22.000Z
src/states/NotImplementedState.cpp
sharkwouter/oceanpop
d8185bca479b0f72754d565254bd4a91ccf07f33
[ "MIT" ]
null
null
null
#include "NotImplementedState.hpp" NotImplementedState::NotImplementedState(SDL_Renderer * renderer, FontManager * fonts, SoundManager * sounds, OptionManager * options) : theme(renderer, options, Theme::MENU), screen_text(renderer, fonts, options, "Not Yet Implemented", "press the confirm button to continue") { this->renderer = renderer; this->fonts = fonts; this->sounds = sounds; this->options = options; } NotImplementedState::~NotImplementedState() { } void NotImplementedState::update() { } void NotImplementedState::handleEvents(std::vector<Event> events) { for(Event event: events) { if (event == Event::CONFIRM || event == Event::CANCEL || event == Event::MENU) { this->done = true; } } } void NotImplementedState::draw(SDL_Renderer *renderer) { this->theme.draw(renderer); screen_text.draw(renderer); } State NotImplementedState::getNextState() { return State::MENU; }
26.666667
136
0.688542
[ "vector" ]
b4868776d62ffea3c9cb0a982babc3f6e6c14fec
1,693
cpp
C++
tests/unit/agas/components/server/managed_refcnt_checker.cpp
ShmuelLevine/hpx
a1621a0cfa58a884b03bc8557d4f5ad896297f14
[ "BSL-1.0" ]
null
null
null
tests/unit/agas/components/server/managed_refcnt_checker.cpp
ShmuelLevine/hpx
a1621a0cfa58a884b03bc8557d4f5ad896297f14
[ "BSL-1.0" ]
1
2018-04-20T14:17:33.000Z
2018-04-20T14:17:33.000Z
tests/unit/agas/components/server/managed_refcnt_checker.cpp
victor-ludorum/hpx
d1db0def60687a662e4e25a909550f08eaf1a18a
[ "BSL-1.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2011 Bryce Adelstein-Lelbach // // 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 <hpx/hpx.hpp> #include <hpx/include/iostreams.hpp> #include <hpx/util/format.hpp> #include <cstdint> #include <sstream> #include <string> #include <tests/unit/agas/components/server/managed_refcnt_checker.hpp> namespace hpx { namespace test { namespace server { managed_refcnt_checker::~managed_refcnt_checker() { const std::uint32_t prefix_ = get_locality_id(); const naming::gid_type this_ = get_base_gid(); std::ostringstream strm; if (!references_.empty()) { hpx::util::format_to(strm, "[%1%/%2%]: held references\n", prefix_, this_); for (naming::id_type const& ref : references_) { strm << " " << ref << " " << naming::get_management_type_name(ref.get_management_type()) << "\n"; } // Flush garbage collection. references_.clear(); agas::garbage_collect(); } if (naming::invalid_id != target_) { hpx::util::format_to(strm, "[%1%/%2%]: destroying object\n", prefix_, this_); hpx::util::format_to(strm, "[%1%/%2%]: triggering flag %3%\n", prefix_, this_, target_); hpx::trigger_lco_event(target_); } std::string const str = strm.str(); if (!str.empty()) cout << str << flush; } }}}
26.453125
80
0.546958
[ "object" ]
b48b86be58c27723ca2f1655592216b23005f769
7,205
cc
C++
tools/openvr_driver/openvr_driver.cc
tiiuae/libsurvive
b966a6c0942889f7a4d6a34dd21488bb9a06ffc6
[ "MIT" ]
null
null
null
tools/openvr_driver/openvr_driver.cc
tiiuae/libsurvive
b966a6c0942889f7a4d6a34dd21488bb9a06ffc6
[ "MIT" ]
null
null
null
tools/openvr_driver/openvr_driver.cc
tiiuae/libsurvive
b966a6c0942889f7a4d6a34dd21488bb9a06ffc6
[ "MIT" ]
null
null
null
#include <openvr/openvr_driver.h> #include <cstring> #include <memory> #include <survive_api.h> #include <cstdarg> #include <map> #if defined(_WIN32) #define HMD_DLL_EXPORT extern "C" __declspec(dllexport) #define HMD_DLL_IMPORT extern "C" __declspec(dllimport) #elif defined(__GNUC__) || defined(COMPILER_GCC) || defined(__APPLE__) #define HMD_DLL_EXPORT extern "C" __attribute__((visibility("default"))) #define HMD_DLL_IMPORT extern "C" #else #error "Unsupported Platform." #endif static void DriverLogVarArgs(const char *pMsgFormat, va_list args) { char buf[1024]; vsnprintf(buf, sizeof(buf), pMsgFormat, args); vr::VRDriverLog()->Log(buf); } void DriverLog(const char *pMsgFormat, ...) { va_list args; va_start(args, pMsgFormat); DriverLogVarArgs(pMsgFormat, args); va_end(args); } void DebugDriverLog(const char *pMsgFormat, ...) { va_list args; va_start(args, pMsgFormat); DriverLogVarArgs(pMsgFormat, args); va_end(args); } static vr::HmdQuaternion_t survive2openvr() { LinmathQuat q = {}; LinmathPoint3d survivePts[] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; LinmathPoint3d openvrPts[] = {{1, 0, 0}, {0, 0, -1}, {0, 1, 0}}; KabschCentered(q, (FLT *)survivePts, (FLT *)openvrPts, 3); return vr::HmdQuaternion_t{q[0], q[1], q[2], q[3]}; } LinmathPoint3d lh0position = {}; struct SurviveObjectOpenVRDriver : public vr::ITrackedDeviceServerDriver { explicit SurviveObjectOpenVRDriver(const SurviveSimpleObject *surviveSimpleObject) : surviveSimpleObject(surviveSimpleObject) {} vr::EVRInitError Activate(uint32_t unObjectId) override { objectId = unObjectId; // Prop_FieldOfViewLeftDegrees_Float auto objType = survive_simple_object_get_type(surviveSimpleObject); auto propContainer = vr::VRProperties()->TrackedDeviceToPropertyContainer(unObjectId); switch (objType) { case SurviveSimpleObject_LIGHTHOUSE: vr::VRProperties()->SetFloatProperty(propContainer, vr::Prop_FieldOfViewLeftDegrees_Float, 60); vr::VRProperties()->SetFloatProperty(propContainer, vr::Prop_FieldOfViewRightDegrees_Float, 60); vr::VRProperties()->SetFloatProperty(propContainer, vr::Prop_FieldOfViewBottomDegrees_Float, 60); vr::VRProperties()->SetFloatProperty(propContainer, vr::Prop_FieldOfViewTopDegrees_Float, 60); vr::VRProperties()->SetFloatProperty(propContainer, vr::Prop_TrackingRangeMinimumMeters_Float, 0.1); vr::VRProperties()->SetFloatProperty(propContainer, vr::Prop_TrackingRangeMaximumMeters_Float, 4); vr::VRProperties()->SetStringProperty(propContainer, vr::Prop_RenderModelName_String, "lh_basestation_vive"); break; case SurviveSimpleObject_OBJECT: vr::VRProperties()->SetStringProperty(propContainer, vr::Prop_RenderModelName_String, "{htc}vr_tracker_vive_1_0"); break; case SurviveSimpleObject_EXTERNAL: break; } return vr::VRInitError_None; } void Deactivate() override { objectId = vr::k_unTrackedDeviceIndexInvalid; } void EnterStandby() override {} void *GetComponent(const char *pchComponentNameAndVersion) override { return nullptr; } void DebugRequest(const char *pchRequest, char *pchResponseBuffer, uint32_t unResponseBufferSize) override {} vr::DriverPose_t Pose() const { SurvivePose sPose; survive_simple_object_get_latest_pose(surviveSimpleObject, &sPose); const char *name = survive_simple_object_name(surviveSimpleObject); if (strcmp(name, "LH0") == 0) { auto iSPose = InvertPoseRtn(&sPose); // scale3d(lh0position, iSPose.Pos, 1.); DebugDriverLog("lh0position %f %f %f", lh0position[0], lh0position[1], lh0position[2]); } vr::DriverPose_t pose = {0}; pose.poseIsValid = true; pose.result = vr::TrackingResult_Running_OK; pose.deviceIsConnected = true; pose.vecPosition[0] = sPose.Pos[0]; pose.vecPosition[1] = sPose.Pos[1]; pose.vecPosition[2] = sPose.Pos[2]; quatcopy(&pose.qRotation.w, sPose.Rot); pose.qWorldFromDriverRotation = survive2openvr(); copy3d(pose.vecWorldFromDriverTranslation, lh0position); pose.qDriverFromHeadRotation = vr::HmdQuaternion_t{1, 0, 0, 0}; return pose; } vr::DriverPose_t GetPose() override { return Pose(); } void NotifyUpdate() const { if (objectId != vr::k_unTrackedDeviceIndexInvalid) { vr::VRServerDriverHost()->TrackedDevicePoseUpdated(objectId, Pose(), sizeof(vr::DriverPose_t)); } } uint32_t objectId = vr::k_unTrackedDeviceIndexInvalid; const SurviveSimpleObject *surviveSimpleObject; }; static void log_fn(SurviveSimpleContext *ctx, SurviveLogLevel logLevel, const char *fault) { vr::VRDriverLog()->Log(fault); } class SurviveOpenVRDriver : public vr::IServerTrackedDeviceProvider { vr::EVRInitError Init(vr::IVRDriverContext *pDriverContext) override { VR_INIT_SERVER_DRIVER_CONTEXT(pDriverContext); vr::VRDriverLog()->Log("Loading up\n"); const char *args[] = {"", "--v", "100", "--usbmon", "--log", "/home/justin/.steam/logs/libsurvive.txt", "--center-on-lh0", "--force-calibrate"}; actx = survive_simple_init_with_logger(sizeof(args) / sizeof(args[0]), (char *const *)args, log_fn); if (actx == nullptr) { vr::VRDriverLog()->Log("Survive context was null"); return vr::VRInitError_Init_InterfaceNotFound; } survive_simple_start_thread(actx); for (const SurviveSimpleObject *it = survive_simple_get_first_object(actx); it != 0; it = survive_simple_get_next_object(actx, it)) { if (objects[it] == nullptr) { objects[it] = std::make_unique<SurviveObjectOpenVRDriver>(it); vr::VRServerDriverHost()->TrackedDeviceAdded(survive_simple_object_name(it), survive_simple_object_get_type(it) == SurviveSimpleObject_LIGHTHOUSE ? vr::TrackedDeviceClass_TrackingReference : vr::TrackedDeviceClass_GenericTracker, objects[it].get()); vr::VRDriverLog()->Log("Loaded object..."); } } vr::VRDriverLog()->Log("Init done..."); return vr::VRInitError_None; } void Cleanup() override { survive_simple_close(actx); actx = 0; } const char *const *GetInterfaceVersions() override { return vr::k_InterfaceVersions; } void RunFrame() override { for (const SurviveSimpleObject *it = survive_simple_get_next_updated(actx); it != 0; it = survive_simple_get_next_updated(actx)) { if (objects[it] == nullptr) { objects[it] = std::make_unique<SurviveObjectOpenVRDriver>(it); vr::VRServerDriverHost()->TrackedDeviceAdded(survive_simple_object_name(it), vr::TrackedDeviceClass_Controller, objects[it].get()); } objects[it]->NotifyUpdate(); } } bool ShouldBlockStandbyMode() override { return false; } void EnterStandby() override {} void LeaveStandby() override {} SurviveSimpleContext *actx = 0; std::map<const SurviveSimpleObject *, std::unique_ptr<SurviveObjectOpenVRDriver>> objects; }; SurviveOpenVRDriver g_serverDriver; HMD_DLL_EXPORT void *HmdDriverFactory(const char *pInterfaceName, int *pReturnCode) { if (0 == strcmp(vr::IServerTrackedDeviceProvider_Version, pInterfaceName)) { return &g_serverDriver; } if (pReturnCode) *pReturnCode = vr::VRInitError_Init_InterfaceNotFound; return NULL; }
31.880531
110
0.726718
[ "object" ]
b48b9ad75ec6bbdb34c9ef231b021747ae14905a
12,440
cpp
C++
llvm/lib/Target/AMDGPU/SIShrinkInstructions.cpp
vusec/typesan
831ca2af1a629e8ea93bb8c5b4215f12247b595c
[ "Apache-2.0" ]
30
2016-09-06T06:58:43.000Z
2021-12-23T11:59:38.000Z
llvm/lib/Target/AMDGPU/SIShrinkInstructions.cpp
vusec/typesan
831ca2af1a629e8ea93bb8c5b4215f12247b595c
[ "Apache-2.0" ]
1
2018-05-15T00:55:37.000Z
2018-05-15T00:55:37.000Z
llvm/lib/Target/AMDGPU/SIShrinkInstructions.cpp
vusec/typesan
831ca2af1a629e8ea93bb8c5b4215f12247b595c
[ "Apache-2.0" ]
17
2016-10-24T06:08:16.000Z
2022-02-18T17:27:14.000Z
//===-- SIShrinkInstructions.cpp - Shrink Instructions --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // /// The pass tries to use the 32-bit encoding for instructions when possible. //===----------------------------------------------------------------------===// // #include "AMDGPU.h" #include "AMDGPUMCInstLower.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #define DEBUG_TYPE "si-shrink-instructions" STATISTIC(NumInstructionsShrunk, "Number of 64-bit instruction reduced to 32-bit."); STATISTIC(NumLiteralConstantsFolded, "Number of literal constants folded into 32-bit instructions."); namespace llvm { void initializeSIShrinkInstructionsPass(PassRegistry&); } using namespace llvm; namespace { class SIShrinkInstructions : public MachineFunctionPass { public: static char ID; public: SIShrinkInstructions() : MachineFunctionPass(ID) { } bool runOnMachineFunction(MachineFunction &MF) override; const char *getPassName() const override { return "SI Shrink Instructions"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIShrinkInstructions, DEBUG_TYPE, "SI Lower il Copies", false, false) INITIALIZE_PASS_END(SIShrinkInstructions, DEBUG_TYPE, "SI Lower il Copies", false, false) char SIShrinkInstructions::ID = 0; FunctionPass *llvm::createSIShrinkInstructionsPass() { return new SIShrinkInstructions(); } static bool isVGPR(const MachineOperand *MO, const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI) { if (!MO->isReg()) return false; if (TargetRegisterInfo::isVirtualRegister(MO->getReg())) return TRI.hasVGPRs(MRI.getRegClass(MO->getReg())); return TRI.hasVGPRs(TRI.getPhysRegClass(MO->getReg())); } static bool canShrink(MachineInstr &MI, const SIInstrInfo *TII, const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI) { const MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2); // Can't shrink instruction with three operands. // FIXME: v_cndmask_b32 has 3 operands and is shrinkable, but we need to add // a special case for it. It can only be shrunk if the third operand // is vcc. We should handle this the same way we handle vopc, by addding // a register allocation hint pre-regalloc and then do the shrining // post-regalloc. if (Src2) { switch (MI.getOpcode()) { default: return false; case AMDGPU::V_MAC_F32_e64: if (!isVGPR(Src2, TRI, MRI) || TII->hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers)) return false; break; case AMDGPU::V_CNDMASK_B32_e64: break; } } const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); const MachineOperand *Src1Mod = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers); if (Src1 && (!isVGPR(Src1, TRI, MRI) || (Src1Mod && Src1Mod->getImm() != 0))) return false; // We don't need to check src0, all input types are legal, so just make sure // src0 isn't using any modifiers. if (TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers)) return false; // Check output modifiers if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod)) return false; return !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp); } /// \brief This function checks \p MI for operands defined by a move immediate /// instruction and then folds the literal constant into the instruction if it /// can. This function assumes that \p MI is a VOP1, VOP2, or VOPC instruction /// and will only fold literal constants if we are still in SSA. static void foldImmediates(MachineInstr &MI, const SIInstrInfo *TII, MachineRegisterInfo &MRI, bool TryToCommute = true) { if (!MRI.isSSA()) return; assert(TII->isVOP1(MI) || TII->isVOP2(MI) || TII->isVOPC(MI)); const SIRegisterInfo &TRI = TII->getRegisterInfo(); int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0); MachineOperand &Src0 = MI.getOperand(Src0Idx); // Only one literal constant is allowed per instruction, so if src0 is a // literal constant then we can't do any folding. if (Src0.isImm() && TII->isLiteralConstant(Src0, TII->getOpSize(MI, Src0Idx))) return; // Literal constants and SGPRs can only be used in Src0, so if Src0 is an // SGPR, we cannot commute the instruction, so we can't fold any literal // constants. if (Src0.isReg() && !isVGPR(&Src0, TRI, MRI)) return; // Try to fold Src0 if (Src0.isReg() && MRI.hasOneUse(Src0.getReg())) { unsigned Reg = Src0.getReg(); MachineInstr *Def = MRI.getUniqueVRegDef(Reg); if (Def && Def->isMoveImmediate()) { MachineOperand &MovSrc = Def->getOperand(1); bool ConstantFolded = false; if (MovSrc.isImm() && isUInt<32>(MovSrc.getImm())) { Src0.ChangeToImmediate(MovSrc.getImm()); ConstantFolded = true; } if (ConstantFolded) { if (MRI.use_empty(Reg)) Def->eraseFromParent(); ++NumLiteralConstantsFolded; return; } } } // We have failed to fold src0, so commute the instruction and try again. if (TryToCommute && MI.isCommutable() && TII->commuteInstruction(&MI)) foldImmediates(MI, TII, MRI, false); } // Copy MachineOperand with all flags except setting it as implicit. static MachineOperand copyRegOperandAsImplicit(const MachineOperand &Orig) { assert(!Orig.isImplicit()); return MachineOperand::CreateReg(Orig.getReg(), Orig.isDef(), true, Orig.isKill(), Orig.isDead(), Orig.isUndef(), Orig.isEarlyClobber(), Orig.getSubReg(), Orig.isDebug(), Orig.isInternalRead()); } bool SIShrinkInstructions::runOnMachineFunction(MachineFunction &MF) { MachineRegisterInfo &MRI = MF.getRegInfo(); const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo()); const SIRegisterInfo &TRI = TII->getRegisterInfo(); std::vector<unsigned> I1Defs; for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) { MachineBasicBlock &MBB = *BI; MachineBasicBlock::iterator I, Next; for (I = MBB.begin(); I != MBB.end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; // Try to use S_MOVK_I32, which will save 4 bytes for small immediates. if (MI.getOpcode() == AMDGPU::S_MOV_B32) { const MachineOperand &Src = MI.getOperand(1); if (Src.isImm()) { if (isInt<16>(Src.getImm()) && !TII->isInlineConstant(Src, 4)) MI.setDesc(TII->get(AMDGPU::S_MOVK_I32)); } continue; } if (MI.getOpcode() == AMDGPU::V_MOV_B32_e32) { // If this has a literal constant source that is the same as the // reversed bits of an inline immediate, replace with a bitreverse of // that constant. This saves 4 bytes in the common case of materializing // sign bits. // Test if we are after regalloc. We only want to do this after any // optimizations happen because this will confuse them. // XXX - not exactly a check for post-regalloc run. MachineOperand &Src = MI.getOperand(1); if (Src.isImm() && TargetRegisterInfo::isPhysicalRegister(MI.getOperand(0).getReg())) { int64_t Imm = Src.getImm(); if (isInt<32>(Imm) && !TII->isInlineConstant(Src, 4)) { int32_t ReverseImm = reverseBits<int32_t>(static_cast<int32_t>(Imm)); if (ReverseImm >= -16 && ReverseImm <= 64) { MI.setDesc(TII->get(AMDGPU::V_BFREV_B32_e32)); Src.setImm(ReverseImm); continue; } } } } if (!TII->hasVALU32BitEncoding(MI.getOpcode())) continue; if (!canShrink(MI, TII, TRI, MRI)) { // Try commuting the instruction and see if that enables us to shrink // it. if (!MI.isCommutable() || !TII->commuteInstruction(&MI) || !canShrink(MI, TII, TRI, MRI)) continue; } // getVOPe32 could be -1 here if we started with an instruction that had // a 32-bit encoding and then commuted it to an instruction that did not. if (!TII->hasVALU32BitEncoding(MI.getOpcode())) continue; int Op32 = AMDGPU::getVOPe32(MI.getOpcode()); if (TII->isVOPC(Op32)) { unsigned DstReg = MI.getOperand(0).getReg(); if (TargetRegisterInfo::isVirtualRegister(DstReg)) { // VOPC instructions can only write to the VCC register. We can't // force them to use VCC here, because this is only one register and // cannot deal with sequences which would require multiple copies of // VCC, e.g. S_AND_B64 (vcc = V_CMP_...), (vcc = V_CMP_...) // // So, instead of forcing the instruction to write to VCC, we provide // a hint to the register allocator to use VCC and then we we will run // this pass again after RA and shrink it if it outputs to VCC. MRI.setRegAllocationHint(MI.getOperand(0).getReg(), 0, AMDGPU::VCC); continue; } if (DstReg != AMDGPU::VCC) continue; } if (Op32 == AMDGPU::V_CNDMASK_B32_e32) { // We shrink V_CNDMASK_B32_e64 using regalloc hints like we do for VOPC // instructions. const MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2); if (!Src2->isReg()) continue; unsigned SReg = Src2->getReg(); if (TargetRegisterInfo::isVirtualRegister(SReg)) { MRI.setRegAllocationHint(SReg, 0, AMDGPU::VCC); continue; } if (SReg != AMDGPU::VCC) continue; } // We can shrink this instruction DEBUG(dbgs() << "Shrinking " << MI); MachineInstrBuilder Inst32 = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(Op32)); // Add the dst operand if the 32-bit encoding also has an explicit $vdst. // For VOPC instructions, this is replaced by an implicit def of vcc. int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst); if (Op32DstIdx != -1) { // dst Inst32.addOperand(MI.getOperand(0)); } else { assert(MI.getOperand(0).getReg() == AMDGPU::VCC && "Unexpected case"); } Inst32.addOperand(*TII->getNamedOperand(MI, AMDGPU::OpName::src0)); const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); if (Src1) Inst32.addOperand(*Src1); const MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2); if (Src2) { int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2); if (Op32Src2Idx != -1) { Inst32.addOperand(*Src2); } else { // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is // replaced with an implicit read of vcc. assert(Src2->getReg() == AMDGPU::VCC && "Unexpected missing register operand"); Inst32.addOperand(copyRegOperandAsImplicit(*Src2)); } } ++NumInstructionsShrunk; MI.eraseFromParent(); foldImmediates(*Inst32, TII, MRI); DEBUG(dbgs() << "e32 MI = " << *Inst32 << '\n'); } } return false; }
34.94382
81
0.619534
[ "vector" ]
b48e8c1a0db92b861e20c382668bbccc021ebb67
6,668
cpp
C++
codeforces/B - Berkomnadzor/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/B - Berkomnadzor/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/B - Berkomnadzor/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: JU_Troubleshooer: tariqiitju, the0dd1out, kzvd4729 created: Oct/20/2018 17:39 * solution_verdict: Accepted language: GNU C++14 * run_time: 608 ms memory_used: 32000 KB * problem: https://codeforces.com/contest/1070/problem/B ****************************************************************************************/ #include <bits/stdc++.h> using namespace std; #define output freopen("output.txt","w",stdout) #define input freopen("input.txt","r",stdin) #define inputfile(x) freopen(x,"r",stdin) #define outputfile(x) freopen(x,"w",stdout) #define ensure(c,m) assert(c && m) ///C IO #define pf printf #define sc scanf #define pch putchar #define ssc sscanf #define spf sprintf ///functions #define pb push_back #define Mid(l,r) ((l+r)>>1) #define present(c,x) ((c).find(x) != (c).end()) #define cpresent(c,x) (find(all(c),x) != (c).end()) #define mp make_pair #define xx first #define yy second #define endl '\n' #define forr(i,n) for(int i=0;i<n;i++) #define forr1(i,n) for(int i=1;i<=n;i++) ///memory reset #define MEM(Array,Val,Size) memset(Array,Val,(Size)*(sizeof(Array[0]))) #define SET(Array,Val) memset(Array,Val,sizeof(Array)) #define set0(x) memset(x,0,sizeof(x)) #define setn1(x) memset(x,-1,sizeof(x)) #define setinf(x) memset(x,127,sizeof(x)) ///misc #define SZ(v) ((int) (v).size()) #define all(v) (v).begin(), (v).end() ///bit operation single variable :: be careful with LL and ULL #define On(x,i) (x|=(1<<(i))) #define Off(x,i) (x&= ~(1<<(i))) #define isOn(x,i) (x&(1<<(i))) #define Toggle(x,i) (x^=(1<<(i))) #define tmod(x,i) (x&(~(-1<<i))) template <class _T>inline void ina(_T a[],int n) {forr(i,n)cin>>(a[i]);} #define nln cout<<"\n" #define sps cout<<" " int TEST_CASE=0; #define tcsp cout<<"Case "<<(++TEST_CASE)<<": " #define tcnl cout<<"Case "<<(++TEST_CASE)<<":\n" #define FAST ios_base::sync_with_stdio(false);cin.tie(NULL); #define precice(n) cout<<setprecision(n) #define FIX(n) cout<<setprecision(n)<<fixed //data type typedef long long ll; typedef unsigned long long ull; typedef long double LD; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef pair<double,double> pdd; typedef vector<int> vi; // typedef __int128 LLL; // typedef unsigned __int128 ULLL; //BIG MOD / mod inverse template<class _T>inline _T pow(_T a,_T b,_T m){a%=m;_T ans=1%m;while(b){if(b&1)ans*=a,ans%=m;a*=a;a%=m;b>>=1;}return ans;} template<class _T>inline _T pow(_T a,_T b) {_T ans=1;while(b){if(b&1)ans*=a;a*=a;b>>=1;}return ans;} template<class _T>inline _T add(_T a,_T b,_T m){return a>=m-b?a-(m-b):a+b;}//a,b<m template<class _T>inline _T multiply(_T a,_T b,_T m){_T ans=0;if(b>a)swap(a,b);while(b){if(b&1)ans=add(ans,a,m);b>>=1;a=add(a,a,m);}return ans;}//a,b<m template<class _T>inline _T bigpow(_T a,_T b,_T m){a%=m;_T ans=1%m;while(b){if(b&1)ans=multiply(ans,a,m);a=multiply(a,a,m);b>>=1;}return ans;} template<class _T>inline _T modinvers(_T a,_T m){return m>2000000000LL?bigpow(a,m-2,m):pow(a,m-2,m);}//m is prime //egcd / mod inverse template<class _T> _T _egcd(_T a, _T b, _T &x,_T &y){if(!b){x=1,y=0;return a;}_T _g=_egcd(b,a%b,x,y);_T xt=x;x=y,y=xt-(a/b)*y;return _g;} template<class _T>inline _T fmodinvers(_T a,_T m){_T x,y;_egcd(a,m,x,y);x%=m;if(x<0)x+=m;return x;} //a,m co-prime template<class _T>inline _T _lcm(_T a, _T b){return (a*b)/__gcd(a,b);} template <class T> inline T SQ(T a) {return a*a;} ll SQRT(ll n){ll e=sqrt(n*1.0);ll l=max(0LL,e-2),r=min(n,e+2);ll ans=0;while(l<=r){ll m=Mid(l,r);if(m*m<=n)ans=m,l=m+1;else r=m-1;}return ans;} ll CBRT(ll n){ll e=cbrt(n*1.0);ll l=max(0LL,e-2),r=min(n,e+2);ll ans=0;while(l<=r){ll m=Mid(l,r);if(m*m*m<=n)ans=m,l=m+1;else r=m-1;}return ans;} ///Random Number generator ull __SEED=3; ull __MULTI=6364136223846793005ULL; ull __INC=1442695040888963407ULL; ull lcg(){return __SEED=__SEED* __MULTI+ __INC;} template<class _T>inline _T random(_T L,_T R){return lcg()%(R-L+1)+L;} //direction array /* knight: int dx[]={1,-1,1,-1,2,2,-2,-2}; int dy[]={2,2,-2,-2,1,-1,1,-1}; Grid Side: int dx[]={0,0,1,-1};int dy[]={1,-1,0,0}; */ ///constant const LD EPS = 1e-9; const LD PI= acos(-1.0); const int MX= 6e5+5; ll mod= 1e9+7; typedef vector<unsigned> vu; vu bl,blk,wt; vi sm,smb,smw; bool posi=1; void bloc(unsigned mask,int i,vi block,vi white) { if(!posi) return; if(SZ(white)==0 && SZ(block)) { bl.push_back(mask); sm.push_back(31-i); return ; } if(SZ(block)==0) return ; ////impossible check int suffix_len=31-i; int mn_b=32,mn_w=32; for(int j:block) { mn_b=min (mn_b,smb[j]); } for(int j:white) { mn_w=min (mn_w,smw[j]); } if( mn_w <= suffix_len && mn_b<=suffix_len ) { posi=0; return ; } vi bl0,wt0; vi bl1,wt1; for(int j:block) { if(smb[j]<=suffix_len) { bl0.clear(); bl1.clear(); bl0.pb(j); bl1.pb(j); break; } if((blk[j]>>i)&1) bl1.pb(j); else bl0.pb(j); } for(int j:white) { if(smw[j]<=suffix_len) { wt0.clear(); wt1.clear(); wt0.pb(j); wt1.pb(j); break; } if((wt[j]>>i)&1) wt1.pb(j); else wt0.pb(j); } bloc(mask,i-1,bl0,wt0); bloc( mask|(1<<i),i-1,bl1,wt1 ); } int main() { int n; sc("%d\n",&n); for(int i=n;i--;) { char sn,k; unsigned a,b,c,d; sc("%c%u.%u.%u.%u%c",&sn,&a,&b,&c,&d,&k); unsigned msk=(a<<24)|(b<<16)|(c<<8)|d; int sd=32; if(k=='/') { sc("%d\n",&sd); } if(sn=='-') blk.pb(msk),smb.pb(sd); else wt.pb(msk),smw.pb(sd); //cerr<<msk<<endl; //cerr<<bitset<8>(msk)<<endl; } vi b,w; for(int i=0;i<SZ(blk);i++) b.pb(i); for(int i=0;i<SZ(wt);i++) w.pb(i); bloc(0,31,b,w); if(posi) { pf("%d\n",SZ(bl)); for(int i=0;i<SZ(bl);i++) { pf("%u.%u.%u.%u/%d\n",(bl[i]>>24)&255, (bl[i]>>16)&255,(bl[i]>>8)&255,bl[i]&255, sm[i] ); } }else cout<<-1<<endl; return 0; } /** Md. Tariqul Islam IIT,JU fb/tariqiitju tarik.amtoly@gmail.com */
32.686275
151
0.530444
[ "vector" ]
b48eb4596dce1ae8b0932484e741d025137dabce
10,742
hpp
C++
include/NatSuite/Examples/Components/RecordButton.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/NatSuite/Examples/Components/RecordButton.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/NatSuite/Examples/Components/RecordButton.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: UnityEngine.EventSystems.IPointerDownHandler #include "UnityEngine/EventSystems/IPointerDownHandler.hpp" // Including type: UnityEngine.EventSystems.IPointerUpHandler #include "UnityEngine/EventSystems/IPointerUpHandler.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: NatSuite::Examples::Components namespace NatSuite::Examples::Components { } // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Image class Image; } // Forward declaring namespace: UnityEngine::Events namespace UnityEngine::Events { // Forward declaring type: UnityEvent class UnityEvent; } // Forward declaring namespace: UnityEngine::EventSystems namespace UnityEngine::EventSystems { // Forward declaring type: PointerEventData class PointerEventData; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: IEnumerator class IEnumerator; } // Completed forward declares // Type namespace: NatSuite.Examples.Components namespace NatSuite::Examples::Components { // Forward declaring type: RecordButton class RecordButton; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::NatSuite::Examples::Components::RecordButton); DEFINE_IL2CPP_ARG_TYPE(::NatSuite::Examples::Components::RecordButton*, "NatSuite.Examples.Components", "RecordButton"); // Type namespace: NatSuite.Examples.Components namespace NatSuite::Examples::Components { // Size: 0x39 #pragma pack(push, 1) // Autogenerated type: NatSuite.Examples.Components.RecordButton // [TokenAttribute] Offset: FFFFFFFF // [RequireComponent] Offset: 781D00 class RecordButton : public ::UnityEngine::MonoBehaviour/*, public ::UnityEngine::EventSystems::IPointerDownHandler, public ::UnityEngine::EventSystems::IPointerUpHandler*/ { public: // Nested type: ::NatSuite::Examples::Components::RecordButton::$Countdown$d__10 class $Countdown$d__10; public: // public UnityEngine.UI.Image button // Size: 0x8 // Offset: 0x18 ::UnityEngine::UI::Image* button; // Field size check static_assert(sizeof(::UnityEngine::UI::Image*) == 0x8); // public UnityEngine.UI.Image countdown // Size: 0x8 // Offset: 0x20 ::UnityEngine::UI::Image* countdown; // Field size check static_assert(sizeof(::UnityEngine::UI::Image*) == 0x8); // public UnityEngine.Events.UnityEvent onTouchDown // Size: 0x8 // Offset: 0x28 ::UnityEngine::Events::UnityEvent* onTouchDown; // Field size check static_assert(sizeof(::UnityEngine::Events::UnityEvent*) == 0x8); // public UnityEngine.Events.UnityEvent onTouchUp // Size: 0x8 // Offset: 0x30 ::UnityEngine::Events::UnityEvent* onTouchUp; // Field size check static_assert(sizeof(::UnityEngine::Events::UnityEvent*) == 0x8); // private System.Boolean pressed // Size: 0x1 // Offset: 0x38 bool pressed; // Field size check static_assert(sizeof(bool) == 0x1); public: // Creating interface conversion operator: operator ::UnityEngine::EventSystems::IPointerDownHandler operator ::UnityEngine::EventSystems::IPointerDownHandler() noexcept { return *reinterpret_cast<::UnityEngine::EventSystems::IPointerDownHandler*>(this); } // Creating interface conversion operator: operator ::UnityEngine::EventSystems::IPointerUpHandler operator ::UnityEngine::EventSystems::IPointerUpHandler() noexcept { return *reinterpret_cast<::UnityEngine::EventSystems::IPointerUpHandler*>(this); } // Deleting conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept = delete; // static field const value: static private System.Single MaxRecordingTime static constexpr const float MaxRecordingTime = 10; // Get static field: static private System.Single MaxRecordingTime static float _get_MaxRecordingTime(); // Set static field: static private System.Single MaxRecordingTime static void _set_MaxRecordingTime(float value); // Get instance field reference: public UnityEngine.UI.Image button [[deprecated("Use field access instead!")]] ::UnityEngine::UI::Image*& dyn_button(); // Get instance field reference: public UnityEngine.UI.Image countdown [[deprecated("Use field access instead!")]] ::UnityEngine::UI::Image*& dyn_countdown(); // Get instance field reference: public UnityEngine.Events.UnityEvent onTouchDown [[deprecated("Use field access instead!")]] ::UnityEngine::Events::UnityEvent*& dyn_onTouchDown(); // Get instance field reference: public UnityEngine.Events.UnityEvent onTouchUp [[deprecated("Use field access instead!")]] ::UnityEngine::Events::UnityEvent*& dyn_onTouchUp(); // Get instance field reference: private System.Boolean pressed [[deprecated("Use field access instead!")]] bool& dyn_pressed(); // public System.Void .ctor() // Offset: 0xB311FC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RecordButton* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::NatSuite::Examples::Components::RecordButton::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RecordButton*, creationType>())); } // private System.Void Start() // Offset: 0xB3107C void Start(); // private System.Void Reset() // Offset: 0xB31080 void Reset(); // private System.Void UnityEngine.EventSystems.IPointerDownHandler.OnPointerDown(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0xB3115C void UnityEngine_EventSystems_IPointerDownHandler_OnPointerDown(::UnityEngine::EventSystems::PointerEventData* eventData); // private System.Void UnityEngine.EventSystems.IPointerUpHandler.OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0xB311F4 void UnityEngine_EventSystems_IPointerUpHandler_OnPointerUp(::UnityEngine::EventSystems::PointerEventData* eventData); // private System.Collections.IEnumerator Countdown() // Offset: 0xB31188 ::System::Collections::IEnumerator* Countdown(); }; // NatSuite.Examples.Components.RecordButton #pragma pack(pop) static check_size<sizeof(RecordButton), 56 + sizeof(bool)> __NatSuite_Examples_Components_RecordButtonSizeCheck; static_assert(sizeof(RecordButton) == 0x39); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: NatSuite::Examples::Components::RecordButton::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: NatSuite::Examples::Components::RecordButton::Start // Il2CppName: Start template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (NatSuite::Examples::Components::RecordButton::*)()>(&NatSuite::Examples::Components::RecordButton::Start)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(NatSuite::Examples::Components::RecordButton*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: NatSuite::Examples::Components::RecordButton::Reset // Il2CppName: Reset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (NatSuite::Examples::Components::RecordButton::*)()>(&NatSuite::Examples::Components::RecordButton::Reset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(NatSuite::Examples::Components::RecordButton*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: NatSuite::Examples::Components::RecordButton::UnityEngine_EventSystems_IPointerDownHandler_OnPointerDown // Il2CppName: UnityEngine.EventSystems.IPointerDownHandler.OnPointerDown template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (NatSuite::Examples::Components::RecordButton::*)(::UnityEngine::EventSystems::PointerEventData*)>(&NatSuite::Examples::Components::RecordButton::UnityEngine_EventSystems_IPointerDownHandler_OnPointerDown)> { static const MethodInfo* get() { static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.EventSystems", "PointerEventData")->byval_arg; return ::il2cpp_utils::FindMethod(classof(NatSuite::Examples::Components::RecordButton*), "UnityEngine.EventSystems.IPointerDownHandler.OnPointerDown", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData}); } }; // Writing MetadataGetter for method: NatSuite::Examples::Components::RecordButton::UnityEngine_EventSystems_IPointerUpHandler_OnPointerUp // Il2CppName: UnityEngine.EventSystems.IPointerUpHandler.OnPointerUp template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (NatSuite::Examples::Components::RecordButton::*)(::UnityEngine::EventSystems::PointerEventData*)>(&NatSuite::Examples::Components::RecordButton::UnityEngine_EventSystems_IPointerUpHandler_OnPointerUp)> { static const MethodInfo* get() { static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.EventSystems", "PointerEventData")->byval_arg; return ::il2cpp_utils::FindMethod(classof(NatSuite::Examples::Components::RecordButton*), "UnityEngine.EventSystems.IPointerUpHandler.OnPointerUp", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData}); } }; // Writing MetadataGetter for method: NatSuite::Examples::Components::RecordButton::Countdown // Il2CppName: Countdown template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (NatSuite::Examples::Components::RecordButton::*)()>(&NatSuite::Examples::Components::RecordButton::Countdown)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(NatSuite::Examples::Components::RecordButton*), "Countdown", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
55.087179
282
0.755167
[ "vector" ]
b490162dce90d2f75331601bf6b8673c765c8a5c
4,428
cpp
C++
wrappers/C/Testing/Suite_LibStruct_Tests.cpp
sys-bio/Archive_roadRunner
611bd5338bf842fb5708a9ad75a316bbcc44c902
[ "Apache-2.0" ]
null
null
null
wrappers/C/Testing/Suite_LibStruct_Tests.cpp
sys-bio/Archive_roadRunner
611bd5338bf842fb5708a9ad75a316bbcc44c902
[ "Apache-2.0" ]
null
null
null
wrappers/C/Testing/Suite_LibStruct_Tests.cpp
sys-bio/Archive_roadRunner
611bd5338bf842fb5708a9ad75a316bbcc44c902
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <fstream> #include "unit_test/UnitTest++.h" #include "rrc_api.h" #include "rrUtils.h" #include "rrIniFile.h" #include "rrException.h" #include "src/TestUtils.h" using namespace UnitTest; using namespace std; using namespace rr; using namespace rrc; extern string gTempFolder; extern string gTestDataFolder; extern string gCompiler; SUITE(LIBSTRUCT_TESTS) { string TestDataFileName = "LibStructTest.dat"; IniFile iniFile; string TestModelFileName; RRHandle gRR = NULL; TEST(testLibStructTestsDataFiles) { string sec("LS_TESTS"); string key("InputFile"); gRR = createRRInstanceEx(gTempFolder.c_str(), gCompiler.c_str()); string testDataFileName = joinPath(gTestDataFolder, TestDataFileName); CHECK(fileExists(testDataFileName)); CHECK(iniFile.Load(testDataFileName)); clog<<"Loaded test data from file: "<< testDataFileName; if(iniFile.GetSection(sec)) { IniSection* sbml = iniFile.GetSection(sec); IniKey* fNameKey = sbml->GetKey(key); if(fNameKey) { TestModelFileName = joinPath(gTestDataFolder, fNameKey->mValue); CHECK(fileExists(TestModelFileName)); } } CHECK(loadSBMLFromFileE(gRR, TestModelFileName.c_str(), true)); } TEST(getLinkMatrix) { string section("getLinkMatrix"); if(iniFile.GetSection(section)) { IniSection* isec = iniFile.GetSection(section); ls::DoubleMatrix ref = getDoubleMatrixFromString(isec->GetNonKeysAsString()); //Testing call RRDoubleMatrix* actual = getLinkMatrix(gRR); //Check dimensions if(actual->RSize != ref.RSize() || actual->CSize != ref.CSize()) { CHECK(false); return; } for(int row = 0; row < actual->RSize; row++) { for(int col = 0; col < actual->CSize; col++) { CHECK_CLOSE(ref(row,col), actual->Data[row*actual->CSize + col], 1e-6); } } } } TEST(getEigenValuesMatrix) { string section("getEigenValuesMatrix"); if(iniFile.GetSection(section)) { IniSection* isec = iniFile.GetSection(section); ls::DoubleMatrix ref = getDoubleMatrixFromString(isec->GetNonKeysAsString()); RRDoubleMatrix* input = getLinkMatrix(gRR); //Testing call RRDoubleMatrix* actual = getEigenvaluesMatrix(input); ///////////////////////////////// //Check dimensions if(actual->RSize != ref.RSize() || actual->CSize != ref.CSize()) { CHECK(false); return; } for(int row = 0; row < actual->RSize; row++) { for(int col = 0; col < actual->CSize; col++) { CHECK_CLOSE(ref(row,col), actual->Data[row*actual->CSize + col], 1e-6); } } } } TEST(getEigenValuesVector) { string section("getEigenvaluesVector"); if(iniFile.GetSection(section)) { IniSection* isec = iniFile.GetSection(section); vector< complex<double> > ref = getComplexVectorFromString(isec->GetNonKeysAsString()); RRDoubleMatrix* input = getLinkMatrix(gRR); //Testing call RRComplexVector* actual = getEigenvaluesVector(input); ////////////////////////////////////////////////////////////////// //Check dimensions if(actual->Count != ref.size()) { CHECK(false); return; } for(int row = 0; row < actual->Count; row++) { CHECK_CLOSE(real(ref[row]), actual->Data[row].re, 1e-6); CHECK_CLOSE(imag(ref[row]), actual->Data[row].imag, 1e-6); } } } TEST(FREE_RR_INSTANCE) { CHECK(freeRRInstance(gRR)); gRR = NULL; } }
30.328767
109
0.511743
[ "vector" ]
b49119b34476ce2be2c9c9a79ae0d6ed2ee11bcd
3,427
hpp
C++
openZia/IModule.hpp
MatthieuMv/openZia
ac41ab7e1f0e94a6f415f0b849ddd6418364dd1c
[ "MIT" ]
17
2020-01-20T14:29:18.000Z
2021-11-02T19:00:46.000Z
openZia/IModule.hpp
MatthieuMv/openZia
ac41ab7e1f0e94a6f415f0b849ddd6418364dd1c
[ "MIT" ]
35
2020-02-03T17:00:07.000Z
2020-03-01T15:24:17.000Z
openZia/IModule.hpp
MatthieuMv/openZia
ac41ab7e1f0e94a6f415f0b849ddd6418364dd1c
[ "MIT" ]
21
2020-02-04T12:33:33.000Z
2020-02-27T10:42:38.000Z
/* ** EPITECH PROJECT, 2020 ** CPP_zia_2019 ** File description: ** Module interface */ #pragma once #include <memory> #include <vector> #include "Context.hpp" #include "EntryPoint.hpp" namespace oZ { class IModule; class Pipeline; /** * @brief Priority enum, used to sort modules in the pipeline. * * If you need to sort modules with more precision, you can use intermediate offset. * Example: Low + 1, Low + 2, ... */ enum Priority : std::uint16_t { Last = 0, Independent = 1000, Low = 2000, Medium = 3000, High = 4000, ASAP = 5000 }; enum class MessageState { Readable = 0, Done, Disconnection }; /** * @brief Module pointer type, using shared_ptr as backend. */ using ModulePtr = std::shared_ptr<IModule>; /** * @brief Function signature that each module should respect to get detected and instantied. * It musts uses the name 'createModule'. * * Example : IModule *CreateModule(void) { return MyModule(); } */ using ModuleInstanceFunction = IModule*(*)(void); } /** * @brief This class is the interface of every module. * * Each module can reimplement a set of virtual functions at each callback of the pipeline. * Pipeline callbacks get a Context reference in order to transform and/or use its state. */ class oZ::IModule { public: /** * @brief Dependencies are represented as a vector of raw string */ using Dependencies = std::vector<const char *>; /** * @brief Destroy the IModule object */ virtual ~IModule(void) = default; /** * @brief Get the module name */ virtual const char *getName(void) const = 0; /** * @brief Register module's callbacks in the pipeline */ virtual void onRegisterCallbacks(Pipeline &) = 0; /** * @brief Get the module dependencies * * By default a module has no dependencies */ virtual Dependencies getDependencies(void) const noexcept { return Dependencies(); } /** * @brief This function is called once module registered their callbacks * * There you should (if needed) implement dependencies search * Be careful, at this point other modules may not have retreived their dependencies ! * Use the pipeline only to find your dependencies and store their shared_ptr instances * * This function is not pure virtual because you may not need it */ virtual void onRetreiveDependencies(Pipeline &pipeline); /** * @brief This function is called after module retreived its dependencies. * * The given directory is the path to configuration files * * This function is not pure virtual because you may not need it */ virtual void onLoadConfigurationFile(const std::string &directory); /** * @brief Callback used to intercept client connections */ virtual void onConnection(Context &context); /** * @brief Callback used to intercept client disconnections */ virtual void onDisconnection(Context &context); /** * @brief Callback used to read client message and prepare a given context with the data * * @return Returns true if the message has been read and the pipeline can be runned */ virtual MessageState onMessageAvaible(Context &context); };
26.361538
96
0.645171
[ "object", "vector", "transform" ]
b493acd6f43a5b89e6c5f8d7e680f2f5a8110cd7
40,598
cpp
C++
analysiscode/Simpoint.cpp
EricCheng2222/simpoint
9896a7844682331adedaf4971380b02bf4395895
[ "Unlicense" ]
5
2018-07-04T09:21:30.000Z
2022-02-14T14:24:44.000Z
analysiscode/Simpoint.cpp
EricCheng2222/simpoint
9896a7844682331adedaf4971380b02bf4395895
[ "Unlicense" ]
1
2018-07-05T06:12:19.000Z
2018-07-07T00:07:56.000Z
analysiscode/Simpoint.cpp
EricCheng2222/simpoint
9896a7844682331adedaf4971380b02bf4395895
[ "Unlicense" ]
4
2016-12-02T05:30:43.000Z
2020-07-15T09:04:27.000Z
/*********************************************************************** * __________________________________________________________________ * * _____ _ ____ _ __ * / ___/(_)___ ___ / __ \____ (_)___ / /_ * \__ \/ / __ `__ \/ /_/ / __ \/ / __ \/ __/ * ___/ / / / / / / / ____/ /_/ / / / / / /_ * /____/_/_/ /_/ /_/_/ \____/_/_/ /_/\__/ * * __________________________________________________________________ * * This file is part of the SimPoint Toolkit written by Greg Hamerly, * Erez Perelman, Jeremy Lau, Tim Sherwood, and Brad Calder as part of * Efficient Simulation Project at UCSD. If you find this toolkit useful please * cite the following paper published at ASPLOS 2002. * * Timothy Sherwood, Erez Perelman, Greg Hamerly and Brad Calder, * Automatically Characterizing Large Scale Program Behavior , In the * 10th International Conference on Architectural Support for Programming * Languages and Operating Systems, October 2002. * * Contact info: * Brad Calder <calder@cs.ucsd.edu>, (858) 822 - 1619 * Greg Hamerly <Greg_Hamerly@baylor.edu>, * Erez Perelman <eperelma@cs.ucsd.edu>, * Jeremy Lau <jl@cs.ucsd.edu>, * Tim Sherwood <sherwood@cs.ucsb.edu> * * University of California, San Diego * Department of Computer Science and Engineering * 9500 Gilman Drive, Dept 0114 * La Jolla CA 92093-0114 USA * * * Copyright 2001, 2002, 2003, 2004, 2005 The Regents of the University of * California All Rights Reserved * * Permission to use, copy, modify and distribute any part of this * SimPoint Toolkit for educational, non-profit, and industry research * purposes, without fee, and without a written agreement is hereby * granted, provided that the above copyright notice, this paragraph and * the following four paragraphs appear in all copies and every modified * file. * * Permission is not granted to include SimPoint into a commercial product. * Those desiring to incorporate this SimPoint Toolkit into commercial * products should contact the Technology Transfer Office, University of * California, San Diego, 9500 Gilman Drive, La Jolla, CA 92093-0910, Ph: * (619) 534-5815, FAX: (619) 534-7345. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THE SimPoint * Toolkit, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * THE SimPoint Toolkit PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE * UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, * SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE UNIVERSITY OF * CALIFORNIA MAKES NO REPRESENTATIONS AND EXTENDS NO WARRANTIES OF ANY * KIND, EITHER IMPLIED OR EXPRESS, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR * PURPOSE, OR THAT THE USE OF THE SimPoint Toolkit WILL NOT INFRINGE ANY * PATENT, TRADEMARK OR OTHER RIGHTS. * * No non-profit user may place any restrictions on the use of this * software, including as modified by the user, by any other authorized * user. * ************************************************************************/ #include <iostream> #include <fstream> #include <set> #include <algorithm> #include <ctime> #include <cfloat> #include <cmath> #include <cstdio> #include <cstdlib> #include <sys/stat.h> #include "Utilities.h" #include "Dataset.h" #include "KMeans.h" #include "SimpointOptions.h" #include "Simpoint.h" #include "CmdLineParser.h" #include "Logger.h" bool Simpoint::isRegularFile(const string &filename) { struct stat info; if (stat(filename.c_str(), &info) != 0) { return false; } return S_ISREG(info.st_mode); } FILE *Simpoint::openInputVectorFile(const string &filename, bool isGzipped) { Utilities::check(isRegularFile(filename), "openInputVectorFile() not regular file: " + filename); FILE *input = NULL; if (isGzipped) { string command = "gzip -dc " + filename; input = popen(command.c_str(), "r"); } else { input = fopen(filename.c_str(), "r"); } Utilities::check(input != NULL, "openInputVectorFile() could not open file " + filename); return input; } void Simpoint::closeInputVectorFile(FILE *fp, bool isGzipped) { if (isGzipped) { pclose(fp); } else { fclose(fp); } } void Simpoint::loadData() { Utilities::check(wholeDataset == NULL, "Simpoint::loadData() wholeDataset is not NULL"); // load the data, project it, etc. if (options.loadVectorsTxtFmtName != "") { FILE *input = openInputVectorFile(options.loadVectorsTxtFmtName, options.inputVectorsAreGzipped); wholeDataset = new Dataset; wholeDataset->read(input); Logger::log() << "Loaded data from text format data file '" << options.loadVectorsTxtFmtName << "' (size: " << wholeDataset->numRows() << "x" << wholeDataset->numCols() << ")\n"; closeInputVectorFile(input, options.inputVectorsAreGzipped); } else if (options.loadVectorsBinFmtName != "") { FILE *input = openInputVectorFile(options.loadVectorsBinFmtName, options.inputVectorsAreGzipped); wholeDataset = new Dataset; wholeDataset->readBinary(input); Logger::log() << "Loaded data from binary format data file '" << options.loadVectorsBinFmtName << "' (size: " << wholeDataset->numRows() << "x" << wholeDataset->numCols() << ")\n"; closeInputVectorFile(input, options.inputVectorsAreGzipped); } else if (options.frequencyVectorFileName != "") { FILE *input = openInputVectorFile(options.frequencyVectorFileName, options.inputVectorsAreGzipped); FVParser *parser = new FVParser(input); int numPts, numDims; if ((options.numFreqVectors != options.DEFAULT_NUM_FREQ_VECTORS) && (options.numFVDims != options.DEFAULT_NUM_FREQ_DIMS)) { numPts = options.numFreqVectors; numDims = options.numFVDims; } else { Utilities::sizeOfFVFile(*parser, &numPts, &numDims); delete parser; closeInputVectorFile(input, options.inputVectorsAreGzipped); input = openInputVectorFile(options.frequencyVectorFileName, options.inputVectorsAreGzipped); parser = new FVParser(input); } Logger::log() << " Loading data from frequency vector file '" << options.frequencyVectorFileName << "' (size: " << numPts << "x" << numDims << ")\n"; if (options.useNoProjection) { wholeDataset = new Dataset(numPts, numDims); Utilities::loadFVFile(*parser, wholeDataset); Logger::log() << " Loaded frequency vectors without projecting them.\n"; delete parser; } else { // Get the projection matrix Dataset *projection = NULL; if (options.loadProjMatrixTxtFmtName != "") { Utilities::check(isRegularFile(options.loadProjMatrixTxtFmtName), "loadData() not regular file: " + options.loadProjMatrixTxtFmtName); projection = new Dataset; ifstream input(options.loadProjMatrixTxtFmtName.c_str()); Utilities::check(input, "Simpoint::loadData(): could not open file " + options.loadProjMatrixTxtFmtName); projection->read(input); input.close(); Logger::log() << " Loaded projection matrix from file '" << options.loadProjMatrixTxtFmtName << "' (size: " << projection->numRows() << "x" << projection->numCols() << ")\n"; Utilities::check(projection->numRows() == (unsigned int)numDims, "loadData(): projection matrix rows != original dimensions"); } else if (options.loadProjMatrixBinFmtName != "") { Utilities::check(isRegularFile(options.loadProjMatrixBinFmtName), "loadData() not regular file: " + options.loadProjMatrixBinFmtName); projection = new Dataset; ifstream input(options.loadProjMatrixBinFmtName.c_str()); Utilities::check(input, "Simpoint::loadData(): could not open file " + options.loadProjMatrixBinFmtName); projection->readBinary(input); input.close(); Logger::log() << " Loaded projection matrix from binary file '" << options.loadProjMatrixBinFmtName << "' (size: " << projection->numRows() << "x" << projection->numCols() << ")\n"; Utilities::check(projection->numRows() == (unsigned int)numDims, "loadData(): projection matrix rows != original dimensions"); } else { projection = new Dataset(numDims, options.projectionDimension); Utilities::randomProjectionMatrix(options.randSeedProjection, projection); Logger::log() << " Created random projection matrix (size: " << numDims << "x" << options.projectionDimension << ")\n"; } // save the projection matrix if (options.saveProjMatrixTxtFmtName != "") { Logger::log() << " Saving the projection matrix to file '" << options.saveProjMatrixTxtFmtName << "'\n"; ofstream output(options.saveProjMatrixTxtFmtName.c_str()); Utilities::check(output, "Simpoint::loadData(): could not open file " + options.saveProjMatrixTxtFmtName); projection->write(output); output.close(); } if (options.saveProjMatrixBinFmtName != "") { Logger::log() << " Saving the projection matrix to binary file '" << options.saveProjMatrixBinFmtName << "'\n"; ofstream output(options.saveProjMatrixBinFmtName.c_str()); Utilities::check(output, "Simpoint::loadData(): could not open file " + options.saveProjMatrixBinFmtName); projection->writeBinary(output); output.close(); } wholeDataset = new Dataset(numPts, options.projectionDimension); Utilities::loadAndProjectFVFile(*parser, *projection, wholeDataset); delete parser; if (options.inputVectorsAreGzipped) { pclose(input); } else { fclose(input); } Logger::log() << " Loaded and projected frequency vector file\n"; delete projection; } } else { // shouldn't get here Utilities::check(false, "loadData(): no data to load"); } } Dataset *Simpoint::loadInitialCentersFromLabels(const string &file, const Dataset &data) { Utilities::check(isRegularFile(file), "Simpoint::loadInitialCentersFromLabels() not regular file: " + file); int n = data.numRows(), d = data.numCols(); ifstream input(file.c_str()); Utilities::check(input, "Simpoint::loadInitialCentersFromLabels() could not open file " + file); // load all the labels, find the largest one in the process (this is // the number of clusters) map<string, int> labelMap; // map from user-given (external) label to actual (internal) label vector<int> labels(n); for (int i = 0; i < n; i++) { string externalLabel; input >> externalLabel; map<string, int>::iterator itr = labelMap.find(externalLabel); if (itr == labelMap.end()) { int lmsize = labelMap.size(); labelMap[externalLabel] = lmsize; itr = labelMap.find(externalLabel); } labels[i] = itr->second; } int k = labelMap.size(); // create the initial centers Dataset *centers = new Dataset(k, d); for (int i = 0; i < k; i++) { centers->setWeight(i, 0.0); } // assign each datapoint to each center for (int i = 0; i < n; i++) { double wt = data.getWeight(i); (*centers)[labels[i]].multAndAdd(data[i], wt); centers->setWeight(labels[i], centers->getWeight(labels[i]) + wt); } // normalize each center for (int i = 0; i < k; i++) { (*centers)[i] /= centers->getWeight(i); } return centers; } Dataset *Simpoint::loadInitialCenters(int runNumber, int seedNumber) const { Dataset *centers = NULL; // user has provided initial labels? if (options.loadInitialLabelsName != "") { centers = loadInitialCentersFromLabels(options.loadInitialLabelsName, *wholeDataset); // user has provided initial centers? } else if (options.loadInitialCentersName != "") { Utilities::check(isRegularFile(options.loadInitialCentersName), "loadInitialCenters() not regular file: " + options.loadInitialCentersName); centers = new Dataset; ifstream input(options.loadInitialCentersName.c_str()); Utilities::check(input, "Simpoint::loadInitialCenters(): could not open file " + options.loadInitialCentersName); centers->read(input); input.close(); Logger::log() << " Loaded initial k-means centers from file '" << options.loadInitialCentersName << "' (k = " << centers->numRows() << ")\n"; Utilities::check(centers->numCols() == wholeDataset->numCols(), "loadInitialCenters(): initial centers dimension != " "projected data dimension"); // user has not provided initial labels or centers; create the initial centers } else { centers = new Dataset(options.kValues[runNumber], wholeDataset->numCols()); if (options.kMeansInitType == "samp") { KMeans::initializeRandomly(options.randSeedKMeansInit + seedNumber, *wholeDataset, centers); Logger::log() << " Initialized k-means centers using random sampling: " << options.kValues[runNumber] << " centers\n"; } else if (options.kMeansInitType == "ff") { KMeans::initializeFurthestFirst(options.randSeedKMeansInit + seedNumber, *wholeDataset, centers); Logger::log() << " Initialized k-means centers using furthest-first: " << options.kValues[runNumber] << " centers\n"; } else { Utilities::check(false, "loadInitialCenters(): unknown k-means initialization type"); } } // Set the (VLI) weights for the centers properly. If vectors should not be // VLI-weighted, the appropriate weights should (will) be applied outside // this scope, after this function completes. for (unsigned int i = 0; i < centers->numRows(); i++) { centers->setWeight(i, 0.0); } vector<int> labels(wholeDataset->numRows()); KMeans::findLabelsAndDists(*wholeDataset, *centers, &labels); for (unsigned int i = 0; i < wholeDataset->numRows(); i++) { centers->setWeight(labels[i], wholeDataset->getWeight(i) + centers->getWeight(labels[i])); } // make sure the center weights add to 1.0 double totalWeight = 0.0; for (unsigned int i = 0; i < centers->numRows(); i++) { totalWeight += centers->getWeight(i); } for (unsigned int i = 0; i < centers->numRows(); i++) { centers->setWeight(i, centers->getWeight(i) / totalWeight); } return centers; } void Simpoint::sampleDataset() { Utilities::check(sampledDataset == NULL, "Simpoint::sampleDataset() sampledDataset is not NULL"); if ((options.sampleSize > 0) && ((unsigned int)options.sampleSize < wholeDataset->numRows())) { // choose enough samples to satisfy the number of desired samples Random rand(options.randSeedSample); vector<pair<double, int> > sortedWeights(wholeDataset->numRows()); for (unsigned int i = 0; i < wholeDataset->numRows(); i++) { sortedWeights[i] = pair<double, int>(wholeDataset->getWeight(i), i); } sort(sortedWeights.begin(), sortedWeights.end(), greater<pair<double, int> >()); for (unsigned int i = 1; i < wholeDataset->numRows(); i++) { sortedWeights[i].first += sortedWeights[i-1].first; } sortedWeights[wholeDataset->numRows() - 1].first = 1.0; // just to be sure set<int> samples; double sampledPct = 0.0; while (samples.size() < (unsigned int)options.sampleSize) { double r = (double)rand.randFloat(); // binary search for the sample corresponding to the generated // random number unsigned int lower = 0, upper = sortedWeights.size(); unsigned int sample = (upper + lower) / 2; while (true) { bool below = (sample > 0) ? (sortedWeights[sample - 1].first <= r) : true; bool above = (sample < sortedWeights.size()) ? (sortedWeights[sample].first >= r) : true; if (above && below) { break; } if (below) { lower = sample; } if (above) { upper = sample; } sample = (upper + lower) / 2; } if (samples.find(sortedWeights[sample].second) == samples.end()) { sampledPct += wholeDataset->getWeight(sortedWeights[sample].second); samples.insert(sortedWeights[sample].second); } } unsigned int sampleSize = samples.size(); Logger::log() << " Creating a random sample of size " << sampleSize << " vectors for clustering\n"; Logger::log() << " which represents " << (sampledPct * 100) << "% of the weights\n"; sampledDataset = new Dataset(sampleSize, wholeDataset->numCols()); // copy the sampled data into the working data structure and reweight it int j = 0; for (set<int>::iterator i = samples.begin(); i != samples.end(); i++) { for (unsigned int col = 0; col < wholeDataset->numCols(); col++) { (*sampledDataset)[j][col] = (*wholeDataset)[*i][col]; sampledDataset->setWeight(j, wholeDataset->getWeight(*i) / sampledPct); } j++; } } else { sampledDataset = wholeDataset; } } void Simpoint::applyWeights() { if (options.fixedLength == "on") { Logger::log() << " Applying fixed-length vector weights (uniform weights)\n"; double weight = 1.0 / (double)wholeDataset->numRows(); for (unsigned int i = 0; i < wholeDataset->numRows(); i++) { wholeDataset->setWeight(i, weight); } } else if (options.loadVectorWeightsName != "") { Logger::log() << " Applying vector weights from file " << options.loadVectorWeightsName << endl; Utilities::check(isRegularFile(options.loadVectorWeightsName), "applyWeights() not regular file " + options.loadVectorWeightsName); ifstream input(options.loadVectorWeightsName.c_str()); Utilities::check(input, "Simpoint::applyWeights(): could not open file " + options.loadVectorWeightsName); vector<double> weights(wholeDataset->numRows()); double totalWeight = 0.0; for (unsigned int i = 0; i < wholeDataset->numRows(); i++) { input >> weights[i]; totalWeight += weights[i]; } for (unsigned int i = 0; i < wholeDataset->numRows(); i++) { wholeDataset->setWeight(i, weights[i] / totalWeight); } input.close(); } } string Simpoint::createFileNameFromRun(const string &baseName, int runNumber, int kValue) { char newname[1024]; sprintf(newname, "%s.run_%d_k_%d", baseName.c_str(), runNumber, kValue); return string(newname); } void Simpoint::savePreClusteringData() { if (options.saveVectorsTxtFmtName != "") { Logger::log() << " Saving Simpoint-format vector data to text file '" << options.saveVectorsTxtFmtName << "'\n"; ofstream output(options.saveVectorsTxtFmtName.c_str()); Utilities::check(output, "Simpoint::savePreClusteringData(): could not open file " + options.saveVectorsTxtFmtName); wholeDataset->write(output); output.close(); } if (options.saveVectorsBinFmtName != "") { Logger::log() << " Saving Simpoint-format vector data to binary file '" << options.saveVectorsBinFmtName << "'\n"; ofstream output(options.saveVectorsBinFmtName.c_str()); Utilities::check(output, "Simpoint::savePreClusteringData(): could not open file " + options.saveVectorsBinFmtName); wholeDataset->writeBinary(output); output.close(); } if (options.saveVectorWeightsName != "") { Logger::log() << " Saving weights of each input vector to file '" << options.saveVectorWeightsName << "'\n"; ofstream output(options.saveVectorWeightsName.c_str()); Utilities::check(output, "Simpoint::saveVectorWeights(): could not open file " + options.saveVectorWeightsName); output.precision(20); for (unsigned int i = 0; i < wholeDataset->numRows(); i++) { output << wholeDataset->getWeight(i) << endl; } output.close(); } } int Simpoint::findBestRun() { int bestRun = 0; if (options.kValues.size() > 1) { double min_bic = bicScores[0], max_bic = bicScores[0]; for (unsigned int i = 1; i < options.kValues.size(); i++) { if (bicScores[i] > max_bic) { max_bic = bicScores[i]; } if (bicScores[i] < min_bic) { min_bic = bicScores[i]; } } double threshold = (max_bic - min_bic) * options.bicThreshold + min_bic; bestRun = -1; for (unsigned int i = 0; i < options.kValues.size(); i++) { if ((bicScores[i] >= threshold) && ((bestRun == -1) || (options.kValues[i] < options.kValues[bestRun]))) { bestRun = i; } } } return bestRun; } vector<bool> Simpoint::getLargestClusters(double coveragePct, const Dataset &finalCenters) { Utilities::check(coveragePct >= 0 && coveragePct <= 1, "getLargestClusters(): coveragePct is out of bounds"); // sort the clusters by size // the pair represents percentage (double) and cluster (int) vector<pair<double, int> > sortedClusters(finalCenters.numRows()); for (unsigned int i = 0; i < sortedClusters.size(); i++) { sortedClusters[i] = make_pair(finalCenters.getWeight(i), i); } sort(sortedClusters.begin(), sortedClusters.end()); reverse(sortedClusters.begin(), sortedClusters.end()); // now that they're sorted, select the largest that fulfill the // desired percentage and mark them as largestClusters double percentExecution = 0.0; vector<bool> largestClusters(sortedClusters.size(), false); // order of orig. clusters Logger::log(1) << " Largest non-empty clusters with total weight >= " << coveragePct << " (listed largest to smallest): "; for (unsigned int i = 0; (i < sortedClusters.size()) && (percentExecution < coveragePct) && (sortedClusters[i].first > 0.0); i++) { percentExecution += sortedClusters[i].first; largestClusters[sortedClusters[i].second] = true; Logger::log(1) << sortedClusters[i].second << " "; } Logger::log(1) << endl; return largestClusters; } void Simpoint::saveSimpoints(const string &filename, const vector<bool> &largestClusters, const Datapoint &distsToCenters, const vector<int> &labels, unsigned int k) { vector<double> minDists(k, -1.0); vector<int> simpoints(k, -1); for (unsigned int i = 0; i < distsToCenters.size(); i++) { int label = labels[i]; if ((simpoints[label] == -1) || (distsToCenters[i] < minDists[label])) { simpoints[label] = i; minDists[label] = distsToCenters[i]; } } ofstream output(filename.c_str()); Utilities::check(output, "Simpoint::saveSimpoints(): could not open file " + filename); for (unsigned int i = 0; i < k; i++) { if (largestClusters[i]) { output << simpoints[i] << " " << i << endl; } } output.close(); } void Simpoint::saveSimpointWeights(const string &filename, const vector<bool> &largestClusters, const Dataset &centers) { ofstream output(filename.c_str()); Utilities::check(output, "Simpoint::saveSimpointWeights(): could not open file " + filename); double sumWeights = 0.0; for (unsigned int r = 0; r < centers.numRows(); r++) { if (largestClusters[r]) { sumWeights += centers.getWeight(r); } } for (unsigned int r = 0; r < centers.numRows(); r++) { if (largestClusters[r]) { output << (centers.getWeight(r) / sumWeights) << " " << r << endl; } } output.close(); } void Simpoint::savePostClusteringData() { Logger::log() << endl << "------------------------------------------------------------------\n" << "------------------------------------------------------------------\n" << "Post-processing runs\n" << "------------------------------------------------------------------\n" << "------------------------------------------------------------------\n"; int bestRun = findBestRun(); Logger::log() << " For the BIC threshold, the best clustering was run " << (bestRun+1) << " (k = " << options.kValues[bestRun] << ")\n"; vector<int> labels(wholeDataset->numRows(), 0); Datapoint distsToCenters(wholeDataset->numRows()); // save everything or just the best for (unsigned int runNumber = 0; runNumber < options.kValues.size(); runNumber++) { if ((runNumber != (unsigned int)bestRun) && (! options.saveAll)) { continue; } Logger::log() << " Post-processing run " << (runNumber+1) << " (k = " << options.kValues[runNumber] << ")\n"; // save the initial centers if (options.saveInitialCentersName != "") { string name = options.saveInitialCentersName; if (options.saveAll) { name = createFileNameFromRun(options.saveInitialCentersName, runNumber+1, options.kValues[runNumber]); } Logger::log() << " Saving initial centers to file '" << name << "'\n"; ofstream output(name.c_str()); Utilities::check(output, "Simpoint::savePostClusteringData(): could not open file " + name); initialCenters[runNumber]->write(output); output.close(); } // save the final centers if (options.saveFinalCentersName != "") { string name = options.saveFinalCentersName; if (options.saveAll) { name = createFileNameFromRun(options.saveFinalCentersName, runNumber+1, options.kValues[runNumber]); } Logger::log() << " Saving final centers to file '" << name << "'\n"; ofstream output(name.c_str()); Utilities::check(output, "Simpoint::savePostClusteringData(): could not open file " + name); finalCenters[runNumber]->write(output); output.close(); } // pre-compute the labels and distances for saveSimpoints or saveLabels KMeans::findLabelsAndDists(*wholeDataset, *finalCenters[runNumber], &labels, &distsToCenters); // save labels if (options.saveLabelsName != "") { string name = options.saveLabelsName; if (options.saveAll) { name = createFileNameFromRun(options.saveLabelsName, runNumber+1, options.kValues[runNumber]); } Logger::log() << " Saving labels and distance from center of " << "each input vector to file '" << name << "'\n"; ofstream output(name.c_str()); Utilities::check(output, "Simpoint::savePostClusteringData(): could not open file " + name); for (unsigned int r = 0; r < labels.size(); r++) { /* output the label and the distance from the center of this point */ output << labels[r] << " " << distsToCenters[r] << endl; } output.close(); } // prepare to save only the largest simpoints and weights vector<bool> nonEmptyClusters = getLargestClusters(1.0, *finalCenters[runNumber]); vector<bool> largestClusters = nonEmptyClusters; if (options.coveragePct < 1.0) { largestClusters = getLargestClusters(options.coveragePct, *finalCenters[runNumber]); } // save simpoints if (options.saveSimpointsName != "") { string name = options.saveSimpointsName; if (options.saveAll) { name = createFileNameFromRun(name, runNumber+1, options.kValues[runNumber]); } Logger::log() << " Saving simpoints of all non-empty clusters to file '" << name << "'\n"; saveSimpoints(name, nonEmptyClusters, distsToCenters, labels, finalCenters[runNumber]->numRows()); if (options.coveragePct < 1.0) { name = options.saveSimpointsName + ".lpt" + toString(options.coveragePct); if (options.saveAll) { name = createFileNameFromRun(name, runNumber+1, options.kValues[runNumber]); } Logger::log() << " Saving simpoints of largest clusters " << "making up proportion " << options.coveragePct << " of all weights to file '" << name << "'\n"; saveSimpoints(name, largestClusters, distsToCenters, labels, finalCenters[runNumber]->numRows()); } } // save weights if (options.saveSimpointWeightsName != "") { string name = options.saveSimpointWeightsName; if (options.saveAll) { name = createFileNameFromRun(name, runNumber+1, options.kValues[runNumber]); } Logger::log() << " Saving weights of all non-empty clusters to file '" << name << "'\n"; saveSimpointWeights(name, nonEmptyClusters, *finalCenters[runNumber]); if (options.coveragePct < 1.0) { name = options.saveSimpointWeightsName + ".lpt" + toString(options.coveragePct); if (options.saveAll) { name = createFileNameFromRun(name, runNumber+1, options.kValues[runNumber]); } Logger::log() << " Saving weights of largest clusters " << "making up proportion " << options.coveragePct << " of all weights to file '" << name << "'\n"; saveSimpointWeights(name, largestClusters, *finalCenters[runNumber]); } } } } void Simpoint::doClustering() { loadData(); applyWeights(); sampleDataset(); savePreClusteringData(); // create vectors to save all the data that will be produced vector<int> labels(wholeDataset->numRows(), 0); Datapoint distsToCenters(wholeDataset->numRows()); // binary search variables int search_k_max = options.max_k, search_k_min = 1, min_bic_ndx = 0, max_bic_ndx = 0; if (options.useBinarySearch) { Logger::log() << " Searching for best clustering for k <= " << search_k_max << endl; options.kValues.clear(); options.kValues.push_back(search_k_min); options.kValues.push_back(search_k_max); options.kValues.push_back((search_k_max + search_k_min) / 2); } else { Logger::log() << " Clustering for user-defined k-values\n"; if (options.learnKFromFile) { // find out the k value from the clusters the user provided Dataset *tempCtrs = loadInitialCenters(0, 0); options.kValues.push_back(tempCtrs->numRows()); delete tempCtrs; } } vector<Dataset *> initSeedInitialCenters(options.numInitSeeds), initSeedFinalCenters(options.numInitSeeds); vector<double> initSeedBicScores(options.numInitSeeds); for (unsigned int runNumber = 0; runNumber < options.kValues.size(); runNumber++) { Logger::log() << endl << "--------------------------------------------------------------\n" << "Run number " << (runNumber+1) << " of "; if (options.useBinarySearch) { int maxRuns = (int)(log((double)options.max_k) / log(2.0) + 3); Logger::log() << "at most " << maxRuns; } else { Logger::log() << options.kValues.size(); } Logger::log() << ", k = " << options.kValues[runNumber] << endl << "--------------------------------------------------------------\n"; int bestInitSeedRun = 0; for (int initSeedRun = 0; initSeedRun < options.numInitSeeds; initSeedRun++) { Logger::log() << " --------------------------------------------------------------\n" << " Initialization seed trial #" << (initSeedRun+1) << " of " << options.numInitSeeds << "; initialization seed = " << options.randSeedKMeansInit << endl << " --------------------------------------------------------------\n"; initSeedInitialCenters[initSeedRun] = loadInitialCenters(runNumber, initSeedRun); initSeedFinalCenters[initSeedRun] = new Dataset(*initSeedInitialCenters[initSeedRun]); int iteration_limit = options.numKMeansIterations; if (options.useNoIterationLimit) { iteration_limit = INT_MAX; } KMeans::runKMeans(*sampledDataset, initSeedFinalCenters[initSeedRun], iteration_limit); // calculate and save the BIC score initSeedBicScores[initSeedRun] = KMeans::bicScore(*wholeDataset, *initSeedFinalCenters[initSeedRun]); Logger::log() << " BIC score: " << initSeedBicScores[initSeedRun] << endl; if (initSeedBicScores[initSeedRun] > initSeedBicScores[bestInitSeedRun]) { bestInitSeedRun = initSeedRun; } // report the distortions and variances KMeans::findLabelsAndDists(*wholeDataset, *initSeedFinalCenters[initSeedRun], &labels, &distsToCenters); Datapoint clusterDistortions(initSeedFinalCenters[initSeedRun]->numRows()); double dist = KMeans::distortion(*wholeDataset, labels, *initSeedFinalCenters[initSeedRun], &clusterDistortions); Logger::log() << " Distortion: " << dist << endl << " Distortions/cluster: "; for (unsigned int i = 0; i < clusterDistortions.size(); i++) { Logger::log() << clusterDistortions[i] << " "; } Logger::log() << endl; double degreesOfFreedom = wholeDataset->numRows() - initSeedFinalCenters[initSeedRun]->numRows(); Logger::log() << " Variance: " << (dist/degreesOfFreedom) << endl << " Variances/cluster: "; for (unsigned int i = 0; i < clusterDistortions.size(); i++) { double weight = initSeedFinalCenters[initSeedRun]->getWeight(i) * wholeDataset->numRows(); if (weight > 1.0) { Logger::log() << (clusterDistortions[i] / (weight - 1.0)) << " "; } else { Logger::log() << 0 << " "; } } Logger::log() << endl; options.randSeedKMeansInit++; } Logger::log() << " The best initialization seed trial was #" << (bestInitSeedRun+1) << endl; initialCenters.push_back(initSeedInitialCenters[bestInitSeedRun]); finalCenters.push_back(initSeedFinalCenters[bestInitSeedRun]); bicScores.push_back(initSeedBicScores[bestInitSeedRun]); // free up the memory and reset the pointers for the next go-round for (int initSeedRun = 0; initSeedRun < options.numInitSeeds; initSeedRun++) { if (initSeedRun != bestInitSeedRun) { delete initSeedInitialCenters[initSeedRun]; delete initSeedFinalCenters[initSeedRun]; } initSeedInitialCenters[initSeedRun] = NULL; initSeedFinalCenters[initSeedRun] = NULL; } if (options.useBinarySearch) { if (bicScores[runNumber] > bicScores[max_bic_ndx]) max_bic_ndx = runNumber; if (bicScores[runNumber] < bicScores[min_bic_ndx]) min_bic_ndx = runNumber; double bic_range = (bicScores[max_bic_ndx] - bicScores[min_bic_ndx]); double bic_threshold = bicScores[min_bic_ndx] + bic_range * options.bicThreshold; int last_k = options.kValues[runNumber]; if (runNumber >= 2) { // determine where we should search next int next_k = -1; bool searchUpper = (max_bic_ndx > min_bic_ndx) ? (bicScores.back() < bic_threshold) : false; if (searchUpper) { // search in upper window next_k = (last_k + search_k_max) / 2; search_k_min = last_k; } else { // search in the lower window next_k = (last_k + search_k_min) / 2; search_k_max = last_k; } // the ending condition for binary search if ((search_k_max - search_k_min) > 1) { options.kValues.push_back(next_k); } } } } savePostClusteringData(); } Simpoint::~Simpoint() { if (wholeDataset && (wholeDataset == sampledDataset)) { delete wholeDataset; } else { if (wholeDataset) { delete wholeDataset; } if (sampledDataset) { delete sampledDataset; } } wholeDataset = sampledDataset = NULL; for (unsigned int i = 0; i < initialCenters.size(); i++) { if (initialCenters[i]) { delete initialCenters[i]; initialCenters[i] = NULL; } } for (unsigned int i = 0; i < finalCenters.size(); i++) { if (finalCenters[i]) { delete finalCenters[i]; finalCenters[i] = NULL; } } } bool Simpoint::parseCmdLineOptions(int argc, char **argv) { Logger::log() << "Command-line: \""; for (int i = 0; i < argc; i++) { if (i > 0) { Logger::log() << ' '; } Logger::log() << argv[i]; } Logger::log() << "\"\n"; if (argc == 1) { options.usage(argv[0]); return false; } if (! options.parseOptions(argc, argv)) { return false; } Logger::log() << "Using these options (*** indicates user-specified option):\n"; options.printOptionSettings(Logger::log()); Logger::log() << "-------------------------------------------------------------\n"; return true; } // MAIN int main(int argc, char **argv) { Simpoint simpointAnalyzer; if (simpointAnalyzer.parseCmdLineOptions(argc, argv)) { // do everything else simpointAnalyzer.doClustering(); } return 0; }
43.327641
118
0.571284
[ "vector" ]
b498a488f5e7ecbc993beb3ee8e3c58cbe11202a
15,561
cc
C++
src/json.cc
StevenYCChou/metadata-agent
31fe5ca0cc6075fb233c3609cab91747503e54e2
[ "Apache-2.0" ]
15
2018-02-05T19:44:40.000Z
2021-07-10T01:38:38.000Z
src/json.cc
Stackdriver/metadata-agent
85d4f5a570911ddbc2cd0be2a87fa186694140d3
[ "Apache-2.0" ]
61
2018-01-31T22:04:29.000Z
2019-07-29T12:07:10.000Z
src/json.cc
StevenYCChou/metadata-agent
31fe5ca0cc6075fb233c3609cab91747503e54e2
[ "Apache-2.0" ]
11
2018-01-25T17:03:49.000Z
2022-01-15T10:09:06.000Z
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #include "json.h" #include <cmath> #include <iostream> #include <iterator> #include <limits> #include <sstream> #include <utility> #include <yajl/yajl_gen.h> #include <yajl/yajl_parse.h> //#if HAVE_YAJL_YAJL_VERSION_H //# include <yajl/yajl_version.h> //#endif #include <stdio.h> #include <stdlib.h> #include <string.h> namespace json { namespace internal { constexpr const char TypeHelper<Null>::name[]; constexpr const char TypeHelper<Boolean>::name[]; constexpr const char TypeHelper<Number>::name[]; constexpr const char TypeHelper<String>::name[]; constexpr const char TypeHelper<Array>::name[]; constexpr const char TypeHelper<Object>::name[]; struct JSONSerializer { JSONSerializer(); ~JSONSerializer(); std::string ToString(); void ToStream(std::ostream& stream); yajl_gen& gen() { return gen_; } private: std::pair<const unsigned char*, size_t> buf(); void clear(); yajl_gen gen_; }; JSONSerializer::JSONSerializer() { gen_ = yajl_gen_alloc(NULL); //yajl_gen_config(gen, yajl_gen_beautify, 1); yajl_gen_config(gen_, yajl_gen_validate_utf8, 1); } JSONSerializer::~JSONSerializer() { yajl_gen_free(gen_); } std::pair<const unsigned char*, size_t> JSONSerializer::buf() { size_t len; const unsigned char* buf; yajl_gen_get_buf(gen_, &buf, &len); return {buf, len}; } void JSONSerializer::clear() { yajl_gen_clear(gen_); } void JSONSerializer::ToStream(std::ostream& stream) { const auto buf_and_len = buf(); stream.write(reinterpret_cast<const char*>(buf_and_len.first), buf_and_len.second); } std::string JSONSerializer::ToString() { const auto buf_and_len = buf(); return {reinterpret_cast<const char*>(buf_and_len.first), buf_and_len.second}; } } // internal std::string Value::ToString() const { internal::JSONSerializer serializer; Serialize(&serializer); return serializer.ToString(); } std::ostream& operator<<(std::ostream& stream, const Value& value) { internal::JSONSerializer serializer; value.Serialize(&serializer); serializer.ToStream(stream); return stream; } void Null::Serialize(internal::JSONSerializer* serializer) const { yajl_gen_null(serializer->gen()); } std::unique_ptr<Value> Null::Clone() const { return std::unique_ptr<Value>(new Null()); } void Boolean::Serialize(internal::JSONSerializer* serializer) const { yajl_gen_bool(serializer->gen(), value_); } std::unique_ptr<Value> Boolean::Clone() const { return std::unique_ptr<Value>(new Boolean(value_)); } namespace { template<class IntType> constexpr bool IsEffectivelyInteger(long double value) { return (value == std::floor(value) && value >= std::numeric_limits<IntType>::min() && value <= std::numeric_limits<IntType>::max() && !(value == 0.0 && std::signbit(value))); } } void Number::Serialize(internal::JSONSerializer* serializer) const { if (IsEffectivelyInteger<long long>(value_)) { yajl_gen_integer(serializer->gen(), static_cast<long long>(value_)); } else { yajl_gen_double(serializer->gen(), static_cast<double>(value_)); } } std::unique_ptr<Value> Number::Clone() const { return std::unique_ptr<Value>(new Number(value_)); } void String::Serialize(internal::JSONSerializer* serializer) const { yajl_gen_string(serializer->gen(), reinterpret_cast<const unsigned char*>(value_.data()), value_.size()); } std::unique_ptr<Value> String::Clone() const { return std::unique_ptr<Value>(new String(value_)); } Array::Array(const Array& other) { for (const auto& e : other) { emplace_back(e->Clone()); } } Array::Array(std::vector<std::unique_ptr<Value>>&& elements) { for (auto& e : elements) { if (e != nullptr) { emplace_back(std::move(e)); } } } Array::Array( std::initializer_list<rref_capture<std::unique_ptr<Value>>> elements) { for (auto& e : elements) { if (((std::unique_ptr<Value>&&) e) != nullptr) { emplace_back(std::move(e)); } } } void Array::Serialize(internal::JSONSerializer* serializer) const { yajl_gen_array_open(serializer->gen()); for (const auto& e : *this) { e->Serialize(serializer); } yajl_gen_array_close(serializer->gen()); } std::unique_ptr<Value> Array::Clone() const { return std::unique_ptr<Value>(new Array(*this)); } Object::Object(const Object& other) { for (const auto& kv : other) { emplace(kv.first, kv.second->Clone()); } } Object::Object(std::map<std::string, std::unique_ptr<Value>>&& fields) { for (auto& kv : fields) { if (kv.second != nullptr) { emplace(kv.first, std::move(kv.second)); } } } Object::Object( std::initializer_list<std::pair<std::string, rref_capture<std::unique_ptr<Value>>>> fields) { for (auto& kv : fields) { if (((std::unique_ptr<Value>&&) kv.second) != nullptr) { emplace(kv.first, std::move(kv.second)); } } } void Object::Serialize(internal::JSONSerializer* serializer) const { yajl_gen_map_open(serializer->gen()); for (const auto& e : *this) { yajl_gen_string(serializer->gen(), reinterpret_cast<const unsigned char*>(e.first.data()), e.first.size()); e.second->Serialize(serializer); } yajl_gen_map_close(serializer->gen()); } std::unique_ptr<Value> Object::Clone() const { return std::unique_ptr<Value>(new Object(*this)); } namespace { class Context { public: virtual ~Context() = default; virtual void AddValue(std::unique_ptr<Value> value) = 0; std::unique_ptr<Context> parent() { return std::move(parent_); } protected: Context(std::unique_ptr<Context> parent) : parent_(std::move(parent)) {} private: std::unique_ptr<Context> parent_; }; class ArrayContext : public Context { public: ArrayContext(std::unique_ptr<Context> parent) : Context(std::move(parent)) {} void AddValue(std::unique_ptr<Value> value) override { elements.emplace_back(std::move(value)); } std::vector<std::unique_ptr<Value>> elements; }; class ObjectContext : public Context { public: ObjectContext(std::unique_ptr<Context> parent) : Context(std::move(parent)) {} void NewField(const std::string& name) { if (field_name_ != nullptr) { std::cerr << "Replacing " << *field_name_ << " with " << name << std::endl; } field_name_.reset(new std::string(name)); } void AddValue(std::unique_ptr<Value> value) override { if (field_name_ == nullptr) { std::cerr << "Value without a field name" << *value << std::endl; return; } fields.emplace(*field_name_, std::move(value)); field_name_.reset(); } std::map<std::string, std::unique_ptr<Value>> fields; private: std::unique_ptr<std::string> field_name_; }; class CallbackContext : public Context { public: CallbackContext(std::function<void(std::unique_ptr<Value>)> callback) : Context(nullptr), callback_(callback) {} void AddValue(std::unique_ptr<Value> value) override { callback_(std::move(value)); } private: std::function<void(std::unique_ptr<Value>)> callback_; }; // A builder context that allows building up a JSON object. class JSONBuilder { public: JSONBuilder(std::function<void(std::unique_ptr<Value>)> callback) : context_(new CallbackContext(callback)) {} ~JSONBuilder() = default; void AddValue(std::unique_ptr<Value> value) { context_->AddValue(std::move(value)); } void PushArray() { context_.reset(new ArrayContext(std::move(context_))); } void PushObject() { context_.reset(new ObjectContext(std::move(context_))); } std::unique_ptr<ArrayContext> PopArray() { ArrayContext* array_context = dynamic_cast<ArrayContext*>(context_.get()); if (array_context == nullptr) { std::cerr << "Not in array context" << std::endl; return nullptr; } context_ = context_.release()->parent(); return std::unique_ptr<ArrayContext>(array_context); } std::unique_ptr<ObjectContext> PopObject() { ObjectContext* object_context = dynamic_cast<ObjectContext*>(context_.get()); if (object_context == nullptr) { std::cerr << "Not in object context" << std::endl; return nullptr; } context_ = context_.release()->parent(); return std::unique_ptr<ObjectContext>(object_context); } // Objects only. bool NewField(const std::string& name) { ObjectContext* object_context = dynamic_cast<ObjectContext*>(context_.get()); if (object_context == nullptr) { std::cerr << "NewField " << name << " outside of object" << std::endl; return false; } object_context->NewField(name); return true; } private: std::unique_ptr<Context> context_; }; int handle_null(void* arg) { JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); builder->AddValue(std::unique_ptr<Value>(new Null())); return 1; } int handle_bool(void* arg, int value) { JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); builder->AddValue( std::unique_ptr<Value>(new Boolean(static_cast<bool>(value)))); return 1; } int handle_string(void* arg, const unsigned char* val, size_t length) { std::string value(reinterpret_cast<const char*>(val), length); JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); builder->AddValue(std::unique_ptr<Value>(new String(value))); return 1; } int handle_integer(void* arg, long long value) { JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); builder->AddValue( std::unique_ptr<Value>(new Number(value))); return 1; } int handle_double(void* arg, double value) { JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); builder->AddValue(std::unique_ptr<Value>(new Number(value))); return 1; } int handle_start_array(void* arg) { JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); builder->PushArray(); return 1; } static int handle_end_array(void* arg) { JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); std::unique_ptr<ArrayContext> array_context = builder->PopArray(); if (array_context == nullptr) { return 0; } builder->AddValue( std::unique_ptr<Value>(new Array(std::move(array_context->elements)))); return 1; } int handle_start_map(void* arg) { JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); builder->PushObject(); return 1; } int handle_map_key(void* arg, const unsigned char* data, size_t length) { std::string key(reinterpret_cast<const char*>(data), length); JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); return builder->NewField(key) ? 1 : 0; } int handle_end_map(void* arg) { JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg); std::unique_ptr<ObjectContext> object_context = builder->PopObject(); if (object_context == nullptr) { return 0; } builder->AddValue( std::unique_ptr<Value>(new Object(std::move(object_context->fields)))); return 1; } const yajl_callbacks callbacks = { .yajl_null = &handle_null, .yajl_boolean = &handle_bool, .yajl_integer = &handle_integer, .yajl_double = &handle_double, .yajl_number = nullptr, .yajl_string = &handle_string, .yajl_start_map = &handle_start_map, .yajl_map_key = &handle_map_key, .yajl_end_map = &handle_end_map, .yajl_start_array = &handle_start_array, .yajl_end_array = &handle_end_array, }; class YajlHandle { public: YajlHandle(JSONBuilder* builder) : handle_(yajl_alloc(&callbacks, NULL, builder)) { yajl_config(handle_, yajl_allow_comments, 1); yajl_config(handle_, yajl_allow_multiple_values, 1); //yajl_config(handle_, yajl_allow_partial_values, 1); //yajl_config(handle_, yajl_allow_trailing_garbage, 1); //yajl_config(handle_, yajl_dont_validate_strings, 1); } ~YajlHandle() { yajl_free(handle_); } operator yajl_handle() { return handle_; } private: yajl_handle handle_; }; class YajlError { public: YajlError(yajl_handle handle, bool verbose, const unsigned char* json_text, size_t json_len) : handle_(handle), str_(yajl_get_error(handle_, (int)verbose, json_text, json_len)) {} ~YajlError() { yajl_free_error(handle_, str_); } const char* c_str() { return reinterpret_cast<const char*>(str_); } private: yajl_handle handle_; unsigned char* str_; }; } // namespace std::vector<std::unique_ptr<Value>> Parser::AllFromStream(std::istream& stream) throw(Exception) { std::vector<std::unique_ptr<Value>> values; Parser p([&values](std::unique_ptr<Value> r){ values.emplace_back(std::move(r)); }); p.ParseStream(stream); p.NotifyEOF(); return values; } std::unique_ptr<Value> Parser::FromStream(std::istream& stream) throw(Exception) { std::vector<std::unique_ptr<Value>> all_values = AllFromStream(stream); if (all_values.empty()) { return nullptr; } if (all_values.size() > 1) { std::ostringstream out; out << "Single value expected, " << all_values.size() << " values seen"; throw Exception(out.str()); } return std::move(all_values[0]); } std::vector<std::unique_ptr<Value>> Parser::AllFromString( const std::string& input) throw(Exception) { return AllFromStream(std::istringstream(input)); } std::unique_ptr<Value> Parser::FromString(const std::string& input) throw(Exception) { return FromStream(std::istringstream(input)); } class Parser::ParseState { public: ParseState(std::function<void(std::unique_ptr<Value>)> callback) : builder_(callback), handle_(&builder_) { yajl_config(handle_, yajl_allow_comments, 1); yajl_config(handle_, yajl_allow_multiple_values, 1); //yajl_config(handle_, yajl_allow_partial_values, 1); //yajl_config(handle_, yajl_allow_trailing_garbage, 1); //yajl_config(handle_, yajl_dont_validate_strings, 1); } void Done() throw(Exception) { yajl_status stat = yajl_complete_parse(handle_); if (stat != yajl_status_ok) { YajlError err(handle_, 0, nullptr, 0); throw Exception(err.c_str()); } } yajl_handle handle() { return handle_; } private: JSONBuilder builder_; YajlHandle handle_; }; Parser::Parser(std::function<void(std::unique_ptr<Value>)> callback) : state_(new ParseState(callback)) {} Parser::~Parser() = default; std::size_t Parser::ParseStream(std::istream& stream) throw(Exception) { const int kMax = 65536; unsigned char data[kMax] = {0}; size_t total_bytes_consumed = 0; yajl_handle handle = state_->handle(); while (!stream.eof()) { stream.read(reinterpret_cast<char*>(&data[0]), kMax); size_t count = stream.gcount(); yajl_status stat = yajl_parse(handle, data, count); if (stat != yajl_status_ok) { YajlError err(handle, 1, data, kMax); throw Exception(err.c_str()); } total_bytes_consumed += yajl_get_bytes_consumed(handle); } return total_bytes_consumed; } void Parser::NotifyEOF() throw(Exception) { state_->Done(); } } // json
27.639432
80
0.685432
[ "object", "vector" ]
b49a31f58309245b7bd851d8aca20fbeaafc24b3
2,149
cpp
C++
Hackerrank/30_Days_of_Code/Day_12_Inheritance.cpp
Snehakri022/Competitive-Programming-Solutions
62a2cbb2d71a040d81e3e71ad6353a86007b8cb7
[ "MIT" ]
40
2020-07-25T19:35:37.000Z
2022-01-28T02:57:02.000Z
Hackerrank/30_Days_of_Code/Day_12_Inheritance.cpp
Snehakri022/Competitive-Programming-Solutions
62a2cbb2d71a040d81e3e71ad6353a86007b8cb7
[ "MIT" ]
160
2021-04-26T19:04:15.000Z
2022-03-26T20:18:37.000Z
Hackerrank/30_Days_of_Code/Day_12_Inheritance.cpp
Snehakri022/Competitive-Programming-Solutions
62a2cbb2d71a040d81e3e71ad6353a86007b8cb7
[ "MIT" ]
24
2020-05-03T08:11:53.000Z
2021-10-04T03:23:20.000Z
#include <iostream> #include <vector> using namespace std; class Person{ protected: string firstName; string lastName; int id; public: Person(string firstName, string lastName, int identification){ this->firstName = firstName; this->lastName = lastName; this->id = identification; } void printPerson(){ cout<< "Name: "<< lastName << ", "<< firstName <<"\nID: "<< id << "\n"; } }; class Student : public Person{ private: vector<int> testScores; public: Student(string firstName, string lastName, int id, std::vector<int>& scores) : Person(firstName,lastName,id), testScores(scores) {} char calculate() { int sum = 0; for(auto x: testScores) sum += x; sum /= testScores.size(); if(sum >= 90 && sum <= 100) return 'O'; if(sum >= 80 && sum < 90) return 'E'; if(sum >= 70 && sum < 80) return 'A'; if(sum >= 55 && sum < 70) return 'P'; if(sum >= 40 && sum < 55) return 'D'; return 'T'; } /* * Class Constructor * * Parameters: * firstName - A string denoting the Person's first name. * lastName - A string denoting the Person's last name. * id - An integer denoting the Person's ID number. * scores - An array of integers denoting the Person's test scores. */ // Write your constructor here /* * Function Name: calculate * Return: A character denoting the grade. */ // Write your function here }; int main() { string firstName; string lastName; int id; int numScores; cin >> firstName >> lastName >> id >> numScores; vector<int> scores; for(int i = 0; i < numScores; i++){ int tmpScore; cin >> tmpScore; scores.push_back(tmpScore); } Student* s = new Student(firstName, lastName, id, scores); s->printPerson(); cout << "Grade: " << s->calculate() << "\n"; return 0; } // Take a look at the calling function to Person Class constructor and the way testScores has been initialized
25.583333
135
0.564914
[ "vector" ]
a3325dda5a66999100c97fda55ac0fb9bd910cc7
3,117
cc
C++
chrome/browser/ui/browser_window_state_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/browser_window_state_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/ui/browser_window_state_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// 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/ui/browser_window_state.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/ui_base_types.h" #include "ui/gfx/geometry/rect.h" namespace chrome { namespace internal { namespace { constexpr int kDefaultWidth = 1920; constexpr int kDefaultHeight = 1200; constexpr int kDefaultOffsetX = 0; constexpr int kDefaultOffsetY = 0; constexpr ui::WindowShowState kDefaultShowState = ui::SHOW_STATE_MAXIMIZED; class BrowserWindowStateTest : public testing::Test { public: BrowserWindowStateTest() : bounds_(gfx::Point(kDefaultOffsetX, kDefaultOffsetY), gfx::Size(kDefaultWidth, kDefaultHeight)), show_state_(kDefaultShowState), command_line_(base::CommandLine::NO_PROGRAM) {} gfx::Rect bounds_; ui::WindowShowState show_state_; base::CommandLine command_line_; }; } // namespace TEST_F(BrowserWindowStateTest, NoCommandLineLeavesParamsIntact) { UpdateWindowBoundsAndShowStateFromCommandLine(command_line_, &bounds_, &show_state_); EXPECT_EQ(bounds_.x(), kDefaultOffsetX); EXPECT_EQ(bounds_.y(), kDefaultOffsetY); EXPECT_EQ(bounds_.width(), kDefaultWidth); EXPECT_EQ(bounds_.height(), kDefaultHeight); EXPECT_EQ(show_state_, kDefaultShowState); } TEST_F(BrowserWindowStateTest, InvalidCommandLineLeavesParamsIntact) { command_line_.AppendSwitchASCII(switches::kWindowSize, "0,abc"); command_line_.AppendSwitchASCII(switches::kWindowPosition, "invalid"); UpdateWindowBoundsAndShowStateFromCommandLine(command_line_, &bounds_, &show_state_); EXPECT_EQ(bounds_.x(), kDefaultOffsetX); EXPECT_EQ(bounds_.y(), kDefaultOffsetY); EXPECT_EQ(bounds_.width(), kDefaultWidth); EXPECT_EQ(bounds_.height(), kDefaultHeight); EXPECT_EQ(show_state_, kDefaultShowState); } TEST_F(BrowserWindowStateTest, WindowSizeOverridesShowState) { command_line_.AppendSwitchASCII(switches::kWindowSize, "100,200"); UpdateWindowBoundsAndShowStateFromCommandLine(command_line_, &bounds_, &show_state_); EXPECT_EQ(bounds_.x(), kDefaultOffsetX); EXPECT_EQ(bounds_.y(), kDefaultOffsetY); EXPECT_EQ(bounds_.width(), 100); EXPECT_EQ(bounds_.height(), 200); EXPECT_EQ(show_state_, ui::SHOW_STATE_NORMAL); } TEST_F(BrowserWindowStateTest, WindowPositionOverridesShowState) { command_line_.AppendSwitchASCII(switches::kWindowPosition, "100,200"); UpdateWindowBoundsAndShowStateFromCommandLine(command_line_, &bounds_, &show_state_); EXPECT_EQ(bounds_.x(), 100); EXPECT_EQ(bounds_.y(), 200); EXPECT_EQ(bounds_.width(), kDefaultWidth); EXPECT_EQ(bounds_.height(), kDefaultHeight); EXPECT_EQ(show_state_, ui::SHOW_STATE_NORMAL); } } // namespace internal } // namespace chrome
34.633333
75
0.730831
[ "geometry" ]
a3384ce0809efc70a0a7a68e0d41cb8994a78658
48,427
cpp
C++
Source/Editctrl/Editctrl.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
2
2022-02-11T11:59:44.000Z
2022-02-16T20:33:25.000Z
Source/Editctrl/Editctrl.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
Source/Editctrl/Editctrl.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
#include "all.h" #include "ectrl_i.h" #include "resource.h" //---------------------------- BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved){ switch(fdwReason){ case DLL_PROCESS_ATTACH: { WNDCLASS wc; memset(&wc, 0, sizeof(wc)); //register document window wc.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS; wc.lpfnWndProc = C_edit_control::dlgECProc; wc.hCursor = LoadCursor(NULL, IDC_IBEAM); wc.lpszClassName = "EC_WINDOW"; if(!RegisterClass(&wc)) return ECTRLERR_GENERIC; } break; case DLL_PROCESS_DETACH: UnregisterClass("EC_WINDOW", hinstDLL); break; } return true; } //---------------------------- bool ConvertMacros(const char *filename, short **cbuf); //---------------------------- C_key_code code_manager; C_clipboard clipboard; //---------------------------- static const struct{ word cmd; short code; } cmd_2_code[] = { //ID_FILE_NEW, NEWFILE, ID_FILE_OPEN, OPENFILE, // ID_FILE_CLOSE, CLOSEFILE, ID_FILE_SAVE, SAVEFILE, ID_FILE_SAVEAS, SAVEAS, // ID_FILE_SAVEALL, SAVEALL, ID_FILE_RELOAD, RELOADFILE, ID_FILE_READBLOCK,READBLOCK, ID_FILE_WRITEBLOCK, WRITEBLOCK, // ID_FILE_SAVEPROJECT, SAVEPROJECT, // ID_FILE_OPENPROJECT, OPENPROJECT, // ID_FILE_CLOSEPROJECT,CLOSEPROJECT, // ID_FILE_ADDTOPROJECT,ADDTOPROJECT, // ID_FILE_REMOVEFROMPROJECT, REMOVEFROMPROJECT, // ID_FILE_OSCOMMAND,OSSHELL, ID_FILE_EXIT, EXIT, ID_EDIT_CUT, CUT, ID_EDIT_COPY, COPY, ID_EDIT_PASTE, PASTE, ID_EDIT_DELETELINE, DELLINE, ID_EDIT_DUPLICATELINE, DUPLINE, // ID_EDIT_LOWER, LOWER, // ID_EDIT_UPPER, UPPER, // ID_EDIT_FLIP, FLIP, ID_EDIT_UNDO, UNDO, ID_EDIT_REDO, REDO, ID_SEARCH_FIND, FIND, ID_SEARCH_FINDANDREPLACE, FIND_REPLACE, ID_SEARCH_REPEATFINDREPLACE, REPEAT, ID_SEARCH_GOTOLINE, GOTOLINE, ID_SEARCH_GOTOCOLUMN, GOTOCOLUMN, ID_BLOCK_MARKLINE, MARKLINE, ID_BLOCK_MARKCOLUMN, MARKCOLUMN, ID_BLOCK_UNMARK, UNMARKBLOCK, ID_BLOCK_DELETE, DELETEBLOCK, ID_EDIT_DELTOEOL, DELTOEOL, 0 }; //---------------------------- static byte rgb_values_defaults[][3]={ 0,0,0, 0,0,170, 0,170,0, 0,170,170, 170,0,0, 170,0,170, 170,85,0, 170,170,170, 85,85,85, 85,85,255, 85,255,85, 85,255,255, 255,85,85, 255,85,255, 255,255,85, 255,255,255 }; //---------------------------- void SetModify(C_window *wp, int undo_buffer){ if(wp->doc.SetModify(true)){ SetWindowText(wp->ec->hwnd, C_fstr("* %s", (const char*)wp->doc.title)); //only undo 0 can set it if(!undo_buffer) wp->undo[0].Add(C_undo_element::FILEMODIFY); } } //---------------------------- dword C_edit_control::GetRGB(byte c, bool highl){ byte r=rgb_values[c][0]; byte g=rgb_values[c][1]; byte b=rgb_values[c][2]; int i; if(highl && (i=config.curr_line_highlight)!=100){ //adjust brightness if(i<100){ r=r*i/100; g=g*i/100; b=b*i/100; }else{ i-=100; r+=(255-r)*i/100; g+=(255-g)*i/100; b+=(255-b)*i/100; } } return RGB(r, g, b); } //---------------------------- static bool SavePrompt(C_window *wp, HWND hwnd_main){ if(wp->doc.modified){ //prompt for saving changes switch(MessageBox(hwnd_main, C_fstr("Save changes to %s?", (const char*)wp->doc.title), "HighWare editor", MB_YESNOCANCEL)){ case IDYES: if(!wp->Save()) return false; case IDNO: break; default: return false; } } return true; } //---------------------------- static void AdjustBlock(C_window *wp, bool shift_down, bool replay = 0){ if(replay && wp->block.IsCUA()) return; int i = wp->block.Adjust(wp, shift_down, wp->cursor.x, wp->cursor.y, wp->cursor.prv_x, wp->cursor.prv_y); if(i&2) wp->doc.redraw = true; if(i&1) wp->doc.redraw_line = true; } //---------------------------- bool PutCh(C_window*, char c); //---------------------------- static void MinimizeLine(C_window *wp){ if(wp->ec->read_only) return; int line = wp->cursor.y; if(line>=wp->doc.linenum) return; C_document_line *lp=wp->doc.lines[line]; lp->RemoveTrailingSpaces(); wp->doc.ReplaceLine(wp->cursor.y, lp->Minimize()); } //---------------------------- void C_edit_control::InitScrollBar(){ //setup scroll-bar int fsx, fsy; GetFontSize(&fsx, &fsy); RECT rc; GetClientRect(win.hwnd, &rc); int num_l = (rc.bottom-rc.top) / fsy; SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_RANGE | SIF_POS | SIF_PAGE; si.nPage = num_l; si.nMin = 0; si.nMax = win.doc.linenum; si.nPos = win.scroll_y; SetScrollInfo(win.hwnd, SB_VERT, &si, true); } //---------------------------- bool SetCursorPos1(C_window *wp, int x, int y, int undo_buff){ x = Max(0, Min(x, MAX_ROWS)); y = Max(0, Min(y, (int)wp->doc.linenum-1)); if(wp->cursor.x!=x || wp->cursor.y!=y){ //add position into undo buffer wp->undo[undo_buff].Add(C_undo_element::POSITION, wp->cursor.x, wp->cursor.y); wp->cursor.x = x; if(wp->cursor.y!=y){ MinimizeLine(wp); //un-highlight previous line SendMessage(wp->hwnd, WM_USER_PAINTLINE, wp->cursor.y, 0); wp->cursor.y = y; //highlight new current line SendMessage(wp->hwnd, WM_USER_PAINTLINE, wp->cursor.y, 1); } wp->cursor.redraw = true; return true; } return false; } //---------------------------- void SetCursorVisible(C_window *wp, HWND hwnd){ RECT rc; GetClientRect(hwnd, &rc); int fsx, fsy; wp->ec->GetFontSize(&fsx, &fsy); int sx=rc.right/fsx; int sy=rc.bottom/fsy; if(wp->cursor.x >= sx+wp->scroll_x){ wp->SetScrollPos(wp->cursor.x-sx+1, wp->scroll_y); } if(wp->cursor.x < wp->scroll_x){ wp->SetScrollPos(wp->cursor.x, wp->scroll_y); } if(wp->cursor.y >= sy+wp->scroll_y){ wp->SetScrollPos(wp->scroll_x, wp->cursor.y-sy+1); } if(wp->cursor.y < wp->scroll_y){ wp->SetScrollPos(wp->scroll_x, wp->cursor.y); } } //---------------------------- void C_edit_control::SetState(E_state s, const char *msg){ state = s; state_message = msg; } //---------------------------- E_state C_edit_control::CheckState(){ C_str str; switch(state){ case STATE_MESSAGE: str = state_message; break; case STATE_WARNING: str = C_fstr("Warning: %s", (const char*)state_message); break; case STATE_ERROR: str = C_fstr("Error: %s", (const char*)state_message); break; default: SendMessage(hwnd_sb, SB_SETTEXT, 1, (LPARAM)NULL); return STATE_OK; } SendMessage(hwnd_sb, SB_SETTEXT, 1, (LPARAM)(const char*)str); E_state r = state; state = STATE_OK; return r; } //---------------------------- void C_edit_control::DrawLineColumn(){ SendMessage(hwnd_sb, SB_SETTEXT, 0, (LPARAM)(const char*)C_fstr("L: %i C: %i", win.cursor.y + 1, win.cursor.x + 1)); } //---------------------------- static const char CODE_CONVERT[]={ VK_PRIOR, VK_NEXT, VK_END, VK_HOME, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_SNAPSHOT, VK_INSERT, VK_DELETE, /*VK_MULTIPLY, VK_ADD, VK_SEPARATOR, VK_SUBTRACT, VK_DIVIDE, */VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12, (byte)VK_NUMLOCK, (byte)VK_SCROLL, (byte)219, (byte)221, (byte)186, (byte)222, (byte)189, (byte)187, (byte)220, (byte)188, (byte)190, (byte)191, 111, 106, 109, 107, (byte)192, 0 }; static const byte CODE_CONVERT1[]={ K_PAGEUP, K_PAGEDOWN, K_END, K_HOME, K_CURSORLEFT, K_CURSORUP, K_CURSORRIGHT, K_CURSORDOWN, K_PRTSCR, K_INS, K_DEL, /*K_GREYMULT, K_GREYPLUS, K_CENTER, K_GREYMINUS, K_GREYSLASH, */K_F1, K_F2, K_F3, K_F4, K_F5, K_F6, K_F7, K_F8, K_F9, K_F10, K_F11, K_F12, K_NUMLOCK, K_SCROLLLOCK, '[', ']', ';', '\'', '-', '=', '\\', ',', '.', '/', 111, 106, 109, 107, '`', }; //---------------------------- static LOGFONT font_log_defaults = { 12, 8, 0, 0, 0, 0, 0, 0, OEM_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH, "Terminal" }; //---------------------------- //default config static S_config config_defaults = { 3, //tab false, //overwrite mode {6, 2, 0, 7}, //cursor shape "{}[]().=+-*/:;<>|&,~!^?#", 24, //symbols "/*", 2, //comment beg "*/", 2, //comment end "//", 2, //comment eol "\"'", 2, //string '\\', //literal 125, //curr line highlight [%] false, //underline cursor 0, //reserved { //colors (BLUE<<4) | LIGHT_CYAN, //CLR_DEFAULT (BLUE<<4) | YELLOW, //CLR_NUMBER (BLUE<<4) | LIGHT_RED, //CLR_STRING (BLUE<<4) | GREY, //CLR_SYMBOLS (BLUE<<4) | GREEN, //CLR_COMMENT (BLUE<<4) | LIGHT_PURPUR, //CLR_RESERVED1 (BLUE<<4) | LIGHT_GREEN, //CLR_RESERVED2 (BLUE<<4) | LIGHT_BLUE, //CLR_RESERVED3 (BLACK<<4) | YELLOW, //CLR_BLOCK (BLACK<<4) | WHITE, //CLR_FIND }, }; //---------------------------- void C_edit_control::MakeCaret(){ int fsx, fsy; GetFontSize(&fsx, &fsy); int x = (win.cursor.x-win.scroll_x)*fsx; int y = (win.cursor.y-win.scroll_y)*fsy; //offset by frame size int fs = GetSystemMetrics(SM_CXEDGE); x += fs; y += fs; if(HideCaret(hwnd)) DestroyCaret(); int sx=fsx, sy=fsy; if(!win.overwrite) if(config.underline_cursor){ sy = Max(2, GetSystemMetrics(SM_CXBORDER)); y += fsy-sy; }else sx = Max(2, GetSystemMetrics(SM_CXBORDER)); CreateCaret(hwnd, NULL, sx, sy); SetCaretPos(x, y); ShowCaret(hwnd); } //---------------------------- void C_edit_control::SizeWindow(){ RECT rc; GetClientRect(hwnd, &rc); //subtract status-bar if(hwnd_sb){ RECT rc1; GetClientRect(hwnd_sb, &rc1); rc.bottom -= (rc1.bottom-rc1.top); } MoveWindow(win.hwnd, 0, 0, (rc.right-rc.left), (rc.bottom-rc.top), true); InitScrollBar(); } //---------------------------- static unsigned int CALLBACK FontChooseHook(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ switch(uMsg){ case WM_INITDIALOG: { CHOOSEFONT *cf = (CHOOSEFONT*)lParam; SetWindowLong(hwnd, GWL_USERDATA, cf->lCustData); } break; case WM_COMMAND: switch(LOWORD(wParam)){ case 0x402: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); ec->font_sy = -1; if(ec->fnt){ DeleteObject(ec->fnt); ec->fnt = NULL; } SendMessage(hwnd, WM_CHOOSEFONT_GETLOGFONT, 0, (LPARAM)&ec->curr_font_log); PostMessage(ec->win.hwnd, WM_USER_PAINTWHOLE, 0, 0); ec->InitScrollBar(); } break; } break; } return 0; } //---------------------------- static BOOL CALLBACK DlgColors(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ static char COLOR_TEXT[] = { "Default\0" "Number\0" "String\0" "Symbol\0" "Comment\0" "Keyword 1\0" "Keyword 2\0" "Keyword 3\0" "Keyword 4\0" "Block\0" "Find\0" }; int i; static byte (*s_rgb_values)[3]; static byte *s_colors; switch(uMsg){ case WM_INITDIALOG: { C_edit_control *ec = (C_edit_control*)lParam; SetWindowLong(hwnd, GWL_USERDATA, (LPARAM)ec); //center RECT rc, rc1; GetWindowRect(ec->hwnd, &rc1); GetWindowRect(hwnd, &rc); SetWindowPos(hwnd, 0, ((rc1.right-rc1.left)-(rc.right-rc.left))/2+rc1.left, ((rc1.bottom-rc1.top)-(rc.bottom-rc.top))/2+rc1.top, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER); s_rgb_values = new byte[16][3]; memcpy(s_rgb_values, ec->rgb_values, sizeof(ec->rgb_values)); s_colors = new byte[CLR_LAST]; memcpy(s_colors, ec->config.colors, CLR_LAST); char *cp = COLOR_TEXT; for(i=0; i<CLR_LAST; i++){ SendDlgItemMessage(hwnd, IDC_LIST1, LB_ADDSTRING, 0, (LPARAM)cp); cp += strlen(cp) + 1; } for(i=0; i<16; i++){ SendDlgItemMessage(hwnd, IDC_COMBO_COLOR_FORE, CB_ADDSTRING, 0, (LPARAM)""); SendDlgItemMessage(hwnd, IDC_COMBO_COLOR_BACK, CB_ADDSTRING, 0, (LPARAM)""); } SendDlgItemMessage(hwnd, IDC_LIST1, LB_SETCURSEL, 0, 0); SendDlgItemMessage(hwnd, IDC_COMBO_COLOR_FORE, CB_SETCURSEL, s_colors[0]&15, 0); SendDlgItemMessage(hwnd, IDC_COMBO_COLOR_BACK, CB_SETCURSEL, s_colors[0]>>4, 0); } return 1; case WM_DRAWITEM: DRAWITEMSTRUCT *dis; dis=(DRAWITEMSTRUCT*)lParam; if(dis->CtlType==ODT_COMBOBOX){ HDC hdc=dis->hDC; i=dis->itemID; COLORREF cr=RGB(s_rgb_values[i][0], s_rgb_values[i][1], s_rgb_values[i][2]); HBRUSH hb, hb1; hb1 = (HBRUSH)SelectObject(hdc, hb = CreateSolidBrush(cr)); HPEN hp, hp1; if(dis->itemState&ODS_SELECTED) hp1 = (HPEN)SelectObject(hdc, hp=CreatePen(PS_DOT, 1, cr^0xffffff)); else hp1 = (HPEN)SelectObject(hdc, hp=CreatePen(PS_SOLID, 1, cr)); Rectangle(hdc, dis->rcItem.left, dis->rcItem.top, dis->rcItem.right, dis->rcItem.bottom); SelectObject(hdc, hb1); SelectObject(hdc, hp1); DeleteObject(hb); DeleteObject(hp); } break; case WM_CTLCOLORSTATIC: if(((HWND)lParam)==GetDlgItem(hwnd, IDC_STATIC_SAMPLE)){ HDC hdc=(HDC)wParam; i=SendDlgItemMessage(hwnd, IDC_COMBO_COLOR_FORE, CB_GETCURSEL, 0, 0); SetTextColor(hdc, RGB(s_rgb_values[i][0], s_rgb_values[i][1], s_rgb_values[i][2])); i=SendDlgItemMessage(hwnd, IDC_COMBO_COLOR_BACK, CB_GETCURSEL, 0, 0); SetBkColor(hdc, RGB(s_rgb_values[i][0], s_rgb_values[i][1], s_rgb_values[i][2])); return (int)CreateSolidBrush(RGB(s_rgb_values[i][0], s_rgb_values[i][1], s_rgb_values[i][2])); } break; case WM_COMMAND: switch(LOWORD(wParam)){ case IDC_LIST1: switch(HIWORD(wParam)){ case LBN_SELCHANGE: i = SendDlgItemMessage(hwnd, IDC_LIST1, LB_GETCURSEL, 0, 0); SendDlgItemMessage(hwnd, IDC_COMBO_COLOR_FORE, CB_SETCURSEL, s_colors[i]&15, 0); SendDlgItemMessage(hwnd, IDC_COMBO_COLOR_BACK, CB_SETCURSEL, s_colors[i]>>4, 0); char *cp=new char[64]; SendDlgItemMessage(hwnd, IDC_STATIC_SAMPLE, WM_GETTEXT, 64, (LPARAM)cp); SendDlgItemMessage(hwnd, IDC_STATIC_SAMPLE, WM_SETTEXT, 0, (LPARAM)cp); delete[] cp; break; } break; case IDC_COMBO_COLOR_FORE: case IDC_COMBO_COLOR_BACK: switch(HIWORD(wParam)){ case CBN_SELENDOK: //redraw sample char *cp=new char[64]; SendDlgItemMessage(hwnd, IDC_STATIC_SAMPLE, WM_GETTEXT, 64, (LPARAM)cp); SendDlgItemMessage(hwnd, IDC_STATIC_SAMPLE, WM_SETTEXT, 0, (LPARAM)cp); delete[] cp; //get current color item i=SendDlgItemMessage(hwnd, IDC_LIST1, LB_GETCURSEL, 0, 0); int clr; //get selected color clr=SendDlgItemMessage(hwnd, LOWORD(wParam), CB_GETCURSEL, 0, 0); //set fore or back if(LOWORD(wParam)==IDC_COMBO_COLOR_FORE) s_colors[i]=(s_colors[i]&0xf0)|clr; else s_colors[i]=(s_colors[i]&0xf)|(clr<<4); break; } break; case ID_COLOR_EDIT_FORE: case ID_COLOR_EDIT_BACK: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); bool fore; fore = LOWORD(wParam)==ID_COLOR_EDIT_FORE; i = SendDlgItemMessage(hwnd, fore ? IDC_COMBO_COLOR_FORE : IDC_COMBO_COLOR_BACK, CB_GETCURSEL, 0, 0); CHOOSECOLOR cc; memset(&cc, 0, sizeof(cc)); cc.lStructSize = sizeof(cc); cc.hwndOwner = hwnd; cc.hInstance = (HWND)ec->hi; cc.rgbResult = s_rgb_values[i][0] | (s_rgb_values[i][1]<<8) | (s_rgb_values[i][2]<<16); cc.lpCustColors = ec->custom_colors; cc.Flags = CC_RGBINIT | CC_FULLOPEN; if(ChooseColor(&cc)){ s_rgb_values[i][0] = (cc.rgbResult )&255; s_rgb_values[i][1] = (cc.rgbResult>>8 )&255; s_rgb_values[i][2] = (cc.rgbResult>>16)&255; SetFocus(GetDlgItem(hwnd, fore ? IDC_COMBO_COLOR_BACK : IDC_COMBO_COLOR_FORE)); SetFocus(GetDlgItem(hwnd, fore ? IDC_COMBO_COLOR_FORE : IDC_COMBO_COLOR_BACK)); char *cp = new char[64]; SendDlgItemMessage(hwnd, IDC_STATIC_SAMPLE, WM_GETTEXT, 64, (LPARAM)cp); SendDlgItemMessage(hwnd, IDC_STATIC_SAMPLE, WM_SETTEXT, 0, (LPARAM)cp); delete[] cp; ec->config_changed = true; } } break; case IDAPPLY: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); memcpy(ec->rgb_values, s_rgb_values, sizeof(ec->rgb_values)); memcpy(ec->config.colors, s_colors, CLR_LAST); PostMessage(ec->win.hwnd, WM_USER_PAINTWHOLE, 0, 0); } break; case IDOK: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); memcpy(ec->rgb_values, s_rgb_values, sizeof(ec->rgb_values)); memcpy(ec->config.colors, s_colors, CLR_LAST); ec->config_changed = true; delete[] s_rgb_values; delete[] s_colors; EndDialog(hwnd, 1); } break; case IDCANCEL: delete[] s_rgb_values; delete[] s_colors; EndDialog(hwnd, 0); break; } break; } return 0; } //---------------------------- static BOOL CALLBACK DlgConfig(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ char line[128]; int i, j; static const int IDC_KEYWORD[] = { IDC_LIST_KEYWORDS1, IDC_LIST_KEYWORDS2, IDC_LIST_KEYWORDS3, IDC_LIST_KEYWORDS4 }; static int curr_lb; switch(uMsg){ case WM_INITDIALOG: { C_edit_control *ec = (C_edit_control*)lParam; SetWindowLong(hwnd, GWL_USERDATA, (LPARAM)ec); //center RECT rc, rc1; GetWindowRect(ec->hwnd, &rc1); GetWindowRect(hwnd, &rc); SetWindowPos(hwnd, 0, ((rc1.right-rc1.left)-(rc.right-rc.left))/2+rc1.left, ((rc1.bottom-rc1.top)-(rc.bottom-rc.top))/2+rc1.top, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER); SetDlgItemInt(hwnd, IDC_EDIT_TABWIDTH, ec->config.tab_width, 0); SetDlgItemText(hwnd, IDC_EDIT_STRING, ec->config.string); SetDlgItemText(hwnd, IDC_EDIT_EOLCOMMENT, ec->config.eol_comm); SetDlgItemText(hwnd, IDC_EDIT_COMMENTSTART, ec->config.open_comm); SetDlgItemText(hwnd, IDC_EDIT_COMMENTEND, ec->config.close_comm); SetDlgItemText(hwnd, IDC_EDIT_SYMBOLS, ec->config.symbols); line[0] = ec->config.literal; line[1] = 0; SetDlgItemText(hwnd, IDC_EDIT_LITERAL, line); SetDlgItemInt(hwnd, IDC_EDIT_LINEHIGHL, ec->config.curr_line_highlight, 0); int i; for(i=0; i<4; i++){ SendDlgItemMessage(hwnd, IDC_RESERVED_TYPES, CB_ADDSTRING, 0, (LPARAM)(const char*)C_fstr("Reserved %i", i+1)); } SendDlgItemMessage(hwnd, IDC_RESERVED_TYPES, CB_SETCURSEL, 0, 0); ShowWindow(GetDlgItem(hwnd, IDC_LIST_KEYWORDS1), SW_SHOW); SendDlgItemMessage(hwnd, IDC_LIST_KEYWORDS1, LB_SETCURSEL, 0, 0); CheckDlgButton(hwnd, IDC_CHECK_CURSORUNDER, ec->config.underline_cursor); for(j=0; j<4; j++) for(i=0; i<(int)ec->reserved_word[j].size(); i++) SendDlgItemMessage(hwnd, IDC_KEYWORD[j], LB_ADDSTRING, 0, (LPARAM)(const char*)ec->reserved_word[j][i]); curr_lb = 0; } return 1; case WM_COMMAND: switch(LOWORD(wParam)){ case IDC_EDIT_KEYWORD: switch(HIWORD(wParam)){ case EN_CHANGE: i=SendDlgItemMessage(hwnd, IDC_EDIT_KEYWORD, EM_LINELENGTH, 0, 0); EnableWindow(GetDlgItem(hwnd, IDC_BUTTON_ADD), !!i); break; } break; case IDC_BUTTON_ADD: { GetDlgItemText(hwnd, IDC_EDIT_KEYWORD, line, 127); SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_ADDSTRING, 0, (LPARAM)line); } break; case IDC_RESERVED_TYPES: switch(HIWORD(wParam)){ case CBN_SELENDOK: i = curr_lb; curr_lb=SendDlgItemMessage(hwnd, IDC_RESERVED_TYPES, CB_GETCURSEL, 0, 0); ShowWindow(GetDlgItem(hwnd, IDC_KEYWORD[i]), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_KEYWORD[curr_lb]), SW_SHOW); break; } break; case IDC_LIST_KEYWORDS1: case IDC_LIST_KEYWORDS2: case IDC_LIST_KEYWORDS3: switch(HIWORD(wParam)){ case LBN_SELCHANGE: { i = SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_GETCURSEL, 0, 0); SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_GETTEXT, i, (LPARAM)line); SendDlgItemMessage(hwnd, IDC_EDIT_KEYWORD, WM_SETTEXT, 0, (LPARAM)line); } break; case LBN_SETFOCUS: EnableWindow(GetDlgItem(hwnd, IDC_BUTTON_DELETE), 1); break; } break; case IDC_BUTTON_DELETE: i=SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_GETCURSEL, 0, 0); SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_DELETESTRING, i, 0); j=SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_GETCOUNT, 0, 0); if(!j) EnableWindow(GetDlgItem(hwnd, IDC_BUTTON_DELETE), 0); else{ i=min(i, j-1); SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_SETCURSEL, i, 0); } break; case IDCANCEL: EndDialog(hwnd, -1); break; case IDOK: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); ec->config.tab_width= GetDlgItemInt (hwnd, IDC_EDIT_TABWIDTH, NULL, 0); ec->config.string_len= GetDlgItemText(hwnd, IDC_EDIT_STRING, ec->config.string, 7); ec->config.eol_comm_len= GetDlgItemText(hwnd, IDC_EDIT_EOLCOMMENT, ec->config.eol_comm, 7); ec->config.open_comm_len= GetDlgItemText(hwnd, IDC_EDIT_COMMENTSTART, ec->config.open_comm, 7); ec->config.close_comm_len= GetDlgItemText(hwnd, IDC_EDIT_COMMENTEND, ec->config.close_comm, 7); ec->config.symbols_len= GetDlgItemText(hwnd, IDC_EDIT_SYMBOLS, ec->config.symbols, 127); i=GetDlgItemInt(hwnd, IDC_EDIT_LINEHIGHL, NULL, 0); ec->config.curr_line_highlight=max(1, min(200, i)); i=GetDlgItemText(hwnd, IDC_EDIT_LITERAL, line, 2); ec->config.literal= i ? line[0] : 0; ec->config.underline_cursor=IsDlgButtonChecked(hwnd, IDC_CHECK_CURSORUNDER); //collect reserved words for(curr_lb = 0; curr_lb<4; curr_lb++){ int count = SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_GETCOUNT, 0, 0); char buf[256]; ec->reserved_word[curr_lb].clear(); for(j=0; j<count; j++){ SendDlgItemMessage(hwnd, IDC_KEYWORD[curr_lb], LB_GETTEXT, j, (LPARAM)buf); ec->reserved_word[curr_lb].push_back(buf); } } EndDialog(hwnd, 1); } break; } break; } return 0; } //---------------------------- static BOOL CALLBACK DlgAbout(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ switch(uMsg){ case WM_INITDIALOG: { RECT rc, rc1; C_edit_control *ec = (C_edit_control*)lParam; //center GetWindowRect(ec->hwnd, &rc1); GetWindowRect(hwnd, &rc); SetWindowPos(hwnd, 0, ((rc1.right-rc1.left)-(rc.right-rc.left))/2+rc1.left, ((rc1.bottom-rc1.top)-(rc.bottom-rc.top))/2+rc1.top, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER); } return 1; case WM_COMMAND: switch(LOWORD(wParam)){ case IDOK: EndDialog(hwnd, 1); break; } break; } return 0; } //---------------------------- BOOL CALLBACK C_edit_control::dlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ switch(uMsg){ case WM_INITDIALOG: { C_edit_control *ec = (C_edit_control*)lParam; SetWindowLong(hwnd, GWL_USERDATA, lParam); SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER); //init status bar ec->hwnd_sb = CreateStatusWindow( SBARS_SIZEGRIP | WS_VISIBLE | WS_CHILD, NULL, hwnd, 0 ); static int pw[2] = {70, -1}; SendMessage(ec->hwnd_sb, SB_SETPARTS, 2, (LPARAM)pw); { HICON hc = LoadIcon(GetModuleHandle(DLL_NAME), MAKEINTRESOURCE(IDI_ICON3)); SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hc); SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hc); } } return 1; case WM_ACTIVATE: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); C_window *wp = &ec->win; switch(LOWORD(wParam)){ case WA_INACTIVE: HideCaret(hwnd); break; default: ec->MakeCaret(); } if(wp){ ec->DrawLineColumn(); wp->cursor.redraw = true; } } break; case WM_SIZE: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); //C_window *wp = &ec->win; ec->SizeWindow(); if(ec->hwnd_sb) SendMessage(ec->hwnd_sb, uMsg, wParam, lParam); } break; case WM_COMMAND: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); C_window *wp = &ec->win; short wID = LOWORD(wParam); switch(wID){ default: case ID_FILE_OPEN: case ID_FILE_EXIT: { ec->AddRef(); int i = 0; do{ if(cmd_2_code[i].cmd==wID){ code_manager.edit_functions[cmd_2_code[i].code-FIRST_COMMAND](wp); if(wp) wp->undo[0].Add(C_undo_element::MARK); break; } }while(cmd_2_code[++i].cmd); ec->Redraw(); ec->Release(); } break; //OPTIONS case ID_OPTIONS_FONT: { LOGFONT lf; memcpy(&lf, &ec->curr_font_log, sizeof(lf)); CHOOSEFONT cf; memset(&cf, 0, sizeof(cf)); cf.lStructSize = sizeof(cf); cf.hwndOwner = hwnd; cf.lpLogFont = &lf; cf.Flags = CF_FIXEDPITCHONLY | CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT | CF_APPLY | CF_SCREENFONTS | CF_ENABLEHOOK; cf.nFontType = SCREEN_FONTTYPE; cf.lpfnHook = FontChooseHook; cf.lCustData = (LPARAM)ec; if(ChooseFont(&cf)){ DestroyCaret(); memcpy(&ec->curr_font_log, &lf, sizeof(LOGFONT)); ec->font_sy = -1; if(ec->fnt){ DeleteObject(ec->fnt); ec->fnt = NULL; } PostMessage(ec->win.hwnd, WM_USER_PAINTWHOLE, 0, 0); ec->MakeCaret(); ec->InitScrollBar(); ec->config_changed = true; } } break; case ID_OPTIONS_COLORS: if(DialogBoxParam(ec->hi, "IDD_DIALOG_COLORS", hwnd, (DLGPROC)DlgColors, (LPARAM)ec)){ DestroyCaret(); PostMessage(ec->win.hwnd, WM_USER_PAINTWHOLE, 0, 0); ec->MakeCaret(); } break; case ID_OPTIONS_CONFIG: { int i = DialogBoxParam(ec->hi, "IDD_DIALOG_CONFIG", hwnd, (DLGPROC)DlgConfig, (LPARAM)ec); if(i!=-1){ ec->win.doc.CheckComments(&ec->config, 0, 0, 1, 1); PostMessage(ec->win.hwnd, WM_USER_PAINTWHOLE, 0, 0); } ec->config_changed = true; } break; case ID_HELP_ABOUT: DialogBoxParam(ec->hi, "IDD_DIALOG_ABOUT", ec->hwnd, (DLGPROC)DlgAbout, (LPARAM)ec); break; } } break; case WM_CLOSE: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); if(ec){ C_window *wp = &ec->win; if(!SavePrompt(wp, hwnd)) return 0; DestroyWindow(wp->hwnd); wp->hwnd = NULL; DestroyWindow(hwnd); EndDialog(hwnd, 0); return 0; } } break; case WM_DESTROY: { C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); if(ec){ ec->AddRef(); if(ec->cb_proc) (*ec->cb_proc)("close", ec->cb_context); ec->hwnd = NULL; SetWindowLong(hwnd, GWL_USERDATA, 0); ec->Release(); } } break; } return 0; } //---------------------------- long CALLBACK C_edit_control::dlgECProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ C_edit_control *ec = (C_edit_control*)GetWindowLong(hwnd, GWL_USERDATA); static bool hwnd_lbut_down; switch(uMsg){ case WM_CREATE: { CREATESTRUCT *cs = (CREATESTRUCT*)lParam; SetWindowLong(hwnd, GWL_ID, 1); SetWindowLong(hwnd, GWL_USERDATA, (long)cs->lpCreateParams); } break; case WM_DESTROYCLIPBOARD: return !clipboard.Destroy(); case WM_ERASEBKGND: return 1; case WM_PAINT: HideCaret(ec->hwnd); if(!ec) return 0; ec->win.doc.redraw = false; ec->win.doc.Paint(ec, ec->win.scroll_x, ec->win.scroll_y, &ec->win.block, ec->win.cursor.y, hwnd, ec->win.cursor.y); if(ec->win.hwnd==GetFocus()) ec->MakeCaret(); break; case WM_USER_PAINTLINE: HideCaret(ec->hwnd); ec->win.doc.redraw_line=0; if(wParam < (dword)ec->win.doc.linenum){ ec->win.doc.PaintLine(ec, ec->win.scroll_x, ec->win.scroll_y, &ec->win.block, wParam, hwnd, lParam); } if(ec->win.hwnd==GetFocus()) ec->MakeCaret(); break; case WM_USER_MOVECURSOR: if(ec->win.hwnd==GetFocus()) ec->MakeCaret(); ec->win.cursor.redraw = false; break; case WM_LBUTTONDOWN: { int fsx, fsy; ec->GetFontSize(&fsx, &fsy); SetCursorPos1(&ec->win, ec->win.scroll_x+LOWORD(lParam)/fsx, ec->win.scroll_y+HIWORD(lParam)/fsy); ec->win.cursor.redraw = true; if(ec->win.block.IsCUA()) code_manager.edit_functions[UNMARKBLOCK-FIRST_COMMAND](&ec->win); SetCapture(hwnd); ec->win.cursor.SavePos(); hwnd_lbut_down = true; ec->Redraw(); } break; case WM_VSCROLL: { static bool inside; if(!inside){ inside = true; C_window *wp = &ec->win; int scy = wp->scroll_y; int cy = wp->cursor.y; int delta_y = cy-scy; switch(LOWORD(wParam)){ case SB_LINEDOWN: ++scy; break; case SB_LINEUP: --scy; break; case SB_THUMBTRACK: SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_TRACKPOS; GetScrollInfo(hwnd, SB_VERT, &si); scy = si.nTrackPos; break; case SB_PAGEDOWN: scy += 10; break; case SB_PAGEUP: scy -= 10; break; } scy = Max(0, Min(wp->doc.linenum-1, scy)); cy = scy + delta_y; cy = Max(0, Min(wp->doc.linenum-1, cy)); wp->SetScrollPos(wp->scroll_x, scy); SetCursorPos1(wp, wp->cursor.x, cy); SendMessage(hwnd, WM_PAINT, 0, 0); inside = false; } } break; case WM_LBUTTONUP: ReleaseCapture(); hwnd_lbut_down = false; break; case WM_LBUTTONDBLCLK: { code_manager.edit_functions[MARKWORD-FIRST_COMMAND](&ec->win); ec->Redraw(); } break; /* case WM_RBUTTONDOWN: if(ec){ TV_HITTESTINFO thti; int i = GetMessagePos(); thti.pt.x = LOWORD(i); thti.pt.y = HIWORD(i); ScreenToClient(GetDlgItem(hwnd, IDC_TREE_PROJECT), &thti.pt); ec->ContextMenu(LOWORD(i), HIWORD(i)); } break; */ case WM_MOUSEMOVE: if(hwnd_lbut_down && (wParam&MK_LBUTTON)){ int fsx, fsy; ec->GetFontSize(&fsx, &fsy); int x = (short)LOWORD(lParam), y = (short)HIWORD(lParam); x = x / fsx + ec->win.scroll_x; y = y / fsy + ec->win.scroll_y; x = Max(0, x); y = Max(0, y); SetCursorPos1(&ec->win, x, y); ec->win.cursor.redraw = true; AdjustBlock(&ec->win, 1, 0); ec->Redraw(); } break; case WM_GETDLGCODE : return DLGC_WANTALLKEYS | DLGC_WANTARROWS | DLGC_WANTCHARS | DLGC_WANTMESSAGE | DLGC_WANTTAB; case WM_CHAR: if(wParam==127) break; if(wParam<' ') break; if(ec) ec->ProcessInput(uMsg, wParam, lParam); break; case WM_KEYDOWN: if(wParam==VK_APPS){ if(ec){ RECT rc; GetWindowRect(hwnd, &rc); int fsx, fsy; ec->GetFontSize(&fsx, &fsy); ec->ContextMenu(rc.left + fsx*(ec->win.cursor.x-ec->win.scroll_x+1), rc.top + fsy*(ec->win.cursor.y-ec->win.scroll_y+1)); } break; } //flow... case WM_SYSKEYDOWN: if(ec){ //keep rerefence, because class may be released during the call ec->AddRef(); ec->ProcessInput(uMsg, wParam, lParam); ec->Release(); } break; case WM_SYSCHAR: return 0; } return DefWindowProc(hwnd, uMsg, wParam, lParam); } //---------------------------- void C_edit_control::ContextMenu(int x, int y){ int i; HMENU hmenu; hmenu = LoadMenu(hi, "MENU_CONTEXT"); i = TrackPopupMenu(GetSubMenu(hmenu,0), TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_RETURNCMD, x, y, 0, hwnd, NULL); DestroyMenu(hmenu); switch(i){ case -1: break; default: SendMessage(hwnd, WM_COMMAND, i, (LPARAM)hwnd); Redraw(); } } //---------------------------- C_edit_control::C_edit_control(): ref(1), user_macros(NULL), read_only(false), hi(NULL), state(STATE_OK), fnt(NULL), config_changed(false), cb_proc(NULL), cb_context(NULL), user_data(0), curr_HDC_color(-1), font_sx(-1), font_sy(-1), hwnd(NULL) { win.ec = this; memset(&config, 0, sizeof(config)); } //---------------------------- C_edit_control::~C_edit_control(){ Close(true); if(cb_proc) (*cb_proc)("exit", cb_context); } //---------------------------- ECTRL_RESULT C_edit_control::Init(const char *macro_file, const char *cfg_file1){ hi = GetModuleHandle(DLL_NAME); if(macro_file) { //init macro file if(!ConvertMacros(macro_file, &user_macros)){ return ECTRLERR_MACROOPENFAIL; } } cfg_file = NULL; { //reset config memcpy(&config, &config_defaults, sizeof(S_config)); memcpy(&curr_font_log, &font_log_defaults, sizeof(font_log_defaults)); memcpy(&rgb_values, &rgb_values_defaults, sizeof(rgb_values_defaults)); memset(&custom_colors, 0, sizeof(custom_colors)); for(int i=0; i<4; i++) reserved_word[i].clear(); } if(cfg_file1){ cfg_file = cfg_file1; C_cache ck; if(!ck.open(cfg_file, CACHE_READ)) return ECTRLERR_CONFIGOPENFAIL; //config ck.read((char*)&config, sizeof(config)); //font log ck.read((char*)&curr_font_log, sizeof(curr_font_log)); //colors ck.read((char*)&rgb_values, sizeof(rgb_values)); //keywords for(int i=0; i<4; i++){ char buf[256]; while(true){ ck.getline(buf, sizeof(buf), 0); if(!buf[0]) break; reserved_word[i].push_back(buf); } } ck.close(); } win.overwrite = config.overwrite; return ECTRL_OK; } //---------------------------- ECTRL_RESULT C_edit_control::Close(bool save_cfg){ ECTRL_RESULT er = ECTRL_OK; /* if(win.doc.modified){ if(!win.Save()) return ECTRLERR_SAVEFAILED; er = ECTRL_MODIFIED; win.doc.Close(); } */ win.doc.Close(); if(save_cfg && cfg_file.Size() && config_changed){ C_cache ck; ck.open(cfg_file, CACHE_WRITE); //write config ck.write((char*)&config, sizeof(config)); //write font log ck.write((char*)&curr_font_log, sizeof(curr_font_log)); //write colors ck.write((char*)&rgb_values, sizeof(rgb_values)); //write keywords for(int i=0; i<4; i++){ for(dword j=0; j<reserved_word[i].size(); j++){ ck.write((const char*)reserved_word[i][j], reserved_word[i][j].Size()+1); } char b = 0; ck.write(&b, sizeof(char)); } ck.close(); } if(hwnd){ SetWindowLong(hwnd, GWL_USERDATA, 0); DestroyWindow(hwnd); hwnd = NULL; } return er; } //---------------------------- ECTRL_RESULT C_edit_control::Save(bool prompt){ ECTRL_RESULT er = ECTRL_OK; if(win.doc.modified){ if(prompt){ switch(MessageBox(hwnd, C_fstr("Save changes to %s?", (const char*)win.doc.title), NULL, MB_YESNOCANCEL)){ case IDYES: if(!win.Save()) return ECTRLERR_SAVEFAILED; er = ECTRL_MODIFIED; break; case IDNO: break; case IDCANCEL: return ECTRLERR_SAVEFAILED; } } } return er; } //---------------------------- ECTRL_RESULT C_edit_control::Open(const char *filename, void *hwnd_parent, dword flags, void **ret_hwnd, const int pos_size[4]){ C_cache ck; if(!ck.open(filename, CACHE_READ)) return ECTRLERR_OPENFAILED; return Open(&ck, filename, hwnd_parent, flags, ret_hwnd, pos_size); } //---------------------------- ECTRL_RESULT C_edit_control::Open(class C_cache *ck, const char *title, void *hwnd_parent, dword flags, void **ret_hwnd, const int pos_size[4]){ read_only = true; if(ret_hwnd) *ret_hwnd = NULL; bool b = win.doc.Open(ck, title, &config); if(!b) return ECTRLERR_OPENFAILED; read_only = (flags&ECTRL_OPEN_READONLY); hwnd = CreateDialogParam(hi, "IDD_EDIT_CONTROL", (HWND)hwnd_parent, dlgProc, (LPARAM)this); if(hwnd){ SetWindowText(hwnd, win.doc.title); win.hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, "EC_WINDOW", NULL, WS_CHILD | WS_CLIPCHILDREN | WS_VSCROLL, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwnd, NULL, hi, this); if(pos_size){ MoveWindow(hwnd, pos_size[0], pos_size[1], pos_size[2], pos_size[3], true); } ShowWindow(win.hwnd, SW_SHOW); SetFocus(win.hwnd); } //SizeWindow(); if(!(flags&ECTRL_OPEN_HIDDEN)){ ShowWindow(hwnd, SW_SHOW); UpdateWindow(hwnd); } if(ret_hwnd) *ret_hwnd = hwnd; return ECTRL_OK; } //---------------------------- void C_edit_control::ProcessInput(UINT uMsg, dword wParam, dword lParam){ //try get code dword code = 0; bool shift_down = false; int i; if(uMsg==WM_KEYDOWN || uMsg==WM_SYSKEYDOWN){ i = wParam; char *cp = (char*)strchr(CODE_CONVERT, i); if(cp) i = CODE_CONVERT1[cp-CODE_CONVERT]; code = code_manager.Get(user_macros, i, lParam, &shift_down); //if(!code) code = wParam; }else if(uMsg==WM_CHAR){ code = code_manager.Get(user_macros, wParam, lParam, &shift_down); if(!code) code = wParam; } if(code){ bool check_state = false; bool command_result = false; short cmd_mode = 0; bool neg = false; do{ if(code>=FIRST_COMMAND){ check_state = true; if(code>=SYS_COMMANDS){ switch(code){ case JUMP: code_manager.Jump(code_manager.GetNumber()); break; case JTRUE: i = code_manager.GetNumber(); if(command_result) code_manager.Jump(i); break; case JFALSE: i=code_manager.GetNumber(); if(!command_result) code_manager.Jump(i); break; case RETURN: code_manager.Stop(); break; case AND: //if already 0, skip next test cmd_mode = code; if(!command_result){ while((code=code_manager.Get(user_macros, 0, 0, &shift_down))==NOT); code_manager.SkipCondCode(code); cmd_mode=0; } break; case OR: //if already 1, skip next test cmd_mode=code; if(command_result){ while((code=code_manager.Get(user_macros, 0, 0, &shift_down))==NOT); code_manager.SkipCondCode(code); cmd_mode=0; } break; case XOR: cmd_mode=code; break; case NOT: neg ^= 1; break; case TRUE: command_result=!neg; break; } }else{ i = code_manager.edit_functions[code-FIRST_COMMAND](&win) ^ neg; switch(cmd_mode){ case AND: (byte&)command_result &= i; break; case OR: (byte&)command_result |= i; break; case XOR: (byte&)command_result ^= i; break; default: command_result = i; } neg = false; cmd_mode = 0; //if(CurrWindow()) { if(code!=UNDO && code!=REDO && code!=MAINMENU && code!=MESSAGE){ win.undo[1].Clear(); if(code!=FIND && code!=REPEAT) AdjustBlock(&win, shift_down, false); }else AdjustBlock(&win, shift_down, true); } } }else if(code>=32){ check_state = true; //char if(win.block.IsCUA()) code_manager.edit_functions[DELETEBLOCK-FIRST_COMMAND](&win); if(PutCh(&win, code)) code_manager.edit_functions[CURSORRIGHT-FIRST_COMMAND](&win); } //continue getting commands code = code_manager.Get(user_macros, 0, 0, &shift_down); }while(code); if(check_state) CheckState(); } { SetCursorVisible(&win, win.hwnd); win.cursor.SavePos(); Redraw(); //break undo level win.undo[0].Add(C_undo_element::MARK); } } //---------------------------- void C_edit_control::Redraw(){ if(win.doc.redraw){ PostMessage(win.hwnd, WM_USER_PAINTWHOLE, 0, 0); win.doc.redraw = false; }else if(win.doc.redraw_line){ SendMessage(win.hwnd, WM_USER_PAINTLINE, win.cursor.y, TRUE); win.doc.redraw_line = false; } if(win.cursor.redraw){ SendMessage(win.hwnd, WM_USER_MOVECURSOR, 0, 0); DrawLineColumn(); win.cursor.redraw = false; } } //---------------------------- void C_edit_control::SetFont(HDC hdc, int *sx, int *sy){ if(!fnt) fnt = CreateFontIndirect(&curr_font_log); SelectObject(hdc, fnt); if(font_sy==-1){ TEXTMETRIC tm; GetTextMetrics(hdc, &tm); font_sy = tm.tmHeight; font_sx = tm.tmAveCharWidth; } *sx = font_sx; *sy = font_sy; } //---------------------------- void C_edit_control::GetFontSize(int *sx, int *sy){ if(font_sy!=-1){ *sx = font_sx; *sy = font_sy; }else{ HDC hdc = GetDC(win.hwnd); SetFont(hdc, sx, sy); ReleaseDC(win.hwnd, hdc); } } //---------------------------- void C_edit_control::SetHDCColors(HDC hdc, byte c, bool line_highl){ if(line_highl!=curr_highl){ ResetHDCColors(); curr_highl=line_highl; } byte cb; byte cf; if(curr_HDC_color==-1){ cb=c+16; cf=c+1; }else{ cb=curr_HDC_color>>4; cf=curr_HDC_color&15; } if(cb!=(c>>4)){ cb=c>>4; SetBkColor(hdc, GetRGB(cb, 0)); } if(cf!=(c&15)){ cf=c&15; SetTextColor(hdc, GetRGB(cf, line_highl)); } curr_HDC_color=(cb<<4)|cf; } //---------------------------- void C_edit_control::ResetHDCColors(){ curr_HDC_color = -1; } //---------------------------- int C_edit_control::CheckReservedWord(char *text, byte len){ for(int i=0; i<4; i++) for(int j=reserved_word[i].size(); j--; ) if(reserved_word[i][j].Size()==len && !memcmp(text, (const char*)reserved_word[i][j], len)) return i; return -1; } //---------------------------- void C_edit_control::SetCurrPos(int line, int row){ SetCursorPos1(&win, row, line); { SetCursorVisible(&win, win.hwnd); win.cursor.SavePos(); Redraw(); //break undo level win.undo[0].Add(C_undo_element::MARK); } } //---------------------------- //---------------------------- PC_edit_control __declspec(dllexport) CreateEditControl(){ return new C_edit_control; } //----------------------------
29.94867
123
0.530861
[ "shape" ]
a33bb3dc3b196d2251f68c0252ca52b519f70b34
15,390
cpp
C++
src/client/MCUDPControl.cpp
jrl-umi3218/mc_udp
13c1e75b1e6b9dec11ce25e097637f8b6a2ee23d
[ "BSD-2-Clause" ]
3
2020-03-11T12:29:15.000Z
2021-10-04T05:46:35.000Z
src/client/MCUDPControl.cpp
jrl-umi3218/mc_udp
13c1e75b1e6b9dec11ce25e097637f8b6a2ee23d
[ "BSD-2-Clause" ]
null
null
null
src/client/MCUDPControl.cpp
jrl-umi3218/mc_udp
13c1e75b1e6b9dec11ce25e097637f8b6a2ee23d
[ "BSD-2-Clause" ]
3
2020-04-09T10:24:38.000Z
2021-01-29T20:08:16.000Z
/* * Copyright 2019-2020 CNRS-UM LIRMM, CNRS-AIST JRL */ #include <mc_udp/client/Client.h> #include <mc_control/mc_global_controller.h> #include <mc_rbdyn/rpy_utils.h> #include <mc_rtc/version.h> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <signal.h> static bool running = true; void handler(int) { running = false; } void cli(mc_control::MCGlobalController & ctl) { while(running) { std::string ui; std::getline(std::cin, ui); std::stringstream ss; ss << ui; std::string token; ss >> token; if(token == "stop") { mc_rtc::log::info("Stopping connection"); running = false; } else if(token == "hs" || token == "GoToHalfSitPose" || token == "half_sitting") { ctl.GoToHalfSitPose_service(); } else if(token.size()) { std::cerr << "Unkwown command " << token << std::endl; } } } template<typename T> void updateConfig(mc_rtc::Configuration & config, po::variables_map & vm, const char * name, T & param) { if(!vm.count(name)) { if(config.has(name)) { param = static_cast<T>(config(name)); } else { config.add(name, param); } } else { config.add(name, param); } } int main(int argc, char * argv[]) { std::string conf_file = ""; std::string host = "localhost"; int port = 4444; /** Whether encoder desired velocities should be sent */ bool withEncoderVelocity = false; /** Whether to use one or two client(s) */ bool singleClient = false; po::options_description desc("MCUDPControl options"); // clang-format off desc.add_options() ("help", "Display help message") ("encoderVelocity", "Send/receive encoder velocities") ("host,h", po::value<std::string>(&host), "Connection host") ("port,p", po::value<int>(&port), "Connection port") ("conf,f", po::value<std::string>(&conf_file), "Configuration file") ("single,s", "Use a single client"); // clang-format on /** If the robot name is NOT_SET then warn once */ bool warnedNOT_SET = false; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { std::cout << desc << std::endl; return 1; } if(vm.count("encoderVelocity")) { mc_rtc::log::info("[UDP] Sending/Receiving encoder velocities"); withEncoderVelocity = true; } if(vm.count("single")) { singleClient = true; } if(mc_rtc::MC_RTC_VERSION != mc_rtc::version()) { mc_rtc::log::error("mc_udp was compiled with {} but mc_rtc is at version {}, you might face subtle issues or " "unexpected crashes, please recompile mc_udp", mc_rtc::MC_RTC_VERSION, mc_rtc::version()); } mc_control::MCGlobalController::GlobalConfiguration gconfig(conf_file, nullptr); auto config = gconfig.config; if(!config.has("UDP")) { config.add("UDP"); } config = config("UDP"); updateConfig(config, vm, "host", host); updateConfig(config, vm, "port", port); mc_control::MCGlobalController controller(gconfig); if(singleClient) { mc_rtc::log::info("Connect UDP client to {};{}", host, port); } else { mc_rtc::log::info("Connecting UDP sensors client to {}:{}", host, port); } mc_udp::Client sensorsClient(host, port); mc_udp::Client * controlClientPtr = &sensorsClient; if(!singleClient) { mc_rtc::log::info("Connecting UDP control client to {}:{}", host, port + 1); controlClientPtr = new mc_udp::Client(host, port + 1); } mc_udp::Client & controlClient = *controlClientPtr; bool init = false; // RTC port to robot force sensors std::unordered_map<std::string, std::string> fsensors; fsensors["rfsensor"] = "RightFootForceSensor"; fsensors["lfsensor"] = "LeftFootForceSensor"; fsensors["rhsensor"] = "RightHandForceSensor"; fsensors["lhsensor"] = "LeftHandForceSensor"; std::map<std::string, std::map<std::string, sva::ForceVecd>> robot_wrenches; auto refIndex = [&controller](const std::string & jName) { const auto & rjo = controller.robot().refJointOrder(); for(size_t i = 0; i < rjo.size(); ++i) { if(rjo[i] == jName) { return static_cast<int>(i); } } return -1; }; std::map<size_t, double> ignoredJoints; std::map<size_t, double> ignoredVelocities; if(config.has("IgnoredJoints")) { const auto & c = config("IgnoredJoints"); std::vector<std::string> joints = c("joints", std::vector<std::string>{}); std::map<std::string, double> ignoredValues = c("values", std::map<std::string, double>{}); std::map<std::string, double> ignoredVelocityValues = c("velocities", std::map<std::string, double>{}); for(const auto & jN : joints) { if(controller.robot().hasJoint(jN)) { const auto & rjo = controller.robot().refJointOrder(); const auto idx = std::distance(rjo.begin(), std::find(rjo.begin(), rjo.end(), jN)); double qInit = 0; double alphaInit = 0; // Ignored joint values if(ignoredValues.count(jN) > 0) { // Use user-provided value for the ignored joint qInit = ignoredValues[jN]; } else { // Use halfsitting configuration qInit = controller.robot().stance().at(jN)[0]; } ignoredJoints[idx] = qInit; // Ignored velocity values if(ignoredVelocityValues.count(jN) > 0) { // Use user-provided value for the ignored joint alphaInit = ignoredVelocityValues[jN]; } ignoredVelocities[idx] = alphaInit; mc_rtc::log::warning("[UDP] Joint {} is ignored, value = {}, velocity= {}", jN, qInit, alphaInit); } else { mc_rtc::log::warning("[UDP] Ignored joint {} is not present in robot ", jN, controller.robot().name()); } } } uint64_t prev_id = 0; using duration_ms = std::chrono::duration<double, std::milli>; duration_ms udp_run_dt{0}; controller.controller().logger().addLogEntry("perf_UDP", [&udp_run_dt]() { return udp_run_dt.count(); }); signal(SIGINT, handler); std::thread cli_thread([&controller]() { cli(controller); }); std::vector<double> qIn; std::vector<double> alphaIn; using clock = typename std::conditional<std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock, std::chrono::steady_clock>::type; auto mc_udp_start = clock::now(); while(running) { if(sensorsClient.recv()) { auto start = clock::now(); const std::string & mainRobotName = controller.robot().name(); if(!sensorsClient.sensors().messages.count(mainRobotName)) { mc_rtc::log::error("Server is providing sensors message for:"); for(const auto & m : sensorsClient.sensors().messages) { mc_rtc::log::error("- {}", m.first); } mc_rtc::log::error_and_throw<std::runtime_error>("Server is not providing sensors message for main robot ({})", mainRobotName); } for(const auto & msg : sensorsClient.sensors().messages) { bool isMain = mainRobotName == msg.first; if(!controller.controller().robots().hasRobot(msg.first)) { if(msg.first == "NOT_SET") { if(!warnedNOT_SET) { mc_rtc::log::warning("Server is providing data for the NOT_SET robot, the server configuration should be " "updated, assuming this is the main robot"); warnedNOT_SET = true; } } else { mc_rtc::log::error("Server is providing data for a robot that is not controlled by this controller: {}", msg.first); continue; } } const auto & sensors = msg.second; auto & robot = msg.first != "NOT_SET" ? controller.robot(msg.first) : controller.robot(); Eigen::Vector3d rpy; rpy << sensors.orientation[0], sensors.orientation[1], sensors.orientation[2]; Eigen::Vector3d pos; pos << sensors.position[0], sensors.position[1], sensors.position[2]; Eigen::Vector3d vel; vel << sensors.angularVelocity[0], sensors.angularVelocity[1], sensors.angularVelocity[2]; Eigen::Vector3d acc; acc << sensors.linearAcceleration[0], sensors.linearAcceleration[1], sensors.linearAcceleration[2]; if(isMain) { qIn = sensors.encoders; alphaIn = sensors.encoderVelocities; // Ignore encoder value for ignored joints for(const auto & j : ignoredJoints) { qIn[j.first] = j.second; } if(withEncoderVelocity) { for(const auto & j : ignoredVelocities) { alphaIn[j.first] = j.second; } } controller.setEncoderValues(qIn); controller.setEncoderVelocities(alphaIn); controller.setJointTorques(sensors.torques); controller.setSensorOrientation(Eigen::Quaterniond(mc_rbdyn::rpyToMat(rpy))); controller.setSensorPosition(pos); controller.setSensorAngularVelocity(vel); controller.setSensorLinearAcceleration(acc); } else { controller.setEncoderValues(robot.name(), sensors.encoders); controller.setEncoderVelocities(robot.name(), sensors.encoderVelocities); controller.setJointTorques(robot.name(), sensors.torques); controller.setSensorOrientation(robot.name(), Eigen::Quaterniond(mc_rbdyn::rpyToMat(rpy))); controller.setSensorPosition(robot.name(), pos); controller.setSensorAngularVelocity(robot.name(), vel); controller.setSensorLinearAcceleration(robot.name(), acc); } // Floating base sensor if(robot.hasBodySensor("FloatingBase")) { controller.setSensorPositions( robot.name(), {{"FloatingBase", {sensors.floatingBasePos[0], sensors.floatingBasePos[1], sensors.floatingBasePos[2]}}}); Eigen::Vector3d fbRPY; controller.setSensorOrientations( robot.name(), {{"FloatingBase", Eigen::Quaterniond(mc_rbdyn::rpyToMat({sensors.floatingBaseRPY[0], sensors.floatingBaseRPY[1], sensors.floatingBaseRPY[2]}))}}); controller.setSensorAngularVelocities( robot.name(), {{"FloatingBase", {sensors.floatingBaseVel[0], sensors.floatingBaseVel[1], sensors.floatingBaseVel[2]}}}); controller.setSensorLinearVelocities( robot.name(), {{"FloatingBase", {sensors.floatingBaseVel[3], sensors.floatingBaseVel[4], sensors.floatingBaseVel[5]}}}); controller.setSensorLinearAccelerations( robot.name(), {{"FloatingBase", {sensors.floatingBaseAcc[0], sensors.floatingBaseAcc[1], sensors.floatingBaseAcc[2]}}}); } auto & wrenches = robot_wrenches[msg.first]; for(const auto & fs : sensors.fsensors) { Eigen::Vector6d reading; reading << fs.reading[3], fs.reading[4], fs.reading[5], fs.reading[0], fs.reading[1], fs.reading[2]; wrenches[fsensors.at(fs.name)] = sva::ForceVecd(reading); } controller.setWrenches(robot.name(), wrenches); } auto & sc = sensorsClient.sensors().messages.at(controller.robot().name()); if(!init) { auto init_start = clock::now(); controller.init(qIn); controller.running = true; init = true; auto init_end = clock::now(); duration_ms init_dt = init_end - init_start; #if MC_RTC_VERSION_MAJOR < 2 for(const auto & robot : controller.controller().robots()) #else for(const auto & robot_ptr : controller.controller().robots()) #endif { #if MC_RTC_VERSION_MAJOR >= 2 const auto & robot = *robot_ptr; #endif const auto & rjo = robot.module().ref_joint_order(); if(rjo.size() == 0) { continue; } auto & cc = controlClient.control().messages[robot.name()]; auto & qOut = cc.encoders; auto & alphaOut = cc.encoderVelocities; if(qOut.size() != rjo.size()) { qOut.resize(rjo.size()); } if(withEncoderVelocity && alphaOut.size() != rjo.size()) { alphaOut.resize(rjo.size()); } } mc_rtc::log::info("[MCUDPControl] Init duration {}", init_dt.count()); sensorsClient.init(); if(!singleClient) { controlClient.init(); } } else { if(prev_id + 1 != sc.id) { mc_rtc::log::warning("[MCUDPControl] Missed one or more sensors reading (previous id: {}, current id: {})", prev_id, sc.id); } if(controller.run()) { #if MC_RTC_VERSION_MAJOR < 2 for(const auto & robot : controller.controller().robots()) #else for(const auto & robot_ptr : controller.controller().robots()) #endif { #if MC_RTC_VERSION_MAJOR >= 2 const auto & robot = *robot_ptr; #endif const auto & rjo = robot.module().ref_joint_order(); if(rjo.size() == 0) { continue; } const auto & mbc = robot.mbc(); auto & cc = controlClient.control().messages[robot.name()]; auto & qOut = cc.encoders; auto & alphaOut = cc.encoderVelocities; for(size_t i = 0; i < rjo.size(); ++i) { const auto & jN = rjo[i]; if(robot.hasJoint(jN)) { auto jIndex = robot.jointIndexByName(jN); if(mbc.q[jIndex].size() == 1) { auto jIdx = robot.jointIndexByName(jN); qOut[i] = mbc.q[jIdx][0]; if(withEncoderVelocity) { alphaOut[i] = mbc.alpha[jIdx][0]; } } } } // Ignore QP output for ignored joints for(const auto & j : ignoredJoints) { qOut[j.first] = j.second; } if(withEncoderVelocity) { for(const auto & j : ignoredVelocities) { alphaOut[j.first] = j.second; } } cc.id = sc.id; } controlClient.send(); } } prev_id = sc.id; udp_run_dt = clock::now() - start; } else if(!init) { duration_ms elapsed = clock::now() - mc_udp_start; if(elapsed.count() > 5000) { mc_rtc::log::warning("No messages received yet, requesting stream again"); mc_udp_start = clock::now(); sensorsClient.sendHello(); if(controlClientPtr) { controlClient.sendHello(); } } } } return 0; }
33.676149
120
0.570305
[ "vector" ]
a33e9e2121b9dc60f006bbac553a3a3399edf469
49,552
cc
C++
chrome/browser/ui/views/extensions/extension_install_dialog_view.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
chrome/browser/ui/views/extensions/extension_install_dialog_view.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/extensions/extension_install_dialog_view.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:13.000Z
2020-11-04T07:24:13.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/basictypes.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/i18n/rtl.h" #include "base/metrics/histogram.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/bundle_installer.h" #include "chrome/browser/extensions/extension_install_prompt.h" #include "chrome/browser/extensions/extension_install_prompt_experiment.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/views/constrained_window_views.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/installer/util/browser_distribution.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/web_contents.h" #include "extensions/common/extension.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/google_chrome_strings.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/animation/slide_animation.h" #include "ui/gfx/text_utils.h" #include "ui/gfx/transform.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/link.h" #include "ui/views/controls/link_listener.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/separator.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/window/dialog_client_view.h" #include "ui/views/window/dialog_delegate.h" using content::OpenURLParams; using content::Referrer; using extensions::BundleInstaller; namespace { // Size of extension icon in top left of dialog. const int kIconSize = 64; // We offset the icon a little bit from the right edge of the dialog, to make it // align with the button below it. const int kIconOffset = 16; // The dialog will resize based on its content, but this sets a maximum height // before overflowing a scrollbar. const int kDialogMaxHeight = 300; // Width of the left column of the dialog when the extension requests // permissions. const int kPermissionsLeftColumnWidth = 250; // Width of the left column of the dialog when the extension requests no // permissions. const int kNoPermissionsLeftColumnWidth = 200; // Width of the left column for bundle install prompts. There's only one column // in this case, so make it wider than normal. const int kBundleLeftColumnWidth = 300; // Width of the left column for external install prompts. The text is long in // this case, so make it wider than normal. const int kExternalInstallLeftColumnWidth = 350; // Lighter color for labels. const SkColor kLighterLabelColor = SkColorSetRGB(0x99, 0x99, 0x99); // Represents an action on a clickable link created by the install prompt // experiment. This is used to group the actions in UMA histograms named // Extensions.InstallPromptExperiment.ShowDetails and // Extensions.InstallPromptExperiment.ShowPermissions. enum ExperimentLinkAction { LINK_SHOWN = 0, LINK_NOT_SHOWN, LINK_CLICKED, NUM_LINK_ACTIONS }; typedef std::vector<base::string16> PermissionDetails; class ExpandableContainerView; void AddResourceIcon(const gfx::ImageSkia* skia_image, void* data) { views::View* parent = static_cast<views::View*>(data); views::ImageView* image_view = new views::ImageView(); image_view->SetImage(*skia_image); parent->AddChildView(image_view); } // Creates a string for displaying |message| to the user. If it has to look // like a entry in a bullet point list, one is added. base::string16 PrepareForDisplay(const base::string16& message, bool bullet_point) { return bullet_point ? l10n_util::GetStringFUTF16( IDS_EXTENSION_PERMISSION_LINE, message) : message; } // A custom scrollable view implementation for the dialog. class CustomScrollableView : public views::View { public: CustomScrollableView(); virtual ~CustomScrollableView(); private: virtual void Layout() OVERRIDE; DISALLOW_COPY_AND_ASSIGN(CustomScrollableView); }; // Implements the extension installation dialog for TOOLKIT_VIEWS. class ExtensionInstallDialogView : public views::DialogDelegateView, public views::LinkListener, public views::ButtonListener { public: ExtensionInstallDialogView( content::PageNavigator* navigator, ExtensionInstallPrompt::Delegate* delegate, scoped_refptr<ExtensionInstallPrompt::Prompt> prompt); virtual ~ExtensionInstallDialogView(); // Called when one of the child elements has expanded/collapsed. void ContentsChanged(); private: // views::DialogDelegateView: virtual int GetDialogButtons() const OVERRIDE; virtual base::string16 GetDialogButtonLabel( ui::DialogButton button) const OVERRIDE; virtual int GetDefaultDialogButton() const OVERRIDE; virtual bool Cancel() OVERRIDE; virtual bool Accept() OVERRIDE; virtual ui::ModalType GetModalType() const OVERRIDE; virtual base::string16 GetWindowTitle() const OVERRIDE; virtual void Layout() OVERRIDE; virtual gfx::Size GetPreferredSize() const OVERRIDE; virtual void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) OVERRIDE; // views::LinkListener: virtual void LinkClicked(views::Link* source, int event_flags) OVERRIDE; // views::ButtonListener: virtual void ButtonPressed(views::Button* sender, const ui::Event& event) OVERRIDE; // Experimental: Toggles inline permission explanations with an animation. void ToggleInlineExplanations(); // Creates a layout consisting of dialog header, extension name and icon. views::GridLayout* CreateLayout( views::View* parent, int left_column_width, int column_set_id, bool single_detail_row) const; bool is_inline_install() const { return prompt_->type() == ExtensionInstallPrompt::INLINE_INSTALL_PROMPT; } bool is_bundle_install() const { return prompt_->type() == ExtensionInstallPrompt::BUNDLE_INSTALL_PROMPT; } bool is_external_install() const { return prompt_->type() == ExtensionInstallPrompt::EXTERNAL_INSTALL_PROMPT; } // Updates the histogram that holds installation accepted/aborted data. void UpdateInstallResultHistogram(bool accepted) const; // Updates the histogram that holds data about whether "Show details" or // "Show permissions" links were shown and/or clicked. void UpdateLinkActionHistogram(int action_type) const; content::PageNavigator* navigator_; ExtensionInstallPrompt::Delegate* delegate_; scoped_refptr<ExtensionInstallPrompt::Prompt> prompt_; // The scroll view containing all the details for the dialog (including all // collapsible/expandable sections). views::ScrollView* scroll_view_; // The container view for the scroll view. CustomScrollableView* scrollable_; // The container for the simpler view with only the dialog header and the // extension icon. Used for the experiment where the permissions are // initially hidden when the dialog shows. CustomScrollableView* scrollable_header_only_; // The preferred size of the dialog. gfx::Size dialog_size_; // Experimental: "Show details" link to expand inline explanations and reveal // permision dialog. views::Link* show_details_link_; // Experimental: Label for showing information about the checkboxes. views::Label* checkbox_info_label_; // Experimental: Contains pointers to inline explanation views. typedef std::vector<ExpandableContainerView*> InlineExplanations; InlineExplanations inline_explanations_; // Experimental: Number of unchecked checkboxes in the permission list. // If this becomes zero, the accept button is enabled, otherwise disabled. int unchecked_boxes_; DISALLOW_COPY_AND_ASSIGN(ExtensionInstallDialogView); }; // A simple view that prepends a view with a bullet with the help of a grid // layout. class BulletedView : public views::View { public: explicit BulletedView(views::View* view); private: DISALLOW_COPY_AND_ASSIGN(BulletedView); }; BulletedView::BulletedView(views::View* view) { views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); views::ColumnSet* column_set = layout->AddColumnSet(0); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::USE_PREF, 0, // no fixed width 0); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::USE_PREF, 0, // no fixed width 0); layout->StartRow(0, 0); layout->AddView(new views::Label(PrepareForDisplay(base::string16(), true))); layout->AddView(view); } // A simple view that prepends a view with a checkbox with the help of a grid // layout. Used for the permission experiment. // TODO(meacer): Remove once the experiment is completed. class CheckboxedView : public views::View { public: CheckboxedView(views::View* view, views::ButtonListener* listener); private: DISALLOW_COPY_AND_ASSIGN(CheckboxedView); }; CheckboxedView::CheckboxedView(views::View* view, views::ButtonListener* listener) { views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); views::ColumnSet* column_set = layout->AddColumnSet(0); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::USE_PREF, 0, // no fixed width 0); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::USE_PREF, 0, // no fixed width 0); layout->StartRow(0, 0); views::Checkbox* checkbox = new views::Checkbox(base::string16()); checkbox->set_listener(listener); // Alignment needs to be explicitly set again here, otherwise the views are // not vertically centered. layout->AddView(checkbox, 1, 1, views::GridLayout::LEADING, views::GridLayout::CENTER); layout->AddView(view, 1, 1, views::GridLayout::LEADING, views::GridLayout::CENTER); } // A view to display text with an expandable details section. class ExpandableContainerView : public views::View, public views::ButtonListener, public views::LinkListener, public gfx::AnimationDelegate { public: ExpandableContainerView(ExtensionInstallDialogView* owner, const base::string16& description, const PermissionDetails& details, int horizontal_space, bool parent_bulleted, bool show_expand_link, bool lighter_color_details); virtual ~ExpandableContainerView(); // views::View: virtual void ChildPreferredSizeChanged(views::View* child) OVERRIDE; // views::ButtonListener: virtual void ButtonPressed(views::Button* sender, const ui::Event& event) OVERRIDE; // views::LinkListener: virtual void LinkClicked(views::Link* source, int event_flags) OVERRIDE; // gfx::AnimationDelegate: virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE; virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE; // Expand/Collapse the detail section for this ExpandableContainerView. void ToggleDetailLevel(); // Expand the detail section without any animation. // TODO(meacer): Remove once the experiment is completed. void ExpandWithoutAnimation(); private: // A view which displays all the details of an IssueAdviceInfoEntry. class DetailsView : public views::View { public: explicit DetailsView(int horizontal_space, bool parent_bulleted, bool lighter_color); virtual ~DetailsView() {} // views::View: virtual gfx::Size GetPreferredSize() const OVERRIDE; void AddDetail(const base::string16& detail); // Animates this to be a height proportional to |state|. void AnimateToState(double state); private: views::GridLayout* layout_; double state_; // Whether the detail text should be shown with a lighter color. bool lighter_color_; DISALLOW_COPY_AND_ASSIGN(DetailsView); }; // The dialog that owns |this|. It's also an ancestor in the View hierarchy. ExtensionInstallDialogView* owner_; // A view for showing |issue_advice.details|. DetailsView* details_view_; // The 'more details' link shown under the heading (changes to 'hide details' // when the details section is expanded). views::Link* more_details_; gfx::SlideAnimation slide_animation_; // The up/down arrow next to the 'more detail' link (points up/down depending // on whether the details section is expanded). views::ImageButton* arrow_toggle_; // Whether the details section is expanded. bool expanded_; DISALLOW_COPY_AND_ASSIGN(ExpandableContainerView); }; void ShowExtensionInstallDialogImpl( const ExtensionInstallPrompt::ShowParams& show_params, ExtensionInstallPrompt::Delegate* delegate, scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); CreateBrowserModalDialogViews( new ExtensionInstallDialogView(show_params.navigator, delegate, prompt), show_params.parent_window)->Show(); } } // namespace CustomScrollableView::CustomScrollableView() {} CustomScrollableView::~CustomScrollableView() {} void CustomScrollableView::Layout() { SetBounds(x(), y(), width(), GetHeightForWidth(width())); views::View::Layout(); } ExtensionInstallDialogView::ExtensionInstallDialogView( content::PageNavigator* navigator, ExtensionInstallPrompt::Delegate* delegate, scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) : navigator_(navigator), delegate_(delegate), prompt_(prompt), scroll_view_(NULL), scrollable_(NULL), scrollable_header_only_(NULL), show_details_link_(NULL), checkbox_info_label_(NULL), unchecked_boxes_(0) { // Possible grid layouts without ExtensionPermissionDialog experiment: // Inline install // w/ permissions no permissions // +--------------------+------+ +--------------+------+ // | heading | icon | | heading | icon | // +--------------------| | +--------------| | // | rating | | | rating | | // +--------------------| | +--------------+ | // | user_count | | | user_count | | // +--------------------| | +--------------| | // | store_link | | | store_link | | // +--------------------+------+ +--------------+------+ // | separator | // +--------------------+------+ // | permissions_header | | // +--------------------+------+ // | permission1 | | // +--------------------+------+ // | permission2 | | // +--------------------+------+ // // Regular install // w/ permissions no permissions // +--------------------+------+ +--------------+------+ // | heading | icon | | heading | icon | // +--------------------| | +--------------+------+ // | permissions_header | | // +--------------------| | // | permission1 | | // +--------------------| | // | permission2 | | // +--------------------+------+ // // If the ExtensionPermissionDialog is on, the layout is modified depending // on the experiment group. For text only experiment, a footer is added at the // bottom of the layouts. For others, inline details are added below some of // the permissions. // // Regular install w/ permissions and footer (experiment): // +--------------------+------+ // | heading | icon | // +--------------------| | // | permissions_header | | // +--------------------| | // | permission1 | | // +--------------------| | // | permission2 | | // +--------------------+------+ // | footer text | | // +--------------------+------+ // // Regular install w/ permissions and inline explanations (experiment): // +--------------------+------+ // | heading | icon | // +--------------------| | // | permissions_header | | // +--------------------| | // | permission1 | | // +--------------------| | // | explanation1 | | // +--------------------| | // | permission2 | | // +--------------------| | // | explanation2 | | // +--------------------+------+ // // Regular install w/ permissions and inline explanations (experiment): // +--------------------+------+ // | heading | icon | // +--------------------| | // | permissions_header | | // +--------------------| | // |checkbox|permission1| | // +--------------------| | // |checkbox|permission2| | // +--------------------+------+ // // Additionally, links or informational text is added to non-client areas of // the dialog depending on the experiment group. int left_column_width = (prompt->ShouldShowPermissions() + prompt->GetRetainedFileCount()) > 0 ? kPermissionsLeftColumnWidth : kNoPermissionsLeftColumnWidth; if (is_bundle_install()) left_column_width = kBundleLeftColumnWidth; if (is_external_install()) left_column_width = kExternalInstallLeftColumnWidth; scroll_view_ = new views::ScrollView(); scroll_view_->set_hide_horizontal_scrollbar(true); AddChildView(scroll_view_); int column_set_id = 0; // Create the full scrollable view which will contain all the information // including the permissions. scrollable_ = new CustomScrollableView(); views::GridLayout* layout = CreateLayout( scrollable_, left_column_width, column_set_id, false); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); if (prompt->ShouldShowPermissions() && prompt->experiment()->should_show_expandable_permission_list()) { // If the experiment should hide the permission list initially, create a // simple layout that contains only the header, extension name and icon. scrollable_header_only_ = new CustomScrollableView(); CreateLayout(scrollable_header_only_, left_column_width, column_set_id, true); scroll_view_->SetContents(scrollable_header_only_); } else { scroll_view_->SetContents(scrollable_); } int dialog_width = left_column_width + 2 * views::kPanelHorizMargin; if (!is_bundle_install()) dialog_width += views::kPanelHorizMargin + kIconSize + kIconOffset; // Widen the dialog for experiment with checkboxes so that the information // label fits the area to the left of the buttons. if (prompt->experiment()->show_checkboxes()) dialog_width += 4 * views::kPanelHorizMargin; if (prompt->has_webstore_data()) { layout->StartRow(0, column_set_id); views::View* rating = new views::View(); rating->SetLayoutManager(new views::BoxLayout( views::BoxLayout::kHorizontal, 0, 0, 0)); layout->AddView(rating); prompt->AppendRatingStars(AddResourceIcon, rating); const gfx::FontList& small_font_list = rb.GetFontList(ui::ResourceBundle::SmallFont); views::Label* rating_count = new views::Label(prompt->GetRatingCount(), small_font_list); // Add some space between the stars and the rating count. rating_count->SetBorder(views::Border::CreateEmptyBorder(0, 2, 0, 0)); rating->AddChildView(rating_count); layout->StartRow(0, column_set_id); views::Label* user_count = new views::Label(prompt->GetUserCount(), small_font_list); user_count->SetAutoColorReadabilityEnabled(false); user_count->SetEnabledColor(SK_ColorGRAY); layout->AddView(user_count); layout->StartRow(0, column_set_id); views::Link* store_link = new views::Link( l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_STORE_LINK)); store_link->SetFontList(small_font_list); store_link->set_listener(this); layout->AddView(store_link); } if (is_bundle_install()) { BundleInstaller::ItemList items = prompt->bundle()->GetItemsWithState( BundleInstaller::Item::STATE_PENDING); for (size_t i = 0; i < items.size(); ++i) { base::string16 extension_name = base::UTF8ToUTF16(items[i].localized_name); base::i18n::AdjustStringForLocaleDirection(&extension_name); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); layout->StartRow(0, column_set_id); views::Label* extension_label = new views::Label( PrepareForDisplay(extension_name, true)); extension_label->SetMultiLine(true); extension_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); extension_label->SizeToFit(left_column_width); layout->AddView(extension_label); } } if (prompt->ShouldShowPermissions()) { layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); if (prompt->GetPermissionCount() > 0) { if (is_inline_install()) { layout->StartRow(0, column_set_id); layout->AddView(new views::Separator(views::Separator::HORIZONTAL), 3, 1, views::GridLayout::FILL, views::GridLayout::FILL); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); } layout->StartRow(0, column_set_id); views::Label* permissions_header = NULL; if (is_bundle_install()) { // We need to pass the FontList in the constructor, rather than calling // SetFontList later, because otherwise SizeToFit mis-judges the width // of the line. permissions_header = new views::Label(prompt->GetPermissionsHeading(), rb.GetFontList(ui::ResourceBundle::MediumFont)); } else { permissions_header = new views::Label(prompt->GetPermissionsHeading()); } permissions_header->SetMultiLine(true); permissions_header->SetHorizontalAlignment(gfx::ALIGN_LEFT); permissions_header->SizeToFit(left_column_width); layout->AddView(permissions_header); for (size_t i = 0; i < prompt->GetPermissionCount(); ++i) { layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); layout->StartRow(0, column_set_id); views::Label* permission_label = new views::Label(prompt->GetPermission(i)); const SkColor kTextHighlight = SK_ColorRED; const SkColor kBackgroundHighlight = SkColorSetRGB(0xFB, 0xF7, 0xA3); if (prompt->experiment()->ShouldHighlightText( prompt->GetPermission(i))) { permission_label->SetAutoColorReadabilityEnabled(false); permission_label->SetEnabledColor(kTextHighlight); } else if (prompt->experiment()->ShouldHighlightBackground( prompt->GetPermission(i))) { permission_label->SetLineHeight(18); permission_label->set_background( views::Background::CreateSolidBackground(kBackgroundHighlight)); } permission_label->SetMultiLine(true); permission_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); permission_label->SizeToFit(left_column_width); if (prompt->experiment()->show_checkboxes()) { layout->AddView(new CheckboxedView(permission_label, this)); ++unchecked_boxes_; } else { layout->AddView(new BulletedView(permission_label)); } // If we have more details to provide, show them in collapsed form. if (!prompt->GetPermissionsDetails(i).empty()) { layout->StartRow(0, column_set_id); PermissionDetails details; details.push_back( PrepareForDisplay(prompt->GetPermissionsDetails(i), false)); ExpandableContainerView* details_container = new ExpandableContainerView( this, base::string16(), details, left_column_width, true, true, false); layout->AddView(details_container); } if (prompt->experiment()->should_show_inline_explanations()) { base::string16 explanation = prompt->experiment()->GetInlineExplanation( prompt->GetPermission(i)); if (!explanation.empty()) { PermissionDetails details; details.push_back(explanation); ExpandableContainerView* container = new ExpandableContainerView(this, base::string16(), details, left_column_width, false, false, true); // Inline explanations are expanded by default if there is // no "Show details" link. if (!prompt->experiment()->show_details_link()) container->ExpandWithoutAnimation(); layout->StartRow(0, column_set_id); layout->AddView(container); inline_explanations_.push_back(container); } } } } else { layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); layout->StartRow(0, column_set_id); views::Label* permission_label = new views::Label( l10n_util::GetStringUTF16(IDS_EXTENSION_NO_SPECIAL_PERMISSIONS)); permission_label->SetMultiLine(true); permission_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); permission_label->SizeToFit(left_column_width); layout->AddView(permission_label); } } if (prompt->GetRetainedFileCount()) { // Slide in under the permissions, if there are any. If there are // either, the retained files prompt stretches all the way to the // right of the dialog. If there are no permissions, the retained // files prompt just takes up the left column. int space_for_files = left_column_width; if (prompt->GetPermissionCount()) { space_for_files += kIconSize; views::ColumnSet* column_set = layout->AddColumnSet(++column_set_id); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, // no fixed width space_for_files); } layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); layout->StartRow(0, column_set_id); views::Label* retained_files_header = NULL; retained_files_header = new views::Label(prompt->GetRetainedFilesHeading()); retained_files_header->SetMultiLine(true); retained_files_header->SetHorizontalAlignment(gfx::ALIGN_LEFT); retained_files_header->SizeToFit(space_for_files); layout->AddView(retained_files_header); layout->StartRow(0, column_set_id); PermissionDetails details; for (size_t i = 0; i < prompt->GetRetainedFileCount(); ++i) details.push_back(prompt->GetRetainedFile(i)); ExpandableContainerView* issue_advice_view = new ExpandableContainerView( this, base::string16(), details, space_for_files, false, true, false); layout->AddView(issue_advice_view); } DCHECK(prompt->type() >= 0); UMA_HISTOGRAM_ENUMERATION("Extensions.InstallPrompt.Type", prompt->type(), ExtensionInstallPrompt::NUM_PROMPT_TYPES); if (prompt->ShouldShowPermissions()) { if (prompt->ShouldShowExplanationText()) { views::ColumnSet* column_set = layout->AddColumnSet(++column_set_id); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Add two rows of space so that the text stands out. layout->AddPaddingRow(0, 2 * views::kRelatedControlVerticalSpacing); layout->StartRow(0, column_set_id); views::Label* explanation = new views::Label(prompt->experiment()->GetExplanationText()); explanation->SetMultiLine(true); explanation->SetHorizontalAlignment(gfx::ALIGN_LEFT); explanation->SizeToFit(left_column_width + kIconSize); layout->AddView(explanation); } if (prompt->experiment()->should_show_expandable_permission_list() || (prompt->experiment()->show_details_link() && prompt->experiment()->should_show_inline_explanations() && !inline_explanations_.empty())) { // Don't show the "Show details" link if there are retained // files. These have their own "Show details" links and having // multiple levels of links is confusing. if (prompt->GetRetainedFileCount() == 0) { int text_id = prompt->experiment()->should_show_expandable_permission_list() ? IDS_EXTENSION_PROMPT_EXPERIMENT_SHOW_PERMISSIONS : IDS_EXTENSION_PROMPT_EXPERIMENT_SHOW_DETAILS; show_details_link_ = new views::Link( l10n_util::GetStringUTF16(text_id)); show_details_link_->SetHorizontalAlignment(gfx::ALIGN_LEFT); show_details_link_->set_listener(this); UpdateLinkActionHistogram(LINK_SHOWN); } else { UpdateLinkActionHistogram(LINK_NOT_SHOWN); } } if (prompt->experiment()->show_checkboxes()) { checkbox_info_label_ = new views::Label( l10n_util::GetStringUTF16( IDS_EXTENSION_PROMPT_EXPERIMENT_CHECKBOX_INFO)); checkbox_info_label_->SetMultiLine(true); checkbox_info_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); checkbox_info_label_->SetAutoColorReadabilityEnabled(false); checkbox_info_label_->SetEnabledColor(kLighterLabelColor); } } gfx::Size scrollable_size = scrollable_->GetPreferredSize(); scrollable_->SetBoundsRect(gfx::Rect(scrollable_size)); dialog_size_ = gfx::Size( dialog_width, std::min(scrollable_size.height(), kDialogMaxHeight)); if (scrollable_header_only_) { gfx::Size header_only_size = scrollable_header_only_->GetPreferredSize(); scrollable_header_only_->SetBoundsRect(gfx::Rect(header_only_size)); dialog_size_ = gfx::Size( dialog_width, std::min(header_only_size.height(), kDialogMaxHeight)); } } ExtensionInstallDialogView::~ExtensionInstallDialogView() {} views::GridLayout* ExtensionInstallDialogView::CreateLayout( views::View* parent, int left_column_width, int column_set_id, bool single_detail_row) const { views::GridLayout* layout = views::GridLayout::CreatePanel(parent); parent->SetLayoutManager(layout); views::ColumnSet* column_set = layout->AddColumnSet(column_set_id); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 0, // no resizing views::GridLayout::USE_PREF, 0, // no fixed width left_column_width); if (!is_bundle_install()) { column_set->AddPaddingColumn(0, views::kPanelHorizMargin); column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::LEADING, 0, // no resizing views::GridLayout::USE_PREF, 0, // no fixed width kIconSize); } layout->StartRow(0, column_set_id); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); views::Label* heading = new views::Label( prompt_->GetHeading(), rb.GetFontList(ui::ResourceBundle::MediumFont)); heading->SetMultiLine(true); heading->SetHorizontalAlignment(gfx::ALIGN_LEFT); heading->SizeToFit(left_column_width); layout->AddView(heading); if (!is_bundle_install()) { // Scale down to icon size, but allow smaller icons (don't scale up). const gfx::ImageSkia* image = prompt_->icon().ToImageSkia(); gfx::Size size(image->width(), image->height()); if (size.width() > kIconSize || size.height() > kIconSize) size = gfx::Size(kIconSize, kIconSize); views::ImageView* icon = new views::ImageView(); icon->SetImageSize(size); icon->SetImage(*image); icon->SetHorizontalAlignment(views::ImageView::CENTER); icon->SetVerticalAlignment(views::ImageView::CENTER); if (single_detail_row) { layout->AddView(icon); } else { int icon_row_span = 1; if (is_inline_install()) { // Also span the rating, user_count and store_link rows. icon_row_span = 4; } else if (prompt_->ShouldShowPermissions()) { size_t permission_count = prompt_->GetPermissionCount(); // Also span the permission header and each of the permission rows (all // have a padding row above it). This also works for the 'no special // permissions' case. icon_row_span = 3 + permission_count * 2; } else if (prompt_->GetRetainedFileCount()) { // Also span the permission header and the retained files container. icon_row_span = 4; } layout->AddView(icon, 1, icon_row_span); } } return layout; } void ExtensionInstallDialogView::ContentsChanged() { Layout(); } void ExtensionInstallDialogView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { // Since we want the links to show up in the same visual row as the accept // and cancel buttons, which is provided by the framework, we must add the // buttons to the non-client view, which is the parent of this view. // Similarly, when we're removed from the view hierarchy, we must take care // to clean up those items as well. if (details.child == this) { if (details.is_add) { if (show_details_link_) details.parent->AddChildView(show_details_link_); if (checkbox_info_label_) details.parent->AddChildView(checkbox_info_label_); } else { if (show_details_link_) details.parent->RemoveChildView(show_details_link_); if (checkbox_info_label_) details.parent->RemoveChildView(checkbox_info_label_); } } } int ExtensionInstallDialogView::GetDialogButtons() const { int buttons = prompt_->GetDialogButtons(); // Simply having just an OK button is *not* supported. See comment on function // GetDialogButtons in dialog_delegate.h for reasons. DCHECK_GT(buttons & ui::DIALOG_BUTTON_CANCEL, 0); return buttons; } base::string16 ExtensionInstallDialogView::GetDialogButtonLabel( ui::DialogButton button) const { switch (button) { case ui::DIALOG_BUTTON_OK: return prompt_->GetAcceptButtonLabel(); case ui::DIALOG_BUTTON_CANCEL: return prompt_->HasAbortButtonLabel() ? prompt_->GetAbortButtonLabel() : l10n_util::GetStringUTF16(IDS_CANCEL); default: NOTREACHED(); return base::string16(); } } int ExtensionInstallDialogView::GetDefaultDialogButton() const { return ui::DIALOG_BUTTON_CANCEL; } bool ExtensionInstallDialogView::Cancel() { UpdateInstallResultHistogram(false); delegate_->InstallUIAbort(true); return true; } bool ExtensionInstallDialogView::Accept() { UpdateInstallResultHistogram(true); delegate_->InstallUIProceed(); return true; } ui::ModalType ExtensionInstallDialogView::GetModalType() const { return ui::MODAL_TYPE_WINDOW; } base::string16 ExtensionInstallDialogView::GetWindowTitle() const { return prompt_->GetDialogTitle(); } void ExtensionInstallDialogView::LinkClicked(views::Link* source, int event_flags) { if (source == show_details_link_) { UpdateLinkActionHistogram(LINK_CLICKED); // Show details link is used to either reveal whole permission list or to // reveal inline explanations. if (prompt_->experiment()->should_show_expandable_permission_list()) { gfx::Rect bounds = GetWidget()->GetWindowBoundsInScreen(); int spacing = bounds.height() - scrollable_header_only_->GetPreferredSize().height(); int content_height = std::min(scrollable_->GetPreferredSize().height(), kDialogMaxHeight); bounds.set_height(spacing + content_height); scroll_view_->SetContents(scrollable_); GetWidget()->SetBoundsConstrained(bounds); ContentsChanged(); } else { ToggleInlineExplanations(); } show_details_link_->SetVisible(false); } else { GURL store_url(extension_urls::GetWebstoreItemDetailURLPrefix() + prompt_->extension()->id()); OpenURLParams params( store_url, Referrer(), NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false); navigator_->OpenURL(params); GetWidget()->Close(); } } void ExtensionInstallDialogView::ToggleInlineExplanations() { for (InlineExplanations::iterator it = inline_explanations_.begin(); it != inline_explanations_.end(); ++it) (*it)->ToggleDetailLevel(); } void ExtensionInstallDialogView::Layout() { scroll_view_->SetBounds(0, 0, width(), height()); if (show_details_link_ || checkbox_info_label_) { views::LabelButton* cancel_button = GetDialogClientView()->cancel_button(); gfx::Rect parent_bounds = parent()->GetContentsBounds(); // By default, layouts have an inset of kButtonHEdgeMarginNew. In order to // align the link horizontally with the left side of the contents of the // layout, put a horizontal margin with this amount. const int horizontal_margin = views::kButtonHEdgeMarginNew; const int vertical_margin = views::kButtonVEdgeMarginNew; int y_buttons = parent_bounds.bottom() - cancel_button->GetPreferredSize().height() - vertical_margin; int max_width = dialog_size_.width() - cancel_button->width() * 2 - horizontal_margin * 2 - views::kRelatedButtonHSpacing; if (show_details_link_) { gfx::Size link_size = show_details_link_->GetPreferredSize(); show_details_link_->SetBounds( horizontal_margin, y_buttons + (cancel_button->height() - link_size.height()) / 2, link_size.width(), link_size.height()); } if (checkbox_info_label_) { gfx::Size label_size = checkbox_info_label_->GetPreferredSize(); checkbox_info_label_->SetBounds( horizontal_margin, y_buttons + (cancel_button->height() - label_size.height()) / 2, label_size.width(), label_size.height()); checkbox_info_label_->SizeToFit(max_width); } } // Disable accept button if there are unchecked boxes and // the experiment is on. if (prompt_->experiment()->show_checkboxes()) GetDialogClientView()->ok_button()->SetEnabled(unchecked_boxes_ == 0); DialogDelegateView::Layout(); } gfx::Size ExtensionInstallDialogView::GetPreferredSize() const { return dialog_size_; } void ExtensionInstallDialogView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (std::string(views::Checkbox::kViewClassName) == sender->GetClassName()) { views::Checkbox* checkbox = static_cast<views::Checkbox*>(sender); if (checkbox->checked()) --unchecked_boxes_; else ++unchecked_boxes_; GetDialogClientView()->ok_button()->SetEnabled(unchecked_boxes_ == 0); checkbox_info_label_->SetVisible(unchecked_boxes_ > 0); } } void ExtensionInstallDialogView::UpdateInstallResultHistogram(bool accepted) const { if (prompt_->type() == ExtensionInstallPrompt::INSTALL_PROMPT) UMA_HISTOGRAM_BOOLEAN("Extensions.InstallPrompt.Accepted", accepted); } void ExtensionInstallDialogView::UpdateLinkActionHistogram(int action_type) const { if (prompt_->experiment()->should_show_expandable_permission_list()) { // The clickable link in the UI is "Show Permissions". UMA_HISTOGRAM_ENUMERATION( "Extensions.InstallPromptExperiment.ShowPermissions", action_type, NUM_LINK_ACTIONS); } else { // The clickable link in the UI is "Show Details". UMA_HISTOGRAM_ENUMERATION( "Extensions.InstallPromptExperiment.ShowDetails", action_type, NUM_LINK_ACTIONS); } } // static ExtensionInstallPrompt::ShowDialogCallback ExtensionInstallPrompt::GetDefaultShowDialogCallback() { return base::Bind(&ShowExtensionInstallDialogImpl); } // ExpandableContainerView::DetailsView ---------------------------------------- ExpandableContainerView::DetailsView::DetailsView(int horizontal_space, bool parent_bulleted, bool lighter_color) : layout_(new views::GridLayout(this)), state_(0), lighter_color_(lighter_color) { SetLayoutManager(layout_); views::ColumnSet* column_set = layout_->AddColumnSet(0); // If the parent is using bullets for its items, then a padding of one unit // will make the child item (which has no bullet) look like a sibling of its // parent. Therefore increase the indentation by one more unit to show that it // is in fact a child item (with no missing bullet) and not a sibling. int padding = views::kRelatedControlHorizontalSpacing * (parent_bulleted ? 2 : 1); column_set->AddPaddingColumn(0, padding); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::FIXED, horizontal_space - padding, 0); } void ExpandableContainerView::DetailsView::AddDetail( const base::string16& detail) { layout_->StartRowWithPadding(0, 0, 0, views::kRelatedControlSmallVerticalSpacing); views::Label* detail_label = new views::Label(PrepareForDisplay(detail, false)); detail_label->SetMultiLine(true); detail_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); if (lighter_color_) { detail_label->SetEnabledColor(kLighterLabelColor); detail_label->SetAutoColorReadabilityEnabled(false); } layout_->AddView(detail_label); } gfx::Size ExpandableContainerView::DetailsView::GetPreferredSize() const { gfx::Size size = views::View::GetPreferredSize(); return gfx::Size(size.width(), size.height() * state_); } void ExpandableContainerView::DetailsView::AnimateToState(double state) { state_ = state; PreferredSizeChanged(); SchedulePaint(); } // ExpandableContainerView ----------------------------------------------------- ExpandableContainerView::ExpandableContainerView( ExtensionInstallDialogView* owner, const base::string16& description, const PermissionDetails& details, int horizontal_space, bool parent_bulleted, bool show_expand_link, bool lighter_color_details) : owner_(owner), details_view_(NULL), more_details_(NULL), slide_animation_(this), arrow_toggle_(NULL), expanded_(false) { views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); int column_set_id = 0; views::ColumnSet* column_set = layout->AddColumnSet(column_set_id); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::USE_PREF, 0, 0); if (!description.empty()) { layout->StartRow(0, column_set_id); views::Label* description_label = new views::Label(description); description_label->SetMultiLine(true); description_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); description_label->SizeToFit(horizontal_space); layout->AddView(new BulletedView(description_label)); } if (details.empty()) return; details_view_ = new DetailsView(horizontal_space, parent_bulleted, lighter_color_details); layout->StartRow(0, column_set_id); layout->AddView(details_view_); for (size_t i = 0; i < details.size(); ++i) details_view_->AddDetail(details[i]); // TODO(meacer): Remove show_expand_link when the experiment is completed. if (show_expand_link) { views::Link* link = new views::Link( l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS)); // Make sure the link width column is as wide as needed for both Show and // Hide details, so that the arrow doesn't shift horizontally when we // toggle. int link_col_width = views::kRelatedControlHorizontalSpacing + std::max(gfx::GetStringWidth( l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS), link->font_list()), gfx::GetStringWidth( l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS), link->font_list())); column_set = layout->AddColumnSet(++column_set_id); // Padding to the left of the More Details column. If the parent is using // bullets for its items, then a padding of one unit will make the child // item (which has no bullet) look like a sibling of its parent. Therefore // increase the indentation by one more unit to show that it is in fact a // child item (with no missing bullet) and not a sibling. column_set->AddPaddingColumn( 0, views::kRelatedControlHorizontalSpacing * (parent_bulleted ? 2 : 1)); // The More Details column. column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::FIXED, link_col_width, link_col_width); // The Up/Down arrow column. column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::USE_PREF, 0, 0); // Add the More Details link. layout->StartRow(0, column_set_id); more_details_ = link; more_details_->set_listener(this); more_details_->SetHorizontalAlignment(gfx::ALIGN_LEFT); layout->AddView(more_details_); // Add the arrow after the More Details link. ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); arrow_toggle_ = new views::ImageButton(this); arrow_toggle_->SetImage(views::Button::STATE_NORMAL, rb.GetImageSkiaNamed(IDR_DOWN_ARROW)); layout->AddView(arrow_toggle_); } } ExpandableContainerView::~ExpandableContainerView() { } void ExpandableContainerView::ButtonPressed( views::Button* sender, const ui::Event& event) { ToggleDetailLevel(); } void ExpandableContainerView::LinkClicked( views::Link* source, int event_flags) { ToggleDetailLevel(); } void ExpandableContainerView::AnimationProgressed( const gfx::Animation* animation) { DCHECK_EQ(&slide_animation_, animation); if (details_view_) details_view_->AnimateToState(animation->GetCurrentValue()); } void ExpandableContainerView::AnimationEnded(const gfx::Animation* animation) { if (arrow_toggle_) { if (animation->GetCurrentValue() != 0.0) { arrow_toggle_->SetImage( views::Button::STATE_NORMAL, ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_UP_ARROW)); } else { arrow_toggle_->SetImage( views::Button::STATE_NORMAL, ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_DOWN_ARROW)); } } if (more_details_) { more_details_->SetText(expanded_ ? l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS) : l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS)); } } void ExpandableContainerView::ChildPreferredSizeChanged(views::View* child) { owner_->ContentsChanged(); } void ExpandableContainerView::ToggleDetailLevel() { expanded_ = !expanded_; if (slide_animation_.IsShowing()) slide_animation_.Hide(); else slide_animation_.Show(); } void ExpandableContainerView::ExpandWithoutAnimation() { expanded_ = true; details_view_->AnimateToState(1.0); }
38.531882
80
0.658339
[ "vector", "transform" ]
a33fbe94f29efaffced27d8dcc42140bc2019be2
1,821
cpp
C++
libmtcnn/utils.cpp
prostoiChelovek/MTCNN
2e0d10322cdc695ff6c263545aacf99e5c21795d
[ "Apache-2.0" ]
194
2018-01-31T12:01:10.000Z
2022-03-29T10:03:56.000Z
libmtcnn/utils.cpp
prostoiChelovek/MTCNN
2e0d10322cdc695ff6c263545aacf99e5c21795d
[ "Apache-2.0" ]
8
2018-02-13T07:26:40.000Z
2020-06-27T14:04:50.000Z
libmtcnn/utils.cpp
prostoiChelovek/MTCNN
2e0d10322cdc695ff6c263545aacf99e5c21795d
[ "Apache-2.0" ]
92
2018-02-17T21:42:15.000Z
2021-11-18T14:28:50.000Z
/* Copyright (C) 2017 Open Intelligent Machines Co.,Ltd 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 <string> #include <vector> #include <iostream> #include <iomanip> #include <fstream> #include <opencv2/opencv.hpp> #include <sys/time.h> unsigned long get_cur_time(void) { struct timeval tv; unsigned long ts; gettimeofday(&tv,NULL); ts=tv.tv_sec*1000000+tv.tv_usec; return ts; } void save_float(const char * name, const float * data, int size) { char fname[128]; sprintf(fname,"%s",name); std::cout<<"save data to "<<fname<<" size " <<size<<std::endl; std::ofstream of; of.open(fname); for(int i=0;i<size;i++) { of<<std::setprecision(6)<<data[i]<<","<<std::endl; } of.close(); } void save_img(const char * name, void * p_img) { const cv::Mat& img= *(cv::Mat *)p_img; int row=img.rows; int col=img.cols; int chan=img.channels(); int sz=row*col*chan; char fname[128]; int data; sprintf(fname,"%s",name); std::cout<<"save data to "<<fname<<" size " <<sz<<std::endl; std::ofstream of; of.open(fname); col=col*chan; if(img.isContinuous()) { col=col*row; row=1; } for(int i=0;i<row;i++) { const unsigned char * p=img.ptr<unsigned char >(i); for(int j=0;j<col;j++) { data=p[j]; of<<data<<","<<std::endl; } } of.close(); }
18.393939
74
0.660626
[ "vector" ]
a3469dd05898afd1c0d6553bf646e19808838e35
10,289
cpp
C++
src/Gui/WidgetNode.cpp
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
1
2018-07-20T03:56:15.000Z
2018-07-20T03:56:15.000Z
src/Gui/WidgetNode.cpp
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
null
null
null
src/Gui/WidgetNode.cpp
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
null
null
null
// // WidgetNode.cpp // HarmonicMotionGui // // Created by Tim Murray-Browne on 03/02/2014. // // #include "WidgetNode.h" #include <QLabel> #include <QLineEdit> #include "Node.h" #include "WidgetParameter.h" #include <QFile> #include <QTimer> #include "Common.h" #include <QStyleOption> #include <QPainter> #include "Utilities.h" #include "WidgetOutlet.h" #include <algorithm> #include "WidgetPatchArea.h" #include "WidgetInlet.h" #include "Pipeline.h" #include <QAction> namespace hm { WidgetNode::WidgetNode(NodePtr node, WidgetPatchArea* patchArea) : QWidget(patchArea) , mIsDragging(false) , mNode(node) , mMainArea(nullptr) , mPatchArea(patchArea) // , mHasBeenErased(false) , mNameWidget(nullptr) { assert(node != nullptr); loadStyleSheet(); setObjectName("WidgetNode"); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); QLabel* typeLabel = new QLabel(str(mNode->type())); typeLabel->setObjectName("LabelNodeType"); typeLabel->setToolTip(("<span>"+mNode->description()+"</span>").c_str()); mNameWidget = new QLineEdit(str(mNode->name())); QVBoxLayout* inletsLayout = new QVBoxLayout; QVBoxLayout* outletsLayout = new QVBoxLayout; inletsLayout->setAlignment(Qt::AlignTop); outletsLayout->setAlignment(Qt::AlignTop); for (ParameterPtr p : node->parameters()) { WidgetBaseParameter* widget = WidgetBaseParameter::create(p); QLabel* label = new QLabel(str(p->name())); widget->setToolTip(str(p->description())); label->setToolTip(str(p->description())); mWidgetParameters.push_back(QPair<QLabel*, WidgetBaseParameter*>(label, widget)); BOOST_VERIFY(connect(widget, SIGNAL(parameterVisibilityChanged(WidgetBaseParameter*, bool)), this, SLOT(parameterVisibilityChanged(WidgetBaseParameter*, bool)))); } assert(parentWidget() != nullptr); for (InletPtr inlet: mNode->inlets()) { WidgetInlet* w = new WidgetInlet(inlet, this); mWidgetInlets.push_back(w); inletsLayout->addWidget(w); } for (OutletPtr outlet: mNode->outlets()) { WidgetOutlet* w = new WidgetOutlet(outlet, this); mWidgetOutlets.push_back(w); outletsLayout->addWidget(w); } preventNegativePosition(); // Setup main area mMainArea = new QWidget; mMainLayout = new QGridLayout; mMainArea->setLayout(mMainLayout); repaint(); mMainLayout->addWidget(typeLabel, 0, 0); mMainLayout->addWidget(mNameWidget, 0, 1); for (QPair<QLabel*, WidgetBaseParameter*> p: mWidgetParameters) { int row = mMainLayout->rowCount(); mMainLayout->addWidget(p.first, row, 0, Qt::AlignRight); mMainLayout->addWidget(p.second, row, 1, Qt::AlignLeft); if (p.second->isParameterVisible()) { p.first->show(); p.second->show(); } else { p.first->hide(); p.second->hide(); } } mMainLayout->setRowStretch(mMainLayout->rowCount(), 1); update(); mMainArea->setObjectName("mMainArea"); setFocusPolicy(Qt::ClickFocus); setContextMenuPolicy(Qt::ActionsContextMenu); QHBoxLayout* layout = new QHBoxLayout(this); layout->addLayout(inletsLayout); layout->addWidget(mMainArea); layout->addLayout(outletsLayout); layout->setSpacing(0); layout->setSizeConstraint(QLayout::SetFixedSize); // setLayout(mLayout); // CONNECTIONS bool success(true); success = connect(mNameWidget, SIGNAL(editingFinished()), this, SLOT(nameChangedInGui())); assert(success); success = connect(this, SIGNAL(geometryChanged()), patchArea, SLOT(updateSize())); assert(success); success = connect(this, SIGNAL(beingDragged(WidgetNode*)), patchArea, SLOT(widgetNodeBeingDragged(WidgetNode*))); assert(success); success = connect(this, SIGNAL(newInfoPanelText(QString)), patchArea, SLOT(provideInfoPanelText(QString))); assert(success); // ACTIONS QAction* eraseAction = new QAction("Delete", this); eraseAction->setShortcuts(QList<QKeySequence>() << QKeySequence::Delete << Qt::Key_Backspace); eraseAction->setShortcutContext(Qt::WidgetShortcut); addAction(eraseAction); success = connect(eraseAction, SIGNAL(triggered()), this, SLOT(deleteFromModel())); assert(success); updateFromNodeParams(); Q_EMIT geometryChanged(); // // TODO: temp // QTimer* t = new QTimer(this); // t->setInterval(500); // connect(t, SIGNAL(timeout()), this, SLOT(loadStyleSheet())); // t->start(); } void WidgetNode::parameterVisibilityChanged(WidgetBaseParameter* widget, bool isVisible) { for (QPair<QLabel*, WidgetBaseParameter*> p: mWidgetParameters) { if (p.second->isParameterVisible()) { p.first->show(); p.second->show(); } else { p.first->hide(); p.second->hide(); } } } WidgetNode::~WidgetNode() { hm_debug("WidgetNode destructor for node "+mNode->name()); } void WidgetNode::nameChangedInGui() { mNode->setName(mNameWidget->text().toStdString()); } void WidgetNode::updateFromNodeParams() { Node::Params params = mNode->exportParams(); move(params.guiLocationX, params.guiLocationY); mNameWidget->blockSignals(true); mNameWidget->setText(str(params.name)); mNameWidget->blockSignals(false); } void WidgetNode::deleteFromModel() { mPatchArea->pipeline()->removeNode(mNode); } QSize WidgetNode::sizeHint() const { QSize size = mMainArea->sizeHint(); return QSize(size.width() + (mWidgetOutlets.empty()? 0 : mWidgetOutlets[0]->width()) + (mWidgetInlets.empty()? 0 : mWidgetInlets[0]->width()), size.height()); } void WidgetNode::loadStyleSheet() { QFile file(":/qss/WidgetNode.qss"); // QFile file("/Users/timmb/Documents/Programming/HarmonicMotion/Gui/resources/qss/WidgetNode.qss"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { setStyleSheet(QString::fromUtf8(file.readAll())); } else { hm_error("Failed to load stylesheet WidgetNode.qss"); } } void WidgetNode::paintEvent(QPaintEvent *) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } void WidgetNode::mousePressEvent(QMouseEvent* event) { mIsDragging = mMainArea->geometry().contains(event->pos()); if (mIsDragging) { event->accept(); // do not propagate // if (isWindow()) // mDragOffset = event->globalPos() - pos(); // else mDragOffset = event->pos(); } else { event->ignore(); } } void WidgetNode::mouseMoveEvent(QMouseEvent* event) { if (mIsDragging) { event->accept(); // do not propagate // if (isWindow()) // move(event->globalPos() - mDragOffset); // else // qDebug() << "event->pos"<<event->pos()<<"to parent"<<mapToParent(event->pos())<<"parent pos"<<parentWidget()->pos(); move(mapToParent(event->pos() - mDragOffset)); // Q_EMIT beingDragged(this); } else { event->ignore(); } } void WidgetNode::mouseReleaseEvent(QMouseEvent* event) { if (mIsDragging) { event->accept(); // do not propagate mDragOffset = QPoint(); mIsDragging = false; Q_EMIT geometryChanged(); } } void WidgetNode::resizeEvent(QResizeEvent* event) { } void WidgetNode::moveEvent(QMoveEvent* event) { preventNegativePosition(); // update values in model and allow it to change those values. QPoint pos = event->pos(); Node::Params params = node()->exportParams(); params.guiLocationX = pos.x(); params.guiLocationY = pos.y(); // this function may modify `params` node()->setNodeParams(params); if (params.guiLocationX != pos.x() || params.guiLocationY != pos.y()) { assert(params.guiLocationX >= 0 && params.guiLocationY >= 0); // there's no reason why node will have set x or y to be negative // but it's essential they're non-negative as otherwise we // may enter an infinite recursion where this class and Node // continually adjust each other's position. pos.setX(qMax(0, pos.x())); pos.setY(qMax(0, pos.y())); move(pos); return; } if (mIsDragging) { Q_EMIT beingDragged(this); } if (!mIsDragging) { Q_EMIT geometryChanged(); } mPatchArea->markDirty(); } void WidgetNode::focusInEvent(QFocusEvent* event) { mPatchArea->raise(this); /// this property adds the black border around the widget mMainArea->setProperty("hasFocus", true); // force update of appearance repolish(mMainArea); Q_EMIT newInfoPanelText(str(mNode->toString())); } void WidgetNode::focusOutEvent(QFocusEvent* event) { mMainArea->setProperty("hasFocus", false); // force update of appearance repolish(mMainArea); } void WidgetNode::preventNegativePosition() { // prevent widgets from having negative positions (relative to the // patch area if (pos().x() < 0 || pos().y() < 0) { move(QPoint(std::max(0, pos().x()), std::max(0, pos().y()))); return; } } void WidgetNode::addWidget(QWidget* widget) { mMainLayout->addWidget(widget, mMainLayout->rowCount(), 0, 1, mMainLayout->columnCount()); } // void WidgetNode::layout() // { //// QPoint p(0,0); //// for (auto w: mWidgetInlets) //// { //// w->move(p); //// p += QPoint(0, w->height()); //// } //// if (!mWidgetInlets.empty()) //// { //// p = QPoint(0, mWidgetInlets[0]->width()); //// } //// mInnerBox->move(p); //// p += QPoint(0, mInnerBox->width()); //// for (auto w: mWidgetInlets) //// { //// w->move(p); //// p += QPoint(0, w->height()); //// } //// //// QPoint p; //// if (mWidgetInlets.size() > 0) //// { //// p = mapToParent(QPoint(- mWidgetInlets[0]->width(), 0)); //// for (auto w: mWidgetInlets) //// { //// w->move(p); //// p += QPoint(0, w->height()); //// } //// } //// //// p = mapToParent(QPoint(width(), 0)); //// for (auto w: mWidgetOutlets) //// { //// w->move(p); //// p += QPoint(0, w->height()); //// } // } }
26.65544
165
0.628341
[ "geometry", "model" ]
a34821815e8d5e8d18fd6e4bb9d43bacda06d898
957
hpp
C++
GPUSorter/GPUFloatSorter.hpp
elad8a/GPUSorter
f93eae32f2fc303159660aa76af4b03cbb79e6fc
[ "MIT" ]
null
null
null
GPUSorter/GPUFloatSorter.hpp
elad8a/GPUSorter
f93eae32f2fc303159660aa76af4b03cbb79e6fc
[ "MIT" ]
null
null
null
GPUSorter/GPUFloatSorter.hpp
elad8a/GPUSorter
f93eae32f2fc303159660aa76af4b03cbb79e6fc
[ "MIT" ]
null
null
null
#pragma once #include "sort_types.hpp" namespace HPC { class GPUFloatSorter { public: GPUFloatSorter(boost::compute::command_queue& queue, std::size_t maxElements); void Sort(boost::compute::vector<int>& src, boost::compute::vector<int>& dst, boost::compute::command_queue& queue); private: boost::compute::vector<partition_segment> _segments1; boost::compute::vector<partition_segment> _segments2; boost::compute::vector<partition_segment_result> _results1; boost::compute::vector<partition_segment_result> _results2; boost::compute::vector<partition_segment_chunk_ex> _chunks; boost::compute::vector<bitonic_segment> _bitonicSegments; boost::compute::kernel _sortKernel; std::vector<partition_segment> _hostSegments; std::vector<partition_segment_result> _hostResults; std::vector<partition_segment_chunk_ex> _hostChunks; }; }
30.870968
124
0.705329
[ "vector" ]
a34aa2f0ddc252927538645b3af6677e8592489f
72,086
cxx
C++
Charts/Core/vtkChartXY.cxx
isi-research/VTK
56a615b4e54233b65072d3eddd89dd6c0df78dd6
[ "BSD-3-Clause" ]
null
null
null
Charts/Core/vtkChartXY.cxx
isi-research/VTK
56a615b4e54233b65072d3eddd89dd6c0df78dd6
[ "BSD-3-Clause" ]
null
null
null
Charts/Core/vtkChartXY.cxx
isi-research/VTK
56a615b4e54233b65072d3eddd89dd6c0df78dd6
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkChartXY.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkChartXY.h" #include "vtkBrush.h" #include "vtkChartSelectionHelper.h" #include "vtkColorSeries.h" #include "vtkContext2D.h" #include "vtkPen.h" #include "vtkContextClip.h" #include "vtkContextKeyEvent.h" #include "vtkContextMouseEvent.h" #include "vtkContextScene.h" #include "vtkContextTransform.h" #include "vtkMath.h" #include "vtkPoints2D.h" #include "vtkTransform2D.h" #include "vtkVector.h" #include "vtkVectorOperators.h" #include "vtkContextMapper2D.h" #include "vtkPlotArea.h" #include "vtkPlotBag.h" #include "vtkPlotBar.h" #include "vtkPlotFunctionalBag.h" #include "vtkPlotLine.h" #include "vtkPlotPoints.h" #include "vtkPlotStacked.h" #include "vtkAxis.h" #include "vtkChartLegend.h" #include "vtkPlotGrid.h" #include "vtkTooltipItem.h" #include "vtkDataSetAttributes.h" #include "vtkIdTypeArray.h" #include "vtkTable.h" #include "vtkAnnotationLink.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkStdString.h" #include "vtkTextProperty.h" #include "vtkDataArray.h" #include "vtkStringArray.h" // My STL containers #include <algorithm> #include <vector> //----------------------------------------------------------------------------- class vtkChartXYPrivate { public: vtkChartXYPrivate() { this->Colors = vtkSmartPointer<vtkColorSeries>::New(); this->Clip = vtkSmartPointer<vtkContextClip>::New(); this->Borders[0] = 60; this->Borders[1] = 50; this->Borders[2] = 20; this->Borders[3] = 20; } vtkPlot* GetPlotByColumn(vtkIdType columnId) { std::vector<vtkPlot*>::iterator it = this->plots.begin(); for (; it != this->plots.end(); ++it) { vtkPlot* plot = *it; vtkTable* table = plot->GetInput(); const int idx = 1; // column if (table && table->GetColumn(columnId) == plot->GetData()->GetInputAbstractArrayToProcess(idx, table)) { return plot; } } return 0; } std::vector<vtkPlot*> plots; // Charts can contain multiple plots of data std::vector<vtkContextTransform*> PlotCorners; // Stored by corner... std::vector<vtkAxis*> axes; // Charts can contain multiple axes vtkSmartPointer<vtkColorSeries> Colors; // Colors in the chart vtkSmartPointer<vtkContextClip> Clip; // Colors in the chart int Borders[4]; }; //----------------------------------------------------------------------------- vtkStandardNewMacro(vtkChartXY); //----------------------------------------------------------------------------- vtkChartXY::vtkChartXY() { this->ChartPrivate = new vtkChartXYPrivate; this->AutoAxes = true; this->HiddenAxisBorder = 20; // The plots are drawn in a clipped, transformed area. this->AddItem(this->ChartPrivate->Clip); // The grid is drawn first in this clipped, transformed area. vtkPlotGrid* grid1 = vtkPlotGrid::New(); this->ChartPrivate->Clip->AddItem(grid1); grid1->Delete(); // The second grid for the far side/top axis vtkPlotGrid* grid2 = vtkPlotGrid::New(); this->ChartPrivate->Clip->AddItem(grid2); grid2->Delete(); // Set up the bottom-left transform, the rest are often not required (set up // on demand if used later). Add it as a child item, rendered automatically. vtkSmartPointer<vtkContextTransform> corner = vtkSmartPointer<vtkContextTransform>::New(); this->ChartPrivate->PlotCorners.push_back(corner); this->ChartPrivate->Clip->AddItem(corner); // Child list maintains ownership. // Next is the axes for (int i = 0; i < 4; ++i) { this->ChartPrivate->axes.push_back(vtkAxis::New()); // By default just show the left and bottom axes this->ChartPrivate->axes.back()->SetVisible(i < 2 ? true : false); this->AttachAxisRangeListener(this->ChartPrivate->axes.back()); this->AddItem(this->ChartPrivate->axes.back()); } this->ChartPrivate->axes[vtkAxis::LEFT]->SetPosition(vtkAxis::LEFT); this->ChartPrivate->axes[vtkAxis::BOTTOM]->SetPosition(vtkAxis::BOTTOM); this->ChartPrivate->axes[vtkAxis::RIGHT]->SetPosition(vtkAxis::RIGHT); this->ChartPrivate->axes[vtkAxis::TOP]->SetPosition(vtkAxis::TOP); // Set up the x and y axes - should be configured based on data this->ChartPrivate->axes[vtkAxis::LEFT]->SetTitle("Y Axis"); this->ChartPrivate->axes[vtkAxis::BOTTOM]->SetTitle("X Axis"); grid1->SetXAxis(this->ChartPrivate->axes[vtkAxis::BOTTOM]); grid1->SetYAxis(this->ChartPrivate->axes[vtkAxis::LEFT]); grid2->SetXAxis(this->ChartPrivate->axes[vtkAxis::TOP]); grid2->SetYAxis(this->ChartPrivate->axes[vtkAxis::RIGHT]); // Then the legend is drawn this->Legend = vtkSmartPointer<vtkChartLegend>::New(); this->Legend->SetChart(this); this->Legend->SetVisible(false); this->AddItem(this->Legend); this->PlotTransformValid = false; this->DrawBox = false; this->DrawSelectionPolygon = false; this->DrawNearestPoint = false; this->DrawAxesAtOrigin = false; this->BarWidthFraction = 0.8f; this->Tooltip = vtkSmartPointer<vtkTooltipItem>::New(); this->Tooltip->SetVisible(false); this->AddItem(this->Tooltip); this->ForceAxesToBounds = false; this->ZoomWithMouseWheel = true; this->AdjustLowerBoundForLogPlot = false; } //----------------------------------------------------------------------------- vtkChartXY::~vtkChartXY() { for (unsigned int i = 0; i < this->ChartPrivate->plots.size(); ++i) { this->ChartPrivate->plots[i]->Delete(); } for (size_t i = 0; i < 4; ++i) { this->ChartPrivate->axes[i]->Delete(); } delete this->ChartPrivate; this->ChartPrivate = 0; } //----------------------------------------------------------------------------- void vtkChartXY::Update() { // Perform any necessary updates that are not graphical // Update the plots if necessary for (size_t i = 0; i < this->ChartPrivate->plots.size(); ++i) { this->ChartPrivate->plots[i]->Update(); } this->Legend->Update(); // Update the selections if necessary. if (this->AnnotationLink) { this->AnnotationLink->Update(); vtkSelection* selection = vtkSelection::SafeDownCast(this->AnnotationLink->GetOutputDataObject(2)); // Two major selection methods - row based or plot based. if (this->SelectionMethod == vtkChart::SELECTION_ROWS) { vtkSelectionNode* node = selection->GetNumberOfNodes() > 0 ? selection->GetNode(0) : NULL; vtkIdTypeArray* idArray = node ? vtkArrayDownCast<vtkIdTypeArray>(node->GetSelectionList()) : NULL; std::vector<vtkPlot*>::iterator it = this->ChartPrivate->plots.begin(); for (; it != this->ChartPrivate->plots.end(); ++it) { // Use the first selection node for all plots to select the rows. (*it)->SetSelection(idArray); } } else if (this->SelectionMethod == vtkChart::SELECTION_PLOTS) { for (unsigned int i = 0; i < selection->GetNumberOfNodes(); ++i) { vtkSelectionNode* node = selection->GetNode(i); vtkIdTypeArray* idArray = vtkArrayDownCast<vtkIdTypeArray>(node->GetSelectionList()); vtkPlot* selectionPlot = vtkPlot::SafeDownCast(node->GetProperties()->Get(vtkSelectionNode::PROP())); // Now iterate through the plots to update selection data std::vector<vtkPlot*>::iterator it = this->ChartPrivate->plots.begin(); for (; it != this->ChartPrivate->plots.end(); ++it) { if (selectionPlot == *it) { (*it)->SetSelection(idArray); } } } } else if (this->SelectionMethod == vtkChart::SELECTION_COLUMNS) { // Retrieve all the selected plots std::vector<vtkPlot*> selectedPlots; for (unsigned int i = 0; i < selection->GetNumberOfNodes(); ++i) { vtkSelectionNode* node = selection->GetNode(i); vtkIdTypeArray* selectedColumns = vtkArrayDownCast<vtkIdTypeArray>(node->GetSelectionList()); vtkIdType* ptr = reinterpret_cast<vtkIdType*>(selectedColumns->GetVoidPointer(0)); for (vtkIdType j = 0; j < selectedColumns->GetNumberOfTuples(); ++j) { vtkPlot* selectedPlot = this->ChartPrivate->GetPlotByColumn(ptr[j]); if (selectedPlot) { selectedPlots.push_back(selectedPlot); } } } // Now iterate through the plots to update selection data std::vector<vtkPlot*>::iterator it = this->ChartPrivate->plots.begin(); for (; it != this->ChartPrivate->plots.end(); ++it) { vtkPlot* plot = *it; vtkIdTypeArray* plotSelection = 0; bool ownPlotSelection = false; bool isSelected = std::find(selectedPlots.begin(), selectedPlots.end(), plot) != selectedPlots.end(); if (isSelected) { static int idx = 1; // y vtkAbstractArray* column = plot->GetData()->GetInputAbstractArrayToProcess(idx, plot->GetInput()); plotSelection = plot->GetSelection(); if (!plotSelection || plotSelection->GetNumberOfTuples() != column->GetNumberOfTuples()) { plotSelection = vtkIdTypeArray::New(); ownPlotSelection = true; for (vtkIdType j = 0; j < column->GetNumberOfTuples(); ++j) { plotSelection->InsertNextValue(j); } } } plot->SetSelection(plotSelection); if (ownPlotSelection) { plotSelection->Delete(); } } } } else { vtkDebugMacro("No annotation link set."); } this->CalculateBarPlots(); if (this->AutoAxes) { vtkTuple<bool, 4> visibilities(false); for (int i = 0; i < static_cast<int>(this->ChartPrivate->PlotCorners.size()); ++i) { int visible = 0; for (unsigned int j = 0; j < this->ChartPrivate->PlotCorners[i]->GetNumberOfItems(); ++j) { if (vtkPlot::SafeDownCast(this->ChartPrivate->PlotCorners[i]->GetItem(j))->GetVisible()) { ++visible; } } if (visible) { visibilities[i % 4] = true; visibilities[(i + 1) % 4] = true; } } for (int i = 0; i < 4; ++i) { this->ChartPrivate->axes[i]->SetVisible(visibilities[i]); } } } //----------------------------------------------------------------------------- bool vtkChartXY::Paint(vtkContext2D* painter) { // This is where everything should be drawn, or dispatched to other methods. vtkDebugMacro(<< "Paint event called."); if (!this->Visible) { // The geometry of the chart must be valid before anything can be drawn return false; } vtkVector2i geometry(0, 0); bool recalculateTransform = false; if (this->LayoutStrategy == vtkChart::FILL_SCENE) { geometry = vtkVector2i(this->GetScene()->GetSceneWidth(), this->GetScene()->GetSceneHeight()); if (geometry.GetX() != this->Geometry[0] || geometry.GetY() != this->Geometry[1]) { recalculateTransform = true; } this->SetSize(vtkRectf(0.0, 0.0, geometry.GetX(), geometry.GetY())); } int visiblePlots = 0; for (size_t i = 0; i < this->ChartPrivate->plots.size(); ++i) { if (this->ChartPrivate->plots[i]->GetVisible()) { ++visiblePlots; } } if (visiblePlots == 0 && !this->RenderEmpty) { // Nothing to plot, so don't draw anything. return false; } this->Update(); this->UpdateLayout(painter); // Axes may have changed during updateLayout if (this->MTime < this->ChartPrivate->axes[0]->GetMTime()) { // Cause the plot transform to be recalculated if necessary recalculateTransform = true; } // Recalculate the plot transform, min and max values if necessary if (!this->PlotTransformValid) { this->RecalculatePlotBounds(); recalculateTransform = true; } if (this->UpdateLayout(painter) || recalculateTransform) { this->RecalculatePlotTransforms(); } // Now that plot transforms, including whether to use log scaling and the // shift-scale factors, have been updated, we give the vtkPlot instances an // opportunity to update caches. for (size_t i = 0; i < this->ChartPrivate->plots.size(); ++i) { this->ChartPrivate->plots[i]->UpdateCache(); } // Update the clipping if necessary this->ChartPrivate->Clip->SetClip(this->Point1[0], this->Point1[1], this->Point2[0] - this->Point1[0], this->Point2[1] - this->Point1[1]); // draw background if (this->BackgroundBrush) { painter->GetPen()->SetLineType(vtkPen::NO_PEN); painter->ApplyBrush(this->BackgroundBrush); painter->DrawRect(this->Point1[0], this->Point1[1], this->Geometry[0], this->Geometry[1]); } // Use the scene to render most of the chart. this->PaintChildren(painter); // Draw the selection box if necessary if (this->DrawBox) { painter->GetBrush()->SetColor(255, 255, 255, 0); painter->GetPen()->SetColor(0, 0, 0, 255); painter->GetPen()->SetWidth(1.0); painter->GetPen()->SetLineType(vtkPen::SOLID_LINE); painter->DrawRect(this->MouseBox.GetX(), this->MouseBox.GetY(), this->MouseBox.GetWidth(), this->MouseBox.GetHeight()); } // Draw the selection polygon if necessary if (this->DrawSelectionPolygon) { painter->GetBrush()->SetColor(255, 0, 0, 0); painter->GetPen()->SetColor(0, 255, 0, 255); painter->GetPen()->SetWidth(2.0); painter->GetPen()->SetLineType(vtkPen::SOLID_LINE); const vtkContextPolygon& polygon = this->SelectionPolygon; // draw each line segment for (vtkIdType i = 0; i < polygon.GetNumberOfPoints() - 1; i++) { const vtkVector2f& a = polygon.GetPoint(i); const vtkVector2f& b = polygon.GetPoint(i + 1); painter->DrawLine(a.GetX(), a.GetY(), b.GetX(), b.GetY()); } // draw a line from the end to the start if (polygon.GetNumberOfPoints() >= 3) { const vtkVector2f& start = polygon.GetPoint(0); const vtkVector2f& end = polygon.GetPoint(polygon.GetNumberOfPoints() - 1); painter->DrawLine(start.GetX(), start.GetY(), end.GetX(), end.GetY()); } } if (this->Title) { int offset = 0; // title margin. vtkAxis* topAxis = this->ChartPrivate->axes[vtkAxis::TOP]; if (topAxis->GetVisible()) { vtkRectf bounds = topAxis->GetBoundingRect(painter); offset += static_cast<int>(bounds.GetHeight()); } vtkPoints2D* rect = vtkPoints2D::New(); rect->InsertNextPoint(this->Point1[0], this->Point2[1] + offset); rect->InsertNextPoint(this->Point2[0] - this->Point1[0], 10); painter->ApplyTextProp(this->TitleProperties); painter->DrawStringRect(rect, this->Title); rect->Delete(); } return true; } //----------------------------------------------------------------------------- void vtkChartXY::CalculateBarPlots() { // Calculate the width, spacing and offsets for the bar plot - they are grouped size_t n = this->ChartPrivate->plots.size(); std::vector<vtkPlotBar*> bars; for (size_t i = 0; i < n; ++i) { vtkPlotBar* bar = vtkPlotBar::SafeDownCast(this->ChartPrivate->plots[i]); if (bar && bar->GetVisible()) { bars.push_back(bar); } } if (!bars.empty()) { // We have some bar plots - work out offsets etc. float barWidth = 0.1; vtkPlotBar* bar = bars[0]; if (!bar->GetUseIndexForXSeries()) { vtkTable* table = bar->GetData()->GetInput(); if (table) { vtkDataArray* x = bar->GetData()->GetInputArrayToProcess(0, table); if (x && x->GetNumberOfTuples() > 1) { double x0 = x->GetTuple1(0); double x1 = x->GetTuple1(1); float width = static_cast<float>(fabs(x1 - x0) * this->BarWidthFraction); barWidth = width / bars.size(); } } } else { barWidth = 1.0f / bars.size() * this->BarWidthFraction; } // Now set the offsets and widths on each bar // The offsetIndex deals with the fact that half the bars // must shift to the left of the point and half to the right int offsetIndex = static_cast<int>(bars.size() - 1); for (size_t i = 0; i < bars.size(); ++i) { bars[i]->SetWidth(barWidth); bars[i]->SetOffset(offsetIndex * (barWidth / 2)); // Increment by two since we need to shift by half widths // but make room for entire bars. Increment backwards because // offsets are always subtracted and Positive offsets move // the bar leftwards. Negative offsets will shift the bar // to the right. offsetIndex -= 2; // bars[i]->SetOffset(float(bars.size()-i-1)*(barWidth/2)); } } } //----------------------------------------------------------------------------- void vtkChartXY::RecalculatePlotTransforms() { for (int i = 0; i < int(this->ChartPrivate->PlotCorners.size()); ++i) { if (this->ChartPrivate->PlotCorners[i]->GetNumberOfItems()) { vtkAxis* xAxis = 0; vtkAxis* yAxis = 0; // Get the appropriate axes, and recalculate the transform. switch (i) { case 0: { xAxis = this->ChartPrivate->axes[vtkAxis::BOTTOM]; yAxis = this->ChartPrivate->axes[vtkAxis::LEFT]; break; } case 1: xAxis = this->ChartPrivate->axes[vtkAxis::BOTTOM]; yAxis = this->ChartPrivate->axes[vtkAxis::RIGHT]; break; case 2: xAxis = this->ChartPrivate->axes[vtkAxis::TOP]; yAxis = this->ChartPrivate->axes[vtkAxis::RIGHT]; break; case 3: xAxis = this->ChartPrivate->axes[vtkAxis::TOP]; yAxis = this->ChartPrivate->axes[vtkAxis::LEFT]; break; default: vtkWarningMacro("Error: default case in recalculate plot transforms."); } this->CalculatePlotTransform( xAxis, yAxis, this->ChartPrivate->PlotCorners[i]->GetTransform()); // Now we need to set the scale factor on the plots to ensure they rescale // their input data when necessary. vtkRectd shiftScale( xAxis->GetShift(), yAxis->GetShift(), xAxis->GetScalingFactor(), yAxis->GetScalingFactor()); for (unsigned int j = 0; j < this->ChartPrivate->PlotCorners[i]->GetNumberOfItems(); ++j) { vtkPlot* plot = vtkPlot::SafeDownCast(this->ChartPrivate->PlotCorners[i]->GetItem(j)); if (plot) { plot->SetShiftScale(shiftScale); } } } } this->PlotTransformValid = true; } //----------------------------------------------------------------------------- int vtkChartXY::GetPlotCorner(vtkPlot* plot) { vtkAxis* x = plot->GetXAxis(); vtkAxis* y = plot->GetYAxis(); if (x == this->ChartPrivate->axes[vtkAxis::BOTTOM] && y == this->ChartPrivate->axes[vtkAxis::LEFT]) { return 0; } else if (x == this->ChartPrivate->axes[vtkAxis::BOTTOM] && y == this->ChartPrivate->axes[vtkAxis::RIGHT]) { return 1; } else if (x == this->ChartPrivate->axes[vtkAxis::TOP] && y == this->ChartPrivate->axes[vtkAxis::RIGHT]) { return 2; } else if (x == this->ChartPrivate->axes[vtkAxis::TOP] && y == this->ChartPrivate->axes[vtkAxis::LEFT]) { return 3; } else { // Should never happen. return 4; } } //----------------------------------------------------------------------------- void vtkChartXY::SetPlotCorner(vtkPlot* plot, int corner) { if (corner < 0 || corner > 3) { vtkWarningMacro("Invalid corner specified, should be between 0 and 3: " << corner); return; } if (this->GetPlotCorner(plot) == corner) { return; } this->RemovePlotFromCorners(plot); // Grow the plot corners if necessary while (static_cast<int>(this->ChartPrivate->PlotCorners.size() - 1) < corner) { vtkNew<vtkContextTransform> transform; this->ChartPrivate->PlotCorners.push_back(transform.GetPointer()); this->ChartPrivate->Clip->AddItem(transform.GetPointer()); // Clip maintains ownership. } this->ChartPrivate->PlotCorners[corner]->AddItem(plot); if (corner == 0) { plot->SetXAxis(this->ChartPrivate->axes[vtkAxis::BOTTOM]); plot->SetYAxis(this->ChartPrivate->axes[vtkAxis::LEFT]); } else if (corner == 1) { plot->SetXAxis(this->ChartPrivate->axes[vtkAxis::BOTTOM]); plot->SetYAxis(this->ChartPrivate->axes[vtkAxis::RIGHT]); } else if (corner == 2) { plot->SetXAxis(this->ChartPrivate->axes[vtkAxis::TOP]); plot->SetYAxis(this->ChartPrivate->axes[vtkAxis::RIGHT]); } else if (corner == 3) { plot->SetXAxis(this->ChartPrivate->axes[vtkAxis::TOP]); plot->SetYAxis(this->ChartPrivate->axes[vtkAxis::LEFT]); } this->PlotTransformValid = false; } //----------------------------------------------------------------------------- void vtkChartXY::RecalculatePlotBounds() { // Get the bounds of each plot, and each axis - ordering as laid out below double y1[] = { 0.0, 0.0 }; // left -> 0 double x1[] = { 0.0, 0.0 }; // bottom -> 1 double y2[] = { 0.0, 0.0 }; // right -> 2 double x2[] = { 0.0, 0.0 }; // top -> 3 // Store whether the ranges have been initialized - follows same order bool initialized[] = { false, false, false, false }; std::vector<vtkPlot*>::iterator it; double bounds[4] = { 0.0, 0.0, 0.0, 0.0 }; for (it = this->ChartPrivate->plots.begin(); it != this->ChartPrivate->plots.end(); ++it) { if ((*it)->GetVisible() == false) { continue; } (*it)->GetBounds(bounds); if (bounds[1] - bounds[0] < 0.0) { // skip uninitialized bounds. continue; } int corner = this->GetPlotCorner(*it); // Initialize the appropriate ranges, or push out the ranges if ((corner == 0 || corner == 3)) // left { if (!initialized[0]) { y1[0] = bounds[2]; y1[1] = bounds[3]; initialized[0] = true; } else { if (y1[0] > bounds[2]) // min { y1[0] = bounds[2]; } if (y1[1] < bounds[3]) // max { y1[1] = bounds[3]; } } } if ((corner == 0 || corner == 1)) // bottom { if (!initialized[1]) { x1[0] = bounds[0]; x1[1] = bounds[1]; initialized[1] = true; } else { if (x1[0] > bounds[0]) // min { x1[0] = bounds[0]; } if (x1[1] < bounds[1]) // max { x1[1] = bounds[1]; } } } if ((corner == 1 || corner == 2)) // right { if (!initialized[2]) { y2[0] = bounds[2]; y2[1] = bounds[3]; initialized[2] = true; } else { if (y2[0] > bounds[2]) // min { y2[0] = bounds[2]; } if (y2[1] < bounds[3]) // max { y2[1] = bounds[3]; } } } if ((corner == 2 || corner == 3)) // top { if (!initialized[3]) { x2[0] = bounds[0]; x2[1] = bounds[1]; initialized[3] = true; } else { if (x2[0] > bounds[0]) // min { x2[0] = bounds[0]; } if (x2[1] < bounds[1]) // max { x2[1] = bounds[1]; } } } } // Now set the newly calculated bounds on the axes for (int i = 0; i < 4; ++i) { vtkAxis* axis = this->ChartPrivate->axes[i]; double* range = 0; switch (i) { case 0: range = y1; break; case 1: range = x1; break; case 2: range = y2; break; case 3: range = x2; break; default: return; } if (this->AdjustLowerBoundForLogPlot && axis->GetLogScale() && range[0] <= 0.) { if (range[1] <= 0.) { // All of the data is negative, so we arbitrarily set the axis range to // be positive and show no data range[1] = 1.; } // The minimum value is set to either 4 decades below the max or to 1, // regardless of the true minimum value (which is less than 0) range[0] = (range[1] < 1.e4 ? range[1] / 1.e4 : 1.); } if (this->ForceAxesToBounds) { axis->SetMinimumLimit(range[0]); axis->SetMaximumLimit(range[1]); } if (axis->GetBehavior() == vtkAxis::AUTO && initialized[i]) { axis->SetRange(range[0], range[1]); axis->AutoScale(); } } this->Modified(); } //----------------------------------------------------------------------------- bool vtkChartXY::UpdateLayout(vtkContext2D* painter) { // The main use of this method is currently to query the visible axes for // their bounds, and to update the chart in response to that. bool changed = false; vtkVector2i tileScale = this->Scene->GetLogicalTileScale(); vtkVector2i hiddenAxisBorder = tileScale * this->HiddenAxisBorder; // Axes if (this->LayoutStrategy == vtkChart::FILL_SCENE || this->LayoutStrategy == vtkChart::FILL_RECT) { for (int i = 0; i < 4; ++i) { int border = 0; vtkAxis* axis = this->ChartPrivate->axes[i]; axis->Update(); if (axis->GetVisible()) { vtkRectf bounds = axis->GetBoundingRect(painter); if (i == vtkAxis::TOP || i == vtkAxis::BOTTOM) { // Horizontal axes border = int(bounds.GetHeight()); } else { // Vertical axes border = int(bounds.GetWidth()); } } border += this->GetLegendBorder(painter, i); if (i == vtkAxis::TOP && this->Title) { painter->ApplyTextProp(this->TitleProperties); float bounds[4]; painter->ComputeStringBounds(this->Title, bounds); if (bounds[3] > 0) { border += (5 * tileScale.GetY()) /* title margin */ + bounds[3]; // add the title text height to the border. } } if (i == vtkAxis::TOP || i == vtkAxis::BOTTOM) { border = std::max(border, hiddenAxisBorder.GetY()); } else { border = std::max(border, hiddenAxisBorder.GetX()); } if (this->ChartPrivate->Borders[i] != border) { this->ChartPrivate->Borders[i] = border; changed = true; } } } if (this->DrawAxesAtOrigin) { this->SetBorders(hiddenAxisBorder.GetX(), hiddenAxisBorder.GetY(), this->ChartPrivate->Borders[2], this->ChartPrivate->Borders[3]); // Get the screen coordinates for the origin, and move the axes there. vtkVector2f origin(0.0); vtkTransform2D* transform = this->ChartPrivate->PlotCorners[0]->GetTransform(); transform->TransformPoints(origin.GetData(), origin.GetData(), 1); // Need to clamp the axes in the plot area. if (int(origin[0]) < this->Point1[0]) { origin[0] = this->Point1[0]; } if (int(origin[0]) > this->Point2[0]) { origin[0] = this->Point2[0]; } if (int(origin[1]) < this->Point1[1]) { origin[1] = this->Point1[1]; } if (int(origin[1]) > this->Point2[1]) { origin[1] = this->Point2[1]; } this->ChartPrivate->axes[vtkAxis::BOTTOM]->SetPoint1(this->Point1[0], origin[1]); this->ChartPrivate->axes[vtkAxis::BOTTOM]->SetPoint2(this->Point2[0], origin[1]); this->ChartPrivate->axes[vtkAxis::LEFT]->SetPoint1(origin[0], this->Point1[1]); this->ChartPrivate->axes[vtkAxis::LEFT]->SetPoint2(origin[0], this->Point2[1]); } else { if (this->LayoutStrategy == vtkChart::AXES_TO_RECT) { this->SetBorders(0, 0, 0, 0); this->ChartPrivate->axes[0]->GetBoundingRect(painter); this->ChartPrivate->axes[1]->GetBoundingRect(painter); this->ChartPrivate->axes[2]->GetBoundingRect(painter); this->ChartPrivate->axes[3]->GetBoundingRect(painter); } else { this->SetBorders(this->ChartPrivate->Borders[0], this->ChartPrivate->Borders[1], this->ChartPrivate->Borders[2], this->ChartPrivate->Borders[3]); } // This is where we set the axes up too // Y axis (left) this->ChartPrivate->axes[0]->SetPoint1(this->Point1[0], this->Point1[1]); this->ChartPrivate->axes[0]->SetPoint2(this->Point1[0], this->Point2[1]); // X axis (bottom) this->ChartPrivate->axes[1]->SetPoint1(this->Point1[0], this->Point1[1]); this->ChartPrivate->axes[1]->SetPoint2(this->Point2[0], this->Point1[1]); // Y axis (right) this->ChartPrivate->axes[2]->SetPoint1(this->Point2[0], this->Point1[1]); this->ChartPrivate->axes[2]->SetPoint2(this->Point2[0], this->Point2[1]); // X axis (top) this->ChartPrivate->axes[3]->SetPoint1(this->Point1[0], this->Point2[1]); this->ChartPrivate->axes[3]->SetPoint2(this->Point2[0], this->Point2[1]); for (int i = 0; i < 4; ++i) { this->ChartPrivate->axes[i]->Update(); } } this->SetLegendPosition(this->Legend->GetBoundingRect(painter)); return changed; } //----------------------------------------------------------------------------- int vtkChartXY::GetLegendBorder(vtkContext2D* painter, int axisPosition) { if (!this->Legend->GetVisible() || this->Legend->GetInline()) { return 0; } vtkVector2i tileScale = this->Scene->GetLogicalTileScale(); int padding = 10; vtkVector2i legendSize(0, 0); vtkVector2i legendAlignment( this->Legend->GetHorizontalAlignment(), this->Legend->GetVerticalAlignment()); this->Legend->Update(); vtkRectf rect = this->Legend->GetBoundingRect(painter); legendSize.Set(static_cast<int>(rect.GetWidth()), static_cast<int>(rect.GetHeight())); // Figure out the correct place and alignment based on the legend layout. if (axisPosition == vtkAxis::LEFT && legendAlignment.GetX() == vtkChartLegend::LEFT) { return legendSize.GetX() + padding * tileScale.GetX(); } else if (axisPosition == vtkAxis::RIGHT && legendAlignment.GetX() == vtkChartLegend::RIGHT) { return legendSize.GetX() + padding * tileScale.GetX(); } else if ((axisPosition == vtkAxis::TOP || axisPosition == vtkAxis::BOTTOM) && (legendAlignment.GetX() == vtkChartLegend::LEFT || legendAlignment.GetX() == vtkChartLegend::RIGHT)) { return 0; } else if (axisPosition == vtkAxis::TOP && legendAlignment.GetY() == vtkChartLegend::TOP) { return legendSize.GetY() + padding * tileScale.GetY(); } else if (axisPosition == vtkAxis::BOTTOM && legendAlignment.GetY() == vtkChartLegend::BOTTOM) { return legendSize.GetY() + padding * tileScale.GetY(); } else { return 0; } } //----------------------------------------------------------------------------- void vtkChartXY::SetLegendPosition(const vtkRectf& rect) { // Put the legend in the top corner of the chart vtkVector2f pos(0, 0); int padding = 5; vtkVector2i legendAlignment( this->Legend->GetHorizontalAlignment(), this->Legend->GetVerticalAlignment()); if (legendAlignment[0] == vtkChartLegend::CUSTOM || legendAlignment[1] == vtkChartLegend::CUSTOM) { return; } if (this->Legend->GetInline()) { switch (this->Legend->GetHorizontalAlignment()) { case vtkChartLegend::LEFT: pos.SetX(this->Point1[0]); break; case vtkChartLegend::CENTER: pos.SetX( ((this->Point2[0] - this->Point1[0]) / 2.0) - rect.GetWidth() / 2.0 + this->Point1[0]); break; case vtkChartLegend::RIGHT: default: pos.SetX(this->Point2[0] - rect.GetWidth()); } switch (this->Legend->GetVerticalAlignment()) { case vtkChartLegend::TOP: pos.SetY(this->Point2[1] - rect.GetHeight()); break; case vtkChartLegend::CENTER: pos.SetY( (this->Point2[1] - this->Point1[1]) / 2.0 - rect.GetHeight() / 2.0 + this->Point1[1]); break; case vtkChartLegend::BOTTOM: default: pos.SetY(this->Point1[1]); } } else { // Non-inline legends. if (legendAlignment.GetX() == vtkChartLegend::LEFT) { pos.SetX(this->Point1[0] - this->ChartPrivate->Borders[vtkAxis::LEFT] + padding); } else if (legendAlignment.GetX() == vtkChartLegend::RIGHT) { pos.SetX( this->Point2[0] + this->ChartPrivate->Borders[vtkAxis::RIGHT] - rect.GetWidth() - padding); } else if (legendAlignment.GetX() == vtkChartLegend::CENTER) { pos.SetX( ((this->Point2[0] - this->Point1[0]) / 2.0) - (rect.GetWidth() / 2.0) + this->Point1[0]); // Check for the special case where the legend is on the top or bottom if (legendAlignment.GetY() == vtkChartLegend::TOP) { pos.SetY( this->Point2[1] + this->ChartPrivate->Borders[vtkAxis::TOP] - rect.GetHeight() - padding); } else if (legendAlignment.GetY() == vtkChartLegend::BOTTOM) { pos.SetY(this->Point1[1] - this->ChartPrivate->Borders[vtkAxis::BOTTOM] + padding); } } // Vertical alignment if (legendAlignment.GetX() != vtkChartLegend::CENTER) { if (legendAlignment.GetY() == vtkChartLegend::TOP) { pos.SetY(this->Point2[1] - rect.GetHeight()); } else if (legendAlignment.GetY() == vtkChartLegend::BOTTOM) { pos.SetY(this->Point1[1]); } } if (legendAlignment.GetY() == vtkChartLegend::CENTER) { pos.SetY( ((this->Point2[1] - this->Point1[1]) / 2.0) - (rect.GetHeight() / 2.0) + this->Point1[1]); } } this->Legend->SetPoint(pos); } //----------------------------------------------------------------------------- vtkPlot* vtkChartXY::AddPlot(int type) { // Use a variable to return the object created (or NULL), this is necessary // as the HP compiler is broken (thinks this function does not return) and // the MS compiler generates a warning about unreachable code if a redundant // return is added at the end. vtkPlot* plot = NULL; vtkColor3ub color = this->ChartPrivate->Colors->GetColorRepeating( static_cast<int>(this->ChartPrivate->plots.size())); switch (type) { case LINE: { vtkPlotLine* line = vtkPlotLine::New(); line->GetPen()->SetColor(color.GetData()); plot = line; break; } case POINTS: { vtkPlotPoints* points = vtkPlotPoints::New(); points->GetPen()->SetColor(color.GetData()); plot = points; break; } case BAR: { vtkPlotBar* bar = vtkPlotBar::New(); bar->GetBrush()->SetColor(color.GetData()); plot = bar; break; } case FUNCTIONALBAG: { vtkPlotFunctionalBag* bag = vtkPlotFunctionalBag::New(); bag->GetPen()->SetColor(color.GetData()); bag->GetBrush()->SetColor(color.GetData()); plot = bag; break; } case STACKED: { vtkPlotStacked* stacked = vtkPlotStacked::New(); stacked->SetParent(this); stacked->GetBrush()->SetColor(color.GetData()); plot = stacked; break; } case BAG: { vtkPlotBag* bag = vtkPlotBag::New(); bag->SetParent(this); bag->GetBrush()->SetColor(color.GetData()); plot = bag; break; } case AREA: { vtkPlotArea* area = vtkPlotArea::New(); area->SetParent(this); area->GetBrush()->SetColor(color.GetData()); plot = area; break; } default: plot = NULL; } if (plot) { this->AddPlot(plot); plot->Delete(); } return plot; } //----------------------------------------------------------------------------- vtkIdType vtkChartXY::AddPlot(vtkPlot* plot) { if (plot == NULL) { return -1; } plot->Register(this); this->ChartPrivate->plots.push_back(plot); vtkIdType plotIndex = static_cast<vtkIdType>(this->ChartPrivate->plots.size() - 1); this->SetPlotCorner(plot, 0); // Ensure that the bounds are recalculated this->PlotTransformValid = false; // Mark the scene as dirty if (this->Scene) { this->Scene->SetDirty(true); } return plotIndex; } //----------------------------------------------------------------------------- bool vtkChartXY::RemovePlot(vtkIdType index) { if (index < static_cast<vtkIdType>(this->ChartPrivate->plots.size())) { this->RemovePlotFromCorners(this->ChartPrivate->plots[index]); this->ChartPrivate->plots[index]->Delete(); this->ChartPrivate->plots.erase(this->ChartPrivate->plots.begin() + index); // Ensure that the bounds are recalculated this->PlotTransformValid = false; if (this->Scene) { // Mark the scene as dirty this->Scene->SetDirty(true); } return true; } else { return false; } } //----------------------------------------------------------------------------- void vtkChartXY::ClearPlots() { for (unsigned int i = 0; i < this->ChartPrivate->plots.size(); ++i) { this->ChartPrivate->plots[i]->Delete(); } this->ChartPrivate->plots.clear(); // Clear the corners too for (int i = 0; i < int(this->ChartPrivate->PlotCorners.size()); ++i) { this->ChartPrivate->PlotCorners[i]->ClearItems(); if (i > 0) { this->ChartPrivate->Clip->RemoveItem(this->ChartPrivate->PlotCorners[i]); } } this->ChartPrivate->PlotCorners.resize(1); // Ensure that the bounds are recalculated this->PlotTransformValid = false; if (this->Scene) { // Mark the scene as dirty this->Scene->SetDirty(true); } } //----------------------------------------------------------------------------- vtkPlot* vtkChartXY::GetPlot(vtkIdType index) { if (static_cast<vtkIdType>(this->ChartPrivate->plots.size()) > index) { return this->ChartPrivate->plots[index]; } else { return NULL; } } //----------------------------------------------------------------------------- vtkIdType vtkChartXY::GetPlotIndex(vtkPlot* plot) { int corner = this->GetPlotCorner(plot); return corner >= 0 && corner < 4 ? this->ChartPrivate->PlotCorners[corner]->GetItemIndex(plot) : static_cast<vtkIdType>(-1); } //----------------------------------------------------------------------------- vtkIdType vtkChartXY::RaisePlot(vtkPlot* plot) { vtkIdType plotIndex = this->GetPlotIndex(plot); int corner = this->GetPlotCorner(plot); if (corner < 0 || corner >= 4) { return plotIndex; } return this->ChartPrivate->PlotCorners[corner]->Raise(plotIndex); } //----------------------------------------------------------------------------- vtkIdType vtkChartXY::StackPlotAbove(vtkPlot* plot, vtkPlot* under) { vtkIdType plotIndex = this->GetPlotIndex(plot); vtkIdType underIndex = this->GetPlotIndex(under); int corner = this->GetPlotCorner(plot); if (corner < 0 || corner >= 4 || underIndex != this->GetPlotCorner(under)) { return plotIndex; } return this->ChartPrivate->PlotCorners[corner]->StackAbove(plotIndex, underIndex); } //----------------------------------------------------------------------------- vtkIdType vtkChartXY::LowerPlot(vtkPlot* plot) { vtkIdType plotIndex = this->GetPlotIndex(plot); int corner = this->GetPlotCorner(plot); if (corner < 0 || corner >= 4) { return plotIndex; } return this->ChartPrivate->PlotCorners[corner]->Lower(plotIndex); } //----------------------------------------------------------------------------- vtkIdType vtkChartXY::StackPlotUnder(vtkPlot* plot, vtkPlot* above) { vtkIdType plotIndex = this->GetPlotIndex(plot); vtkIdType aboveIndex = this->GetPlotIndex(above); int corner = this->GetPlotCorner(plot); if (corner < 0 || corner >= 4 || corner != this->GetPlotCorner(above)) { return plotIndex; } return this->ChartPrivate->PlotCorners[corner]->StackUnder(plotIndex, aboveIndex); } //----------------------------------------------------------------------------- void vtkChartXY::SetShowLegend(bool visible) { this->vtkChart::SetShowLegend(visible); this->Legend->SetVisible(visible); } //----------------------------------------------------------------------------- vtkChartLegend* vtkChartXY::GetLegend() { return this->Legend; } //----------------------------------------------------------------------------- void vtkChartXY::SetTooltip(vtkTooltipItem* tooltip) { if (tooltip == this->Tooltip) { // nothing to change return; } if (this->Tooltip) { // remove current tooltip from scene this->RemoveItem(this->Tooltip); } this->Tooltip = tooltip; if (this->Tooltip) { // add new tooltip to scene this->AddItem(this->Tooltip); } } //----------------------------------------------------------------------------- vtkTooltipItem* vtkChartXY::GetTooltip() { return this->Tooltip; } //----------------------------------------------------------------------------- vtkIdType vtkChartXY::GetNumberOfPlots() { return static_cast<vtkIdType>(this->ChartPrivate->plots.size()); } //----------------------------------------------------------------------------- vtkAxis* vtkChartXY::GetAxis(int axisIndex) { if (axisIndex < 4) { return this->ChartPrivate->axes[axisIndex]; } else { return NULL; } } //----------------------------------------------------------------------------- vtkIdType vtkChartXY::GetNumberOfAxes() { return 4; } //----------------------------------------------------------------------------- void vtkChartXY::RecalculateBounds() { // Ensure that the bounds are recalculated this->PlotTransformValid = false; if (this->Scene) { // Mark the scene as dirty this->Scene->SetDirty(true); } } //----------------------------------------------------------------------------- void vtkChartXY::SetSelectionMethod(int method) { if (method == this->SelectionMethod) { return; } if (method == vtkChart::SELECTION_PLOTS) { // Clear the selection on the plots which may be shared between all of them. // Now iterate through the plots to update selection data std::vector<vtkPlot*>::iterator it = this->ChartPrivate->plots.begin(); for (; it != this->ChartPrivate->plots.end(); ++it) { (*it)->SetSelection(NULL); } } Superclass::SetSelectionMethod(method); } //----------------------------------------------------------------------------- bool vtkChartXY::Hit(const vtkContextMouseEvent& mouse) { if (!this->Interactive) { return false; } vtkVector2i pos(mouse.GetScreenPos()); if (pos[0] > this->Point1[0] && pos[0] < this->Point2[0] && pos[1] > this->Point1[1] && pos[1] < this->Point2[1]) { return true; } else { return false; } } //----------------------------------------------------------------------------- bool vtkChartXY::MouseEnterEvent(const vtkContextMouseEvent&) { // Find the nearest point on the curves and snap to it this->DrawNearestPoint = true; return true; } //----------------------------------------------------------------------------- bool vtkChartXY::MouseMoveEvent(const vtkContextMouseEvent& mouse) { // Iterate through each corner, and check for a nearby point for (size_t i = 0; i < this->ChartPrivate->PlotCorners.size(); ++i) { if (this->ChartPrivate->PlotCorners[i]->MouseMoveEvent(mouse)) { return true; } } if (mouse.GetButton() == this->Actions.Pan()) { // Figure out how much the mouse has moved by in plot coordinates - pan vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData()); vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData()); vtkVector2d pos(0.0, 0.0); vtkVector2d last(0.0, 0.0); // Go from screen to scene coordinates to work out the delta vtkAxis* xAxis = this->ChartPrivate->axes[vtkAxis::BOTTOM]; vtkAxis* yAxis = this->ChartPrivate->axes[vtkAxis::LEFT]; vtkTransform2D* transform = this->ChartPrivate->PlotCorners[0]->GetTransform(); transform->InverseTransformPoints(screenPos.GetData(), pos.GetData(), 1); transform->InverseTransformPoints(lastScreenPos.GetData(), last.GetData(), 1); vtkVector2d delta = last - pos; delta[0] /= xAxis->GetScalingFactor(); delta[1] /= yAxis->GetScalingFactor(); // Now move the axes and recalculate the transform delta[0] = delta[0] > 0 ? std::min(delta[0], xAxis->GetMaximumLimit() - xAxis->GetMaximum()) : std::max(delta[0], xAxis->GetMinimumLimit() - xAxis->GetMinimum()); delta[1] = delta[1] > 0 ? std::min(delta[1], yAxis->GetMaximumLimit() - yAxis->GetMaximum()) : std::max(delta[1], yAxis->GetMinimumLimit() - yAxis->GetMinimum()); xAxis->SetMinimum(xAxis->GetMinimum() + delta[0]); xAxis->SetMaximum(xAxis->GetMaximum() + delta[0]); yAxis->SetMinimum(yAxis->GetMinimum() + delta[1]); yAxis->SetMaximum(yAxis->GetMaximum() + delta[1]); if (this->ChartPrivate->PlotCorners.size() == 2) { // Figure out the right axis position, if greater than 2 both will be done // in the else if block below. screenPos = vtkVector2d(mouse.GetScreenPos().Cast<double>().GetData()); lastScreenPos = vtkVector2d(mouse.GetLastScreenPos().Cast<double>().GetData()); pos = vtkVector2d(0.0, 0.0); last = vtkVector2d(0.0, 0.0); yAxis = this->ChartPrivate->axes[vtkAxis::RIGHT]; transform = this->ChartPrivate->PlotCorners[1]->GetTransform(); transform->InverseTransformPoints(screenPos.GetData(), pos.GetData(), 1); transform->InverseTransformPoints(lastScreenPos.GetData(), last.GetData(), 1); delta = last - pos; delta[0] /= xAxis->GetScalingFactor(); delta[1] /= yAxis->GetScalingFactor(); // Now move the axes and recalculate the transform delta[1] = delta[1] > 0 ? std::min(delta[1], yAxis->GetMaximumLimit() - yAxis->GetMaximum()) : std::max(delta[1], yAxis->GetMinimumLimit() - yAxis->GetMinimum()); yAxis->SetMinimum(yAxis->GetMinimum() + delta[1]); yAxis->SetMaximum(yAxis->GetMaximum() + delta[1]); } else if (this->ChartPrivate->PlotCorners.size() > 2) { // Figure out the right and top axis positions. // Go from screen to scene coordinates to work out the delta screenPos = vtkVector2d(mouse.GetScreenPos().Cast<double>().GetData()); lastScreenPos = vtkVector2d(mouse.GetLastScreenPos().Cast<double>().GetData()); pos = vtkVector2d(0.0, 0.0); last = vtkVector2d(0.0, 0.0); xAxis = this->ChartPrivate->axes[vtkAxis::TOP]; yAxis = this->ChartPrivate->axes[vtkAxis::RIGHT]; transform = this->ChartPrivate->PlotCorners[2]->GetTransform(); transform->InverseTransformPoints(screenPos.GetData(), pos.GetData(), 1); transform->InverseTransformPoints(lastScreenPos.GetData(), last.GetData(), 1); delta = last - pos; delta[0] /= xAxis->GetScalingFactor(); delta[1] /= yAxis->GetScalingFactor(); // Now move the axes and recalculate the transform delta[0] = delta[0] > 0 ? std::min(delta[0], xAxis->GetMaximumLimit() - xAxis->GetMaximum()) : std::max(delta[0], xAxis->GetMinimumLimit() - xAxis->GetMinimum()); delta[1] = delta[1] > 0 ? std::min(delta[1], yAxis->GetMaximumLimit() - yAxis->GetMaximum()) : std::max(delta[1], yAxis->GetMinimumLimit() - yAxis->GetMinimum()); xAxis->SetMinimum(xAxis->GetMinimum() + delta[0]); xAxis->SetMaximum(xAxis->GetMaximum() + delta[0]); yAxis->SetMinimum(yAxis->GetMinimum() + delta[1]); yAxis->SetMaximum(yAxis->GetMaximum() + delta[1]); } this->RecalculatePlotTransforms(); // Mark the scene as dirty this->Scene->SetDirty(true); this->InvokeEvent(vtkCommand::InteractionEvent); } else if (mouse.GetButton() == this->Actions.Zoom() || mouse.GetButton() == this->Actions.Select()) { this->MouseBox.SetWidth(mouse.GetPos().GetX() - this->MouseBox.GetX()); this->MouseBox.SetHeight(mouse.GetPos().GetY() - this->MouseBox.GetY()); // Mark the scene as dirty this->Scene->SetDirty(true); } else if (mouse.GetButton() == this->Actions.ZoomAxis()) { vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData()); vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData()); vtkAxis* axes[] = { this->ChartPrivate->axes[vtkAxis::BOTTOM], this->ChartPrivate->axes[vtkAxis::LEFT], this->ChartPrivate->axes[vtkAxis::TOP], this->ChartPrivate->axes[vtkAxis::RIGHT] }; for (int i = 0; i < 4; i++) { vtkAxis* axis = axes[i]; if (!axis) { continue; } // bottom, top -> 0, right, left -> 1 int side = i % 2; // get mouse delta in the given direction for the axis double delta = lastScreenPos[side] - screenPos[side]; if (std::abs(delta) == 0) { continue; } // scale and invert delta delta /= -100.0; // zoom axis range double min = axis->GetMinimum(); double max = axis->GetMaximum(); double frac = (max - min) * 0.1; if (frac > 0.0) { min += delta * frac; max -= delta * frac; } else { min -= delta * frac; max += delta * frac; } axis->SetMinimum(min); axis->SetMaximum(max); axis->RecalculateTickSpacing(); } this->RecalculatePlotTransforms(); // Mark the scene as dirty this->Scene->SetDirty(true); } else if (mouse.GetButton() == this->Actions.SelectPolygon()) { if (this->SelectionPolygon.GetNumberOfPoints() > 0) { vtkVector2f lastPoint = this->SelectionPolygon.GetPoint(this->SelectionPolygon.GetNumberOfPoints() - 1); if ((lastPoint - mouse.GetPos()).SquaredNorm() > 100) { this->SelectionPolygon.AddPoint(mouse.GetPos()); } // Mark the scene as dirty this->Scene->SetDirty(true); } } else if (mouse.GetButton() == vtkContextMouseEvent::NO_BUTTON) { this->Scene->SetDirty(true); if (this->Tooltip) { this->Tooltip->SetVisible(this->LocatePointInPlots(mouse)); } } return true; } //----------------------------------------------------------------------------- int vtkChartXY::LocatePointInPlot(const vtkVector2f& position, const vtkVector2f& tolerance, vtkVector2f& plotPos, vtkPlot* plot, vtkIdType& segmentIndex) { if (plot && plot->GetVisible()) { vtkPlotBar* plotBar = vtkPlotBar::SafeDownCast(plot); if (plotBar) { // If the plot is a vtkPlotBar, get the segment index too return plotBar->GetNearestPoint(position, tolerance, &plotPos, &segmentIndex); } else { return plot->GetNearestPoint(position, tolerance, &plotPos); } } return -1; } //----------------------------------------------------------------------------- bool vtkChartXY::LocatePointInPlots(const vtkContextMouseEvent& mouse, int invokeEvent) { size_t n = this->ChartPrivate->plots.size(); vtkVector2i pos(mouse.GetScreenPos()); if (pos[0] > this->Point1[0] && pos[0] < this->Point2[0] && pos[1] > this->Point1[1] && pos[1] < this->Point2[1] && n) { // Iterate through each corner, and check for a nearby point for (size_t i = 0; i < this->ChartPrivate->PlotCorners.size(); ++i) { int items = static_cast<int>(this->ChartPrivate->PlotCorners[i]->GetNumberOfItems()); if (items) { vtkVector2f plotPos, position; vtkTransform2D* transform = this->ChartPrivate->PlotCorners[i]->GetTransform(); transform->InverseTransformPoints(mouse.GetPos().GetData(), position.GetData(), 1); // Use a tolerance of +/- 5 pixels vtkVector2f tolerance(std::fabs(5 * (1.0 / transform->GetMatrix()->GetElement(0, 0))), std::fabs(5 * (1.0 / transform->GetMatrix()->GetElement(1, 1)))); // Iterate through the visible plots and return on the first hit vtkIdType segmentIndex = -1; for (int j = items - 1; j >= 0; --j) { vtkPlot* plot = vtkPlot::SafeDownCast(this->ChartPrivate->PlotCorners[i]->GetItem(j)); int seriesIndex = LocatePointInPlot(position, tolerance, plotPos, plot, segmentIndex); if (seriesIndex >= 0) { // We found a point, set up the tooltip and return vtkRectd ss(plot->GetShiftScale()); vtkVector2d plotPosd(plotPos[0] / ss[2] - ss[0], plotPos[1] / ss[3] - ss[1]); this->SetTooltipInfo(mouse, plotPosd, seriesIndex, plot, segmentIndex); if (invokeEvent >= 0) { vtkChartPlotData plotIndex; plotIndex.SeriesName = plot->GetLabel(); plotIndex.Position = plotPos; plotIndex.ScreenPosition = mouse.GetScreenPos(); plotIndex.Index = seriesIndex; // Invoke an event, with the client data supplied this->InvokeEvent(invokeEvent, static_cast<void*>(&plotIndex)); if (invokeEvent == vtkCommand::SelectionChangedEvent) { // Construct a new selection with the selected point in it. vtkNew<vtkIdTypeArray> selectionIds; selectionIds->InsertNextValue(seriesIndex); plot->SetSelection(selectionIds.GetPointer()); if (this->AnnotationLink) { vtkChartSelectionHelper::MakeSelection( this->AnnotationLink, selectionIds.GetPointer(), plot); } } } return true; } } } } } return false; } //----------------------------------------------------------------------------- void vtkChartXY::SetTooltipInfo(const vtkContextMouseEvent& mouse, const vtkVector2d& plotPos, vtkIdType seriesIndex, vtkPlot* plot, vtkIdType segmentIndex) { if (!this->Tooltip) { return; } // Have the plot generate its tooltip label vtkStdString tooltipLabel = plot->GetTooltipLabel(plotPos, seriesIndex, segmentIndex); // Set the tooltip this->Tooltip->SetText(tooltipLabel); this->Tooltip->SetPosition(mouse.GetScreenPos()[0] + 2, mouse.GetScreenPos()[1] + 2); } //----------------------------------------------------------------------------- bool vtkChartXY::MouseLeaveEvent(const vtkContextMouseEvent&) { this->DrawNearestPoint = false; if (this->Tooltip) { this->Tooltip->SetVisible(false); } return true; } //----------------------------------------------------------------------------- bool vtkChartXY::MouseButtonPressEvent(const vtkContextMouseEvent& mouse) { if (this->Tooltip) { this->Tooltip->SetVisible(false); } // Iterate through each corner, and check for a nearby point for (size_t i = 0; i < this->ChartPrivate->PlotCorners.size(); ++i) { if (this->ChartPrivate->PlotCorners[i]->MouseButtonPressEvent(mouse)) { return true; } } if (mouse.GetButton() == this->Actions.Pan()) { // The mouse panning action. this->MouseBox.Set(mouse.GetPos().GetX(), mouse.GetPos().GetY(), 0.0, 0.0); this->DrawBox = false; return true; } else if (mouse.GetButton() == this->Actions.Zoom() || mouse.GetButton() == this->Actions.Select()) { // Selection, for now at least... this->MouseBox.Set(mouse.GetPos().GetX(), mouse.GetPos().GetY(), 0.0, 0.0); this->DrawBox = true; return true; } else if (mouse.GetButton() == this->Actions.ZoomAxis()) { this->MouseBox.Set(mouse.GetPos().GetX(), mouse.GetPos().GetY(), 0.0, 0.0); this->DrawBox = false; return true; } else if (mouse.GetButton() == this->Actions.SelectPolygon()) { this->SelectionPolygon.Clear(); this->SelectionPolygon.AddPoint(mouse.GetPos()); this->DrawSelectionPolygon = true; return true; } else if (mouse.GetButton() == this->ActionsClick.Select() || mouse.GetButton() == this->ActionsClick.Notify()) { return true; } else { return false; } } //----------------------------------------------------------------------------- bool vtkChartXY::MouseButtonReleaseEvent(const vtkContextMouseEvent& mouse) { // Iterate through each corner, and check for a nearby point for (size_t i = 0; i < this->ChartPrivate->PlotCorners.size(); ++i) { if (this->ChartPrivate->PlotCorners[i]->MouseButtonReleaseEvent(mouse)) { return true; } } if (mouse.GetButton() > vtkContextMouseEvent::NO_BUTTON && mouse.GetButton() <= vtkContextMouseEvent::RIGHT_BUTTON) { this->MouseBox.SetWidth(mouse.GetPos().GetX() - this->MouseBox.GetX()); this->MouseBox.SetHeight(mouse.GetPos().GetY() - this->MouseBox.GetY()); if ((fabs(this->MouseBox.GetWidth()) < 0.5 && fabs(this->MouseBox.GetHeight()) < 0.5) && (mouse.GetButton() == this->Actions.Select() || mouse.GetButton() == this->Actions.Pan())) { // Invalid box size - treat as a single clicke event this->MouseBox.SetWidth(0.0); this->MouseBox.SetHeight(0.0); this->DrawBox = false; if (mouse.GetButton() == this->ActionsClick.Notify()) { this->LocatePointInPlots(mouse, vtkCommand::InteractionEvent); return true; } else if (mouse.GetButton() == this->ActionsClick.Select()) { this->LocatePointInPlots(mouse, vtkCommand::SelectionChangedEvent); return true; } else { return false; } } } if (mouse.GetButton() == this->Actions.Select() || mouse.GetButton() == this->Actions.SelectPolygon()) { // Modifiers or selection modes can affect how selection is performed. int selectionMode = vtkChartSelectionHelper::GetMouseSelectionMode(mouse, this->SelectionMode); bool polygonMode(mouse.GetButton() == this->Actions.SelectPolygon()); this->Scene->SetDirty(true); // Update the polygon or box with the last mouse position. if (polygonMode) { this->SelectionPolygon.AddPoint(mouse.GetPos()); this->DrawSelectionPolygon = false; } else { this->MouseBox.SetWidth(mouse.GetPos().GetX() - this->MouseBox.GetX()); this->MouseBox.SetHeight(mouse.GetPos().GetY() - this->MouseBox.GetY()); this->DrawBox = false; } // Check whether we have a valid selection area, exit early if not. if (polygonMode && this->SelectionPolygon.GetNumberOfPoints() < 3) { // There is no polygon to select points in. this->SelectionPolygon.Clear(); return true; } else if (fabs(this->MouseBox.GetWidth()) < 0.5 || fabs(this->MouseBox.GetHeight()) < 0.5) { // The box is too small, and no useful selection can be made. this->MouseBox.SetWidth(0.0); this->MouseBox.SetHeight(0.0); return true; } // Iterate through the plots and build a selection. Two main behaviors are // supported - row-based selections add all rows from all plots and set that // as the selection, plot-based selections create a selection node for each // plot. vtkNew<vtkIdTypeArray> oldSelection; vtkNew<vtkIdTypeArray> accumulateSelection; if (this->SelectionMethod == vtkChart::SELECTION_ROWS) { // There is only one global selection, we build up a union of all rows // selected in all charts and set that on all plots. for (size_t i = 0; i < this->ChartPrivate->PlotCorners.size(); ++i) { int items = static_cast<int>(this->ChartPrivate->PlotCorners[i]->GetNumberOfItems()); if (items) { vtkTransform2D* transform = this->ChartPrivate->PlotCorners[i]->GetTransform(); vtkVector2f min; vtkVector2f max; vtkContextPolygon polygon; this->TransformBoxOrPolygon(polygonMode, transform, mouse.GetPos(), min, max, polygon); // Iterate through the plots and create the selection. for (int j = 0; j < items; ++j) { vtkPlot* plot = vtkPlot::SafeDownCast(this->ChartPrivate->PlotCorners[i]->GetItem(j)); if (plot && plot->GetVisible() && plot->GetSelectable()) { // There is only really one old selection in this mode. if (i == 0 && j == 0) { oldSelection->DeepCopy(plot->GetSelection()); } // Populate the selection using the appropriate shape. if (polygonMode) { plot->SelectPointsInPolygon(polygon); } else { plot->SelectPoints(min, max); } // Accumulate the selection in each plot. vtkChartSelectionHelper::BuildSelection(0, vtkContextScene::SELECTION_ADDITION, accumulateSelection.GetPointer(), plot->GetSelection(), 0); } } } } // Now add the accumulated selection to the old selection. vtkChartSelectionHelper::BuildSelection(this->AnnotationLink, selectionMode, accumulateSelection.GetPointer(), oldSelection.GetPointer(), 0); } else if (this->SelectionMethod == vtkChart::SELECTION_PLOTS) { // We are performing plot based selections. for (size_t i = 0; i < this->ChartPrivate->PlotCorners.size(); ++i) { int items = static_cast<int>(this->ChartPrivate->PlotCorners[i]->GetNumberOfItems()); if (items) { vtkTransform2D* transform = this->ChartPrivate->PlotCorners[i]->GetTransform(); vtkVector2f min; vtkVector2f max; vtkContextPolygon polygon; this->TransformBoxOrPolygon(polygonMode, transform, mouse.GetPos(), min, max, polygon); for (int j = 0; j < items; ++j) { vtkPlot* plot = vtkPlot::SafeDownCast(this->ChartPrivate->PlotCorners[i]->GetItem(j)); if (plot && plot->GetVisible() && plot->GetSelectable()) { oldSelection->DeepCopy(plot->GetSelection()); // Populate the selection using the appropriate shape. if (polygonMode) { plot->SelectPointsInPolygon(polygon); } else { plot->SelectPoints(min, max); } // Combine the selection in this plot with any previous selection. vtkChartSelectionHelper::BuildSelection(this->AnnotationLink, selectionMode, plot->GetSelection(), oldSelection.GetPointer(), plot); } } } } } else if (this->SelectionMethod == vtkChart::SELECTION_COLUMNS) { if (this->AnnotationLink) { this->AnnotationLink->Update(); vtkSelection* selection = vtkSelection::SafeDownCast(this->AnnotationLink->GetOutputDataObject(2)); vtkSelectionNode* node = selection->GetNumberOfNodes() > 0 ? selection->GetNode(0) : NULL; if (node) { oldSelection->DeepCopy(vtkArrayDownCast<vtkIdTypeArray>(node->GetSelectionList())); } } vtkNew<vtkIdTypeArray> plotSelection; // We are performing plot based selections. for (size_t i = 0; i < this->ChartPrivate->PlotCorners.size(); ++i) { int items = static_cast<int>(this->ChartPrivate->PlotCorners[i]->GetNumberOfItems()); if (items) { vtkTransform2D* transform = this->ChartPrivate->PlotCorners[i]->GetTransform(); vtkVector2f min; vtkVector2f max; vtkContextPolygon polygon; this->TransformBoxOrPolygon(polygonMode, transform, mouse.GetPos(), min, max, polygon); for (int j = 0; j < items; ++j) { vtkPlot* plot = vtkPlot::SafeDownCast(this->ChartPrivate->PlotCorners[i]->GetItem(j)); if (plot && plot->GetVisible() && plot->GetSelectable()) { bool selected = false; // Populate the selection using the appropriate shape. if (polygonMode) { selected = plot->SelectPointsInPolygon(polygon); } else { selected = plot->SelectPoints(min, max); } vtkNew<vtkIdTypeArray> plotsSelection; if (selected) { int idx = 1; // y vtkAbstractArray* column = plot->GetData()->GetInputAbstractArrayToProcess(idx, plot->GetInput()); int columnID = -1; plot->GetInput()->GetRowData()->GetAbstractArray(column->GetName(), columnID); if (plotSelection->GetNumberOfTuples() != column->GetNumberOfTuples()) { plotSelection->SetNumberOfTuples(0); for (vtkIdType k = 0; k < column->GetNumberOfTuples(); ++k) { plotSelection->InsertNextValue(k); } } plot->SetSelection(plotSelection.GetPointer()); accumulateSelection->InsertNextValue(columnID); } } } } } vtkIdType* ptrSelection = reinterpret_cast<vtkIdType*>(accumulateSelection->GetVoidPointer(0)); std::sort(ptrSelection, ptrSelection + accumulateSelection->GetNumberOfTuples()); // Now add the accumulated selection to the old selection vtkChartSelectionHelper::BuildSelection(this->AnnotationLink, selectionMode, accumulateSelection.GetPointer(), oldSelection.GetPointer(), 0); } this->InvokeEvent(vtkCommand::SelectionChangedEvent); this->MouseBox.SetWidth(0.0); this->MouseBox.SetHeight(0.0); this->SelectionPolygon.Clear(); return true; } else if (mouse.GetButton() == this->Actions.Zoom()) { // Check whether a valid zoom box was drawn if (fabs(this->MouseBox.GetWidth()) < 0.5 || fabs(this->MouseBox.GetHeight()) < 0.5) { // Invalid box size - do nothing this->MouseBox.SetWidth(0.0); this->MouseBox.SetHeight(0.0); this->DrawBox = false; return true; } // Zoom into the chart by the specified amount, and recalculate the bounds vtkVector2f point2(mouse.GetPos()); this->ZoomInAxes(this->ChartPrivate->axes[vtkAxis::BOTTOM], this->ChartPrivate->axes[vtkAxis::LEFT], this->MouseBox.GetData(), point2.GetData()); this->ZoomInAxes(this->ChartPrivate->axes[vtkAxis::TOP], this->ChartPrivate->axes[vtkAxis::RIGHT], this->MouseBox.GetData(), point2.GetData()); this->RecalculatePlotTransforms(); this->MouseBox.SetWidth(0.0); this->MouseBox.SetHeight(0.0); this->DrawBox = false; // Mark the scene as dirty this->Scene->SetDirty(true); this->InvokeEvent(vtkCommand::InteractionEvent); return true; } else if (mouse.GetButton() == this->Actions.ZoomAxis()) { return true; } return false; } void vtkChartXY::ZoomInAxes(vtkAxis* x, vtkAxis* y, float* originf, float* maxf) { vtkNew<vtkTransform2D> transform; this->CalculateUnscaledPlotTransform(x, y, transform.GetPointer()); vtkVector2d origin(originf[0], originf[1]); vtkVector2d max(maxf[0], maxf[1]); vtkVector2d torigin; transform->InverseTransformPoints(origin.GetData(), torigin.GetData(), 1); vtkVector2d tmax; transform->InverseTransformPoints(max.GetData(), tmax.GetData(), 1); // Ensure we preserve the directionality of the axes if (x->GetMaximum() > x->GetMinimum()) { x->SetMaximum(torigin[0] > tmax[0] ? torigin[0] : tmax[0]); x->SetMinimum(torigin[0] < tmax[0] ? torigin[0] : tmax[0]); } else { x->SetMaximum(torigin[0] < tmax[0] ? torigin[0] : tmax[0]); x->SetMinimum(torigin[0] > tmax[0] ? torigin[0] : tmax[0]); } if (y->GetMaximum() > y->GetMinimum()) { y->SetMaximum(torigin[1] > tmax[1] ? torigin[1] : tmax[1]); y->SetMinimum(torigin[1] < tmax[1] ? torigin[1] : tmax[1]); } else { y->SetMaximum(torigin[1] < tmax[1] ? torigin[1] : tmax[1]); y->SetMinimum(torigin[1] > tmax[1] ? torigin[1] : tmax[1]); } x->RecalculateTickSpacing(); y->RecalculateTickSpacing(); } //----------------------------------------------------------------------------- bool vtkChartXY::MouseWheelEvent(const vtkContextMouseEvent&, int delta) { if (this->Tooltip) { this->Tooltip->SetVisible(false); } if (!this->ZoomWithMouseWheel) { return false; } // Get the bounds of each plot. for (int i = 0; i < 4; ++i) { vtkAxis* axis = this->ChartPrivate->axes[i]; double min = axis->GetMinimum(); double max = axis->GetMaximum(); double frac = (max - min) * 0.1; if (frac > 0.0) { min += delta * frac; max -= delta * frac; } else { min -= delta * frac; max += delta * frac; } axis->SetMinimum(min); axis->SetMaximum(max); axis->RecalculateTickSpacing(); } this->RecalculatePlotTransforms(); // Mark the scene as dirty this->Scene->SetDirty(true); this->InvokeEvent(vtkCommand::InteractionEvent); return true; } //----------------------------------------------------------------------------- bool vtkChartXY::KeyPressEvent(const vtkContextKeyEvent& key) { switch (key.GetKeyCode()) { // Reset the chart axes case 'r': case 'R': this->RecalculateBounds(); this->Scene->SetDirty(true); } return true; } //----------------------------------------------------------------------------- bool vtkChartXY::RemovePlotFromCorners(vtkPlot* plot) { // We know the plot will only ever be in one of the corners for (size_t i = 0; i < this->ChartPrivate->PlotCorners.size(); ++i) { if (this->ChartPrivate->PlotCorners[i]->RemoveItem(plot)) { return true; } } return false; } //----------------------------------------------------------------------------- inline void vtkChartXY::TransformBoxOrPolygon(bool polygonMode, vtkTransform2D* transform, const vtkVector2f& mousePosition, vtkVector2f& min, vtkVector2f& max, vtkContextPolygon& polygon) { if (polygonMode) { vtkNew<vtkTransform2D> inverseTransform; inverseTransform->SetMatrix(transform->GetMatrix()); inverseTransform->Inverse(); polygon = this->SelectionPolygon.Transformed(inverseTransform.GetPointer()); } else { transform->InverseTransformPoints(this->MouseBox.GetData(), min.GetData(), 1); transform->InverseTransformPoints(mousePosition.GetData(), max.GetData(), 1); // Normalize the rectangle selection area before using it. if (min.GetX() > max.GetX()) { float tmp = min.GetX(); min.SetX(max.GetX()); max.SetX(tmp); } if (min.GetY() > max.GetY()) { float tmp = min.GetY(); min.SetY(max.GetY()); max.SetY(tmp); } } } //----------------------------------------------------------------------------- void vtkChartXY::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Axes: " << endl; for (int i = 0; i < 4; ++i) { this->ChartPrivate->axes[i]->PrintSelf(os, indent.GetNextIndent()); } if (this->ChartPrivate) { os << indent << "Number of plots: " << this->ChartPrivate->plots.size() << endl; for (unsigned int i = 0; i < this->ChartPrivate->plots.size(); ++i) { os << indent << "Plot " << i << ":" << endl; this->ChartPrivate->plots[i]->PrintSelf(os, indent.GetNextIndent()); } } os << indent << "ZoomWithMouseWheel: " << this->ZoomWithMouseWheel << endl; }
32.282132
100
0.582485
[ "geometry", "render", "object", "shape", "vector", "transform" ]
a35257136a219bd6bad00b1536dc6a100b1afc9b
5,427
cpp
C++
ArrtModel/Model/ArrServiceStats.cpp
AleksandarTomicMs2/azure-remote-rendering-asset-tool
c3962231e02af6ff90c2867f51e7a3b20af8c592
[ "MIT" ]
null
null
null
ArrtModel/Model/ArrServiceStats.cpp
AleksandarTomicMs2/azure-remote-rendering-asset-tool
c3962231e02af6ff90c2867f51e7a3b20af8c592
[ "MIT" ]
1
2021-02-24T10:21:39.000Z
2021-02-24T15:21:28.000Z
ArrtModel/Model/ArrServiceStats.cpp
AleksandarTomicMs2/azure-remote-rendering-asset-tool
c3962231e02af6ff90c2867f51e7a3b20af8c592
[ "MIT" ]
null
null
null
#include <Model/ArrServiceStats.h> #include <Model/Log/LogHelpers.h> ArrServiceStats::ArrServiceStats(QObject* parent) : QObject(parent) { m_currWindowsElapsedTimer.start(); } void ArrServiceStats::update(RR::ApiHandle<RR::AzureSession> session) { updateStats(session); } void ArrServiceStats::updateStats(RR::ApiHandle<RR::AzureSession> session) { if (!m_collecting || !session || !session->GetIsConnected()) { return; } ++m_tick; RR::FrameStatistics frameStatistics; if (session->GetGraphicsBinding()->GetLastFrameStatistics(&frameStatistics) != RR::Result::Success) { return; } m_currentStats.m_timeSinceLastPresent.addValue(frameStatistics.timeSinceLastPresent * 1000.0, m_tick); m_currentStats.m_videoFramesSkipped.addValue(frameStatistics.videoFramesSkipped, m_tick); m_currentStats.m_videoFramesReused.addValue(frameStatistics.videoFrameReusedCount, m_tick); m_currentStats.m_videoFramesReceived.addValue(frameStatistics.videoFramesReceived, m_tick); if (frameStatistics.videoFramesReceived) { m_currentStats.m_videoFrameMinDelta.addValue(frameStatistics.videoFrameMinDelta * 1000.0, m_tick); m_currentStats.m_videoFrameMaxDelta.addValue(frameStatistics.videoFrameMaxDelta * 1000.0, m_tick); } m_currentStats.m_latencyPoseToReceive.addValue(frameStatistics.latencyPoseToReceive * 1000.0, m_tick); m_currentStats.m_latencyReceiveToPresent.addValue(frameStatistics.latencyReceiveToPresent * 1000.0, m_tick); m_currentStats.m_latencyPresentToDisplay.addValue(frameStatistics.latencyPresentToDisplay * 1000.0, m_tick); m_currentStats.m_videoFramesDiscarded.addValue(frameStatistics.videoFramesDiscarded, m_tick); if (m_runningPerformanceAssesment && m_runningPerformanceAssesment->GetIsCompleted()) { if (m_runningPerformanceAssesment->GetIsFaulted()) { qWarning(LoggingCategory::renderingSession) << tr("Error retrieving the performance assessment. Failure reason: ") << m_runningPerformanceAssesment->GetStatus(); m_runningPerformanceAssesment = {}; } else if (m_runningPerformanceAssesment->GetStatus() == RR::Result::Success) { m_lastPerformanceAssessment = m_runningPerformanceAssesment->GetResult(); m_currentStats.m_timeCPU.addValue(m_lastPerformanceAssessment.timeCPU.aggregate, m_tick); m_currentStats.m_timeGPU.addValue(m_lastPerformanceAssessment.timeGPU.aggregate, m_tick); m_currentStats.m_utilizationCPU.addValue(m_lastPerformanceAssessment.utilizationCPU.aggregate, m_tick); m_currentStats.m_utilizationGPU.addValue(m_lastPerformanceAssessment.utilizationGPU.aggregate, m_tick); m_currentStats.m_memoryCPU.addValue(m_lastPerformanceAssessment.memoryCPU.aggregate, m_tick); m_currentStats.m_memoryGPU.addValue(m_lastPerformanceAssessment.memoryGPU.aggregate, m_tick); m_currentStats.m_networkLatency.addValue(m_lastPerformanceAssessment.networkLatency.aggregate, m_tick); m_currentStats.m_polygonsRendered.addValue(m_lastPerformanceAssessment.networkLatency.aggregate, m_tick); m_runningPerformanceAssesment = {}; } else { qWarning(LoggingCategory::renderingSession) << tr("what?"); } } // If 1 second has past, clear the last stats list. //var now = QDateTime::currentDateTime(); if (m_currWindowsElapsedTimer.elapsed() >= 1000) { m_secondsTick++; m_currWindowsElapsedTimer.start(); m_currentStats.m_timeSinceLastPresent.endWindow(m_secondsTick); m_currentStats.m_videoFramesSkipped.endWindow(m_secondsTick); m_currentStats.m_videoFramesReused.endWindow(m_secondsTick); m_currentStats.m_videoFramesReceived.endWindow(m_secondsTick); m_currentStats.m_videoFrameMinDelta.endWindow(m_secondsTick); m_currentStats.m_videoFrameMaxDelta.endWindow(m_secondsTick); m_currentStats.m_latencyPoseToReceive.endWindow(m_secondsTick); m_currentStats.m_latencyReceiveToPresent.endWindow(m_secondsTick); m_currentStats.m_latencyPresentToDisplay.endWindow(m_secondsTick); m_currentStats.m_videoFramesDiscarded.endWindow(m_secondsTick); m_currentStats.m_timeCPU.endWindow(m_secondsTick); m_currentStats.m_timeGPU.endWindow(m_secondsTick); m_currentStats.m_utilizationCPU.endWindow(m_secondsTick); m_currentStats.m_utilizationGPU.endWindow(m_secondsTick); m_currentStats.m_memoryCPU.endWindow(m_secondsTick); m_currentStats.m_memoryGPU.endWindow(m_secondsTick); m_currentStats.m_networkLatency.endWindow(m_secondsTick); m_currentStats.m_polygonsRendered.endWindow(m_secondsTick); // query the performance assessment (assuming the previous query is completed) if (!m_runningPerformanceAssesment) { if (auto query = session->Actions()->QueryServerPerformanceAssessmentAsync()) { m_runningPerformanceAssesment = *query; } } Q_EMIT updated(); } } void ArrServiceStats::startCollecting() { m_tick = 0; m_secondsTick = 0; m_collecting = true; m_currentStats = {}; m_currWindowsElapsedTimer.start(); } void ArrServiceStats::stopCollecting() { m_collecting = false; }
44.85124
173
0.742952
[ "model" ]
a3574793c69ed07683a603e629f40911f75bca3a
3,887
cpp
C++
AppleOpenSource/WebKit2-7609.3.5.1.3/UIProcess/API/glib/WebKitPolicyDecision.cpp
lzackx/Zone
bf8a3d2b965c383a691a6e7b61d23db15ce11dba
[ "MIT" ]
null
null
null
AppleOpenSource/WebKit2-7609.3.5.1.3/UIProcess/API/glib/WebKitPolicyDecision.cpp
lzackx/Zone
bf8a3d2b965c383a691a6e7b61d23db15ce11dba
[ "MIT" ]
null
null
null
AppleOpenSource/WebKit2-7609.3.5.1.3/UIProcess/API/glib/WebKitPolicyDecision.cpp
lzackx/Zone
bf8a3d2b965c383a691a6e7b61d23db15ce11dba
[ "MIT" ]
null
null
null
/* * Copyright (C) 2012 Igalia S.L. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "WebKitPolicyDecision.h" #include "WebFramePolicyListenerProxy.h" #include "WebKitPolicyDecisionPrivate.h" #include "WebsitePoliciesData.h" #include <wtf/glib/WTFGType.h> using namespace WebKit; /** * SECTION: WebKitPolicyDecision * @Short_description: A pending policy decision * @Title: WebKitPolicyDecision * @See_also: #WebKitWebView * * Often WebKit allows the client to decide the policy for certain * operations. For instance, a client may want to open a link in a new * tab, block a navigation entirely, query the user or trigger a download * instead of a navigation. In these cases WebKit will fire the * #WebKitWebView::decide-policy signal with a #WebKitPolicyDecision * object. If the signal handler does nothing, WebKit will act as if * webkit_policy_decision_use() was called as soon as signal handling * completes. To make a policy decision asynchronously, simply increment * the reference count of the #WebKitPolicyDecision object. */ struct _WebKitPolicyDecisionPrivate { RefPtr<WebFramePolicyListenerProxy> listener; }; WEBKIT_DEFINE_ABSTRACT_TYPE(WebKitPolicyDecision, webkit_policy_decision, G_TYPE_OBJECT) static void webkitPolicyDecisionDispose(GObject* object) { webkit_policy_decision_use(WEBKIT_POLICY_DECISION(object)); G_OBJECT_CLASS(webkit_policy_decision_parent_class)->dispose(object); } void webkitPolicyDecisionSetListener(WebKitPolicyDecision* decision, Ref<WebFramePolicyListenerProxy>&& listener) { decision->priv->listener = WTFMove(listener); } static void webkit_policy_decision_class_init(WebKitPolicyDecisionClass* decisionClass) { GObjectClass* objectClass = G_OBJECT_CLASS(decisionClass); objectClass->dispose = webkitPolicyDecisionDispose; } /** * webkit_policy_decision_use: * @decision: a #WebKitPolicyDecision * * Accept the action which triggered this decision. */ void webkit_policy_decision_use(WebKitPolicyDecision* decision) { g_return_if_fail(WEBKIT_IS_POLICY_DECISION(decision)); if (!decision->priv->listener) return; auto listener = std::exchange(decision->priv->listener, nullptr); listener->use(); } /** * webkit_policy_decision_ignore: * @decision: a #WebKitPolicyDecision * * Ignore the action which triggered this decision. For instance, for a * #WebKitResponsePolicyDecision, this would cancel the request. */ void webkit_policy_decision_ignore(WebKitPolicyDecision* decision) { g_return_if_fail(WEBKIT_IS_POLICY_DECISION(decision)); if (!decision->priv->listener) return; auto listener = std::exchange(decision->priv->listener, nullptr); listener->ignore(); } /** * webkit_policy_decision_download: * @decision: a #WebKitPolicyDecision * * Spawn a download from this decision. */ void webkit_policy_decision_download(WebKitPolicyDecision* decision) { g_return_if_fail(WEBKIT_IS_POLICY_DECISION(decision)); if (!decision->priv->listener) return; auto listener = std::exchange(decision->priv->listener, nullptr); listener->download(); }
32.123967
113
0.765372
[ "object" ]
a35991396adbfa0747114176a4daa4895ba3461a
7,962
cc
C++
test/cpp/end2end/client_callback_end2end_test.cc
john-src/grpc
dc1bbf9932b8de85e96c92db9c7f43219498b58c
[ "Apache-2.0" ]
59
2019-06-28T03:07:42.000Z
2022-03-11T23:09:34.000Z
test/cpp/end2end/client_callback_end2end_test.cc
john-src/grpc
dc1bbf9932b8de85e96c92db9c7f43219498b58c
[ "Apache-2.0" ]
5
2019-07-31T01:49:08.000Z
2021-05-08T02:44:21.000Z
test/cpp/end2end/client_callback_end2end_test.cc
dinara92/grpc
53d82af98c2ac243c45ac28c57062273d03cd9dd
[ "Apache-2.0" ]
29
2019-06-12T03:22:18.000Z
2022-03-03T16:47:28.000Z
/* * * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <functional> #include <mutex> #include <thread> #include <grpcpp/channel.h> #include <grpcpp/client_context.h> #include <grpcpp/create_channel.h> #include <grpcpp/generic/generic_stub.h> #include <grpcpp/impl/codegen/proto_utils.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include <grpcpp/server_context.h> #include <grpcpp/support/client_callback.h> #include "src/proto/grpc/testing/echo.grpc.pb.h" #include "test/core/util/test_config.h" #include "test/cpp/end2end/test_service_impl.h" #include "test/cpp/util/byte_buffer_proto_helper.h" #include "test/cpp/util/string_ref_helper.h" #include <gtest/gtest.h> namespace grpc { namespace testing { namespace { class TestScenario { public: TestScenario(bool serve_callback) : callback_server(serve_callback) {} void Log() const; bool callback_server; }; static std::ostream& operator<<(std::ostream& out, const TestScenario& scenario) { return out << "TestScenario{callback_server=" << (scenario.callback_server ? "true" : "false") << "}"; } void TestScenario::Log() const { std::ostringstream out; out << *this; gpr_log(GPR_DEBUG, "%s", out.str().c_str()); } class ClientCallbackEnd2endTest : public ::testing::TestWithParam<TestScenario> { protected: ClientCallbackEnd2endTest() { GetParam().Log(); } void SetUp() override { ServerBuilder builder; if (!GetParam().callback_server) { builder.RegisterService(&service_); } else { builder.RegisterService(&callback_service_); } server_ = builder.BuildAndStart(); is_server_started_ = true; } void ResetStub() { ChannelArguments args; channel_ = server_->InProcessChannel(args); stub_ = grpc::testing::EchoTestService::NewStub(channel_); generic_stub_.reset(new GenericStub(channel_)); } void TearDown() override { if (is_server_started_) { server_->Shutdown(); } } void SendRpcs(int num_rpcs, bool with_binary_metadata) { grpc::string test_string(""); for (int i = 0; i < num_rpcs; i++) { EchoRequest request; EchoResponse response; ClientContext cli_ctx; test_string += "Hello world. "; request.set_message(test_string); grpc::string val; if (with_binary_metadata) { request.mutable_param()->set_echo_metadata(true); char bytes[8] = {'\0', '\1', '\2', '\3', '\4', '\5', '\6', static_cast<char>(i)}; val = grpc::string(bytes, 8); cli_ctx.AddMetadata("custom-bin", val); } cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP); std::mutex mu; std::condition_variable cv; bool done = false; stub_->experimental_async()->Echo( &cli_ctx, &request, &response, [&cli_ctx, &request, &response, &done, &mu, &cv, val, with_binary_metadata](Status s) { GPR_ASSERT(s.ok()); EXPECT_EQ(request.message(), response.message()); if (with_binary_metadata) { EXPECT_EQ( 1u, cli_ctx.GetServerTrailingMetadata().count("custom-bin")); EXPECT_EQ(val, ToString(cli_ctx.GetServerTrailingMetadata() .find("custom-bin") ->second)); } std::lock_guard<std::mutex> l(mu); done = true; cv.notify_one(); }); std::unique_lock<std::mutex> l(mu); while (!done) { cv.wait(l); } } } void SendRpcsGeneric(int num_rpcs, bool maybe_except) { const grpc::string kMethodName("/grpc.testing.EchoTestService/Echo"); grpc::string test_string(""); for (int i = 0; i < num_rpcs; i++) { EchoRequest request; std::unique_ptr<ByteBuffer> send_buf; ByteBuffer recv_buf; ClientContext cli_ctx; test_string += "Hello world. "; request.set_message(test_string); send_buf = SerializeToByteBuffer(&request); std::mutex mu; std::condition_variable cv; bool done = false; generic_stub_->experimental().UnaryCall( &cli_ctx, kMethodName, send_buf.get(), &recv_buf, [&request, &recv_buf, &done, &mu, &cv, maybe_except](Status s) { GPR_ASSERT(s.ok()); EchoResponse response; EXPECT_TRUE(ParseFromByteBuffer(&recv_buf, &response)); EXPECT_EQ(request.message(), response.message()); std::lock_guard<std::mutex> l(mu); done = true; cv.notify_one(); #if GRPC_ALLOW_EXCEPTIONS if (maybe_except) { throw - 1; } #else GPR_ASSERT(!maybe_except); #endif }); std::unique_lock<std::mutex> l(mu); while (!done) { cv.wait(l); } } } bool is_server_started_; std::shared_ptr<Channel> channel_; std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_; std::unique_ptr<grpc::GenericStub> generic_stub_; TestServiceImpl service_; CallbackTestServiceImpl callback_service_; std::unique_ptr<Server> server_; }; TEST_P(ClientCallbackEnd2endTest, SimpleRpc) { ResetStub(); SendRpcs(1, false); } TEST_P(ClientCallbackEnd2endTest, SequentialRpcs) { ResetStub(); SendRpcs(10, false); } TEST_P(ClientCallbackEnd2endTest, SequentialRpcsWithVariedBinaryMetadataValue) { ResetStub(); SendRpcs(10, true); } TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcs) { ResetStub(); SendRpcsGeneric(10, false); } #if GRPC_ALLOW_EXCEPTIONS TEST_P(ClientCallbackEnd2endTest, ExceptingRpc) { ResetStub(); SendRpcsGeneric(10, true); } #endif TEST_P(ClientCallbackEnd2endTest, MultipleRpcsWithVariedBinaryMetadataValue) { ResetStub(); std::vector<std::thread> threads; threads.reserve(10); for (int i = 0; i < 10; ++i) { threads.emplace_back([this] { SendRpcs(10, true); }); } for (int i = 0; i < 10; ++i) { threads[i].join(); } } TEST_P(ClientCallbackEnd2endTest, MultipleRpcs) { ResetStub(); std::vector<std::thread> threads; threads.reserve(10); for (int i = 0; i < 10; ++i) { threads.emplace_back([this] { SendRpcs(10, false); }); } for (int i = 0; i < 10; ++i) { threads[i].join(); } } TEST_P(ClientCallbackEnd2endTest, CancelRpcBeforeStart) { ResetStub(); EchoRequest request; EchoResponse response; ClientContext context; request.set_message("hello"); context.TryCancel(); std::mutex mu; std::condition_variable cv; bool done = false; stub_->experimental_async()->Echo( &context, &request, &response, [&response, &done, &mu, &cv](Status s) { EXPECT_EQ("", response.message()); EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code()); std::lock_guard<std::mutex> l(mu); done = true; cv.notify_one(); }); std::unique_lock<std::mutex> l(mu); while (!done) { cv.wait(l); } } TestScenario scenarios[] = {TestScenario{false}, TestScenario{true}}; INSTANTIATE_TEST_CASE_P(ClientCallbackEnd2endTest, ClientCallbackEnd2endTest, ::testing::ValuesIn(scenarios)); } // namespace } // namespace testing } // namespace grpc int main(int argc, char** argv) { grpc_test_init(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
28.035211
80
0.64205
[ "vector" ]
a35e114b7376e506b7eda37b25572abe57c9d43f
84,347
cpp
C++
src/OpenColorIO/fileformats/FileFormatCSP.cpp
philip-luk-tangent-anim/OpenColorIO
86800657eb0147cf7af579d4a8c579167c8c00af
[ "BSD-3-Clause" ]
null
null
null
src/OpenColorIO/fileformats/FileFormatCSP.cpp
philip-luk-tangent-anim/OpenColorIO
86800657eb0147cf7af579d4a8c579167c8c00af
[ "BSD-3-Clause" ]
null
null
null
src/OpenColorIO/fileformats/FileFormatCSP.cpp
philip-luk-tangent-anim/OpenColorIO
86800657eb0147cf7af579d4a8c579167c8c00af
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <iterator> #include <sstream> #include <algorithm> #include <OpenColorIO/OpenColorIO.h> #include "MathUtils.h" #include "ops/Lut1D/Lut1DOp.h" #include "ops/Lut3D/Lut3DOp.h" #include "ops/Matrix/MatrixOps.h" #include "ParseUtils.h" #include "pystring/pystring.h" #include "transforms/FileTransform.h" #include "Platform.h" OCIO_NAMESPACE_ENTER { namespace { const int NUM_PRELUT_SAMPLES = 65536; // 2**16 samples // Always use linear interpolation for preluts to get the // best precision const Interpolation PRELUT_INTERPOLATION = INTERP_LINEAR; typedef struct rsr_Interpolator1D_Raw_ { float * stims; float * values; unsigned int length; } rsr_Interpolator1D_Raw; rsr_Interpolator1D_Raw * rsr_Interpolator1D_Raw_create( unsigned int prelutLength ); void rsr_Interpolator1D_Raw_destroy( rsr_Interpolator1D_Raw * prelut ); /* An opaque handle to the cineSpace 1D Interpolator object */ typedef struct rsr_Interpolator1D_ rsr_Interpolator1D; rsr_Interpolator1D * rsr_Interpolator1D_createFromRaw( rsr_Interpolator1D_Raw * data ); void rsr_Interpolator1D_destroy( rsr_Interpolator1D * rawdata ); float rsr_Interpolator1D_interpolate( float x, rsr_Interpolator1D * data ); /* * =========== INTERNAL HELPER FUNCTIONS ============ */ struct rsr_Interpolator1D_ { int nSamplePoints; float * stims; /* 5 * (nSamplePoints-1) long, holding a sequence of * 1.0/delta, a, b, c, d * such that the curve in interval i is given by * z = (stims[i] - x)* (1.0/delta) * y = a + b*z + c*z^2 + d*z^3 */ float * parameters; float minValue; /* = f( stims[0] ) */ float maxValue; /* = f(stims[nSamplePoints-1] ) */ }; static int rsr_internal_I1D_refineSegment( float x, float * data, int low, int high ) { int midPoint; // TODO: Change assert to an exception? assert( x>= data[low] ); assert( x<= data[high] ); assert( (high-low) > 0); if( high-low==1 ) return low; midPoint = (low+high)/2; if( x<data[midPoint] ) return rsr_internal_I1D_refineSegment(x, data, low, midPoint ); return rsr_internal_I1D_refineSegment(x, data, midPoint, high ); } static int rsr_internal_I1D_findSegmentContaining( float x, float * data, int n ) { return rsr_internal_I1D_refineSegment(x, data, 0, n-1); } /* * =========== USER FUNCTIONS ============ */ void rsr_Interpolator1D_destroy( rsr_Interpolator1D * data ) { if(data==NULL) return; free(data->stims); free(data->parameters); free(data); } float rsr_Interpolator1D_interpolate( float x, rsr_Interpolator1D * data ) { int segId; float * segdata; float invDelta; float a,b,c,d,z; assert(data!=NULL); /* Is x in range? */ if( IsNan(x) ) return x; if( x<data->stims[0] ) return data->minValue; if (x>data->stims[ data->nSamplePoints -1] ) return data->maxValue; /* Ok so its between the begining and end .. lets find out where... */ segId = rsr_internal_I1D_findSegmentContaining( x, data->stims, data->nSamplePoints ); assert(data->parameters !=NULL ); segdata = data->parameters + 5 * segId; invDelta = segdata[0]; a = segdata[1]; b = segdata[2]; c = segdata[3]; d = segdata[4]; z = ( x - data->stims[segId] ) * invDelta; return a + z * ( b + z * ( c + d * z ) ) ; } rsr_Interpolator1D * rsr_Interpolator1D_createFromRaw( rsr_Interpolator1D_Raw * data ) { rsr_Interpolator1D * retval = NULL; /* Check the sanity of the data */ assert(data!=NULL); assert(data->length>=2); assert(data->stims!=NULL); assert(data->values!=NULL); /* Create the real data. */ retval = (rsr_Interpolator1D*)malloc( sizeof(rsr_Interpolator1D) ); // OCIO change: explicit cast if(retval==NULL) { return NULL; } retval->stims = (float*)malloc( sizeof(float) * data->length ); // OCIO change: explicit cast if(retval->stims==NULL) { free(retval); return NULL; } memcpy( retval->stims, data->stims, sizeof(float) * data->length ); retval->parameters = (float*)malloc( 5*sizeof(float) * ( data->length - 1 ) ); // OCIO change: explicit cast if(retval->parameters==NULL) { free(retval->stims); free(retval); return NULL; } retval->nSamplePoints = data->length; retval->minValue = data->values[0]; retval->maxValue = data->values[ data->length -1]; /* Now the fun part .. filling in the coeficients. */ if(data->length==2) { retval->parameters[0] = 1.0f/(data->stims[1]-data->stims[0]); retval->parameters[1] = data->values[0]; retval->parameters[2] = ( data->values[1] - data->values[0] ); retval->parameters[3] = 0; retval->parameters[4] = 0; } else { unsigned int i; float * params = retval->parameters; for(i=0; i< data->length-1; ++i) { float f0 = data->values[i+0]; float f1 = data->values[i+1]; params[0] = 1.0f/(retval->stims[i+1]-retval->stims[i+0]); if(i==0) { float delta = data->stims[i+1] - data->stims[i]; float delta2 = (data->stims[i+2] - data->stims[i+1])/delta; float f2 = data->values[i+2]; float dfdx1 = (f2-f0)/(1+delta2); params[1] = 1.0f * f0 + 0.0f * f1 + 0.0f * dfdx1; params[2] = -2.0f * f0 + 2.0f * f1 - 1.0f * dfdx1; params[3] = 1.0f * f0 - 1.0f * f1 + 1.0f * dfdx1; params[4] = 0.0; } else if (i==data->length-2) { float delta = data->stims[i+1] - data->stims[i]; float delta1 = (data->stims[i]-data->stims[i-1])/delta; float fn1 = data->values[i-1]; float dfdx0 = (f1-fn1)/(1+delta1); params[1] = 1.0f * f0 + 0.0f * f1 + 0.0f * dfdx0; params[2] = 0.0f * f0 + 0.0f * f1 + 1.0f * dfdx0; params[3] = -1.0f * f0 + 1.0f * f1 - 1.0f * dfdx0; params[4] = 0.0; } else { float delta = data->stims[i+1] - data->stims[i]; float fn1=data->values[i-1]; float delta1 = (data->stims[i] - data->stims[i-1])/delta; float f2=data->values[i+2]; float delta2 = (data->stims[i+2] - data->stims[i+1])/delta; float dfdx0 = (f1-fn1)/(1.0f+delta1); float dfdx1 = (f2-f0)/(1.0f+delta2); params[1] = 1.0f * f0 + 0.0f * dfdx0 + 0.0f * f1 + 0.0f * dfdx1; params[2] = 0.0f * f0 + 1.0f * dfdx0 + 0.0f * f1 + 0.0f * dfdx1; params[3] =-3.0f * f0 - 2.0f * dfdx0 + 3.0f * f1 - 1.0f * dfdx1; params[4] = 2.0f * f0 + 1.0f * dfdx0 - 2.0f * f1 + 1.0f * dfdx1; } params+=5; } } return retval; } rsr_Interpolator1D_Raw * rsr_Interpolator1D_Raw_create( unsigned int prelutLength) { unsigned int i; rsr_Interpolator1D_Raw * prelut = (rsr_Interpolator1D_Raw*)malloc( sizeof(rsr_Interpolator1D_Raw) ); // OCIO change: explicit cast if(prelut==NULL) return NULL; prelut->stims = (float*)malloc( sizeof(float) * prelutLength ); // OCIO change: explicit cast if(prelut->stims==NULL) { free(prelut); return NULL; } prelut->values = (float*)malloc( sizeof(float) * prelutLength ); // OCIO change: explicit cast if(prelut->values == NULL) { free(prelut->stims); free(prelut); return NULL; } prelut->length = prelutLength; for( i=0; i<prelutLength; ++i ) { prelut->stims[i] = 0.0; prelut->values[i] = 0.0; } return prelut; } void rsr_Interpolator1D_Raw_destroy( rsr_Interpolator1D_Raw * prelut ) { if(prelut==NULL) return; free( prelut->stims ); free( prelut->values ); free( prelut ); } } // End unnamed namespace for Interpolators.c namespace { class CachedFileCSP : public CachedFile { public: CachedFileCSP () : metadata("none") { } ~CachedFileCSP() = default; std::string metadata; double prelut_from_min[3] = { 0.0, 0.0, 0.0 }; double prelut_from_max[3] = { 1.0, 1.0, 1.0 }; Lut1DOpDataRcPtr prelut; Lut1DOpDataRcPtr lut1D; Lut3DOpDataRcPtr lut3D; }; typedef OCIO_SHARED_PTR<CachedFileCSP> CachedFileCSPRcPtr; inline bool startswithU(const std::string & str, const std::string & prefix) { return pystring::startswith(pystring::upper(pystring::strip(str)), prefix); } class LocalFileFormat : public FileFormat { public: LocalFileFormat() = default; ~LocalFileFormat() = default; void getFormatInfo(FormatInfoVec & formatInfoVec) const override; CachedFileRcPtr read( std::istream & istream, const std::string & fileName) const override; void bake(const Baker & baker, const std::string & formatName, std::ostream & ostream) const override; void buildFileOps(OpRcPtrVec & ops, const Config & config, const ConstContextRcPtr & context, CachedFileRcPtr untypedCachedFile, const FileTransform & fileTransform, TransformDirection dir) const override; }; // Note: Remove this when we don't need to debug. /* template<class T> std::ostream& operator<< (std::ostream& os, const std::vector<T>& v) { copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " ")); return os; } */ void LocalFileFormat::getFormatInfo(FormatInfoVec & formatInfoVec) const { FormatInfo info; info.name = "cinespace"; info.extension = "csp"; info.capabilities = (FORMAT_CAPABILITY_READ | FORMAT_CAPABILITY_BAKE); formatInfoVec.push_back(info); } CachedFileRcPtr LocalFileFormat::read( std::istream & istream, const std::string & fileName) const { Lut1DOpDataRcPtr lut1d_ptr; Lut3DOpDataRcPtr lut3d_ptr; // Try and read the LUT header. std::string line; bool notEmpty = nextline (istream, line); if (!notEmpty) { std::ostringstream os; os << "File " << fileName; os << ": file stream empty when trying to read csp LUT."; throw Exception(os.str().c_str()); } if (!startswithU(line, "CSPLUTV100")) { std::ostringstream os; os << "File " << fileName << " doesn't seem to be a csp LUT, "; os << "expected 'CSPLUTV100'. First line: '" << line << "'."; throw Exception(os.str().c_str()); } // Next line tells us if we are reading a 1D or 3D LUT. nextline (istream, line); if (!startswithU(line, "1D") && !startswithU(line, "3D")) { std::ostringstream os; os << "Unsupported CSP LUT type. Require 1D or 3D. "; os << "Found, '" << line << "' in " << fileName << "."; throw Exception(os.str().c_str()); } std::string csptype = line; // Read meta data block. std::string metadata; bool lineUpdateNeeded = false; nextline (istream, line); if(startswithU(line, "BEGIN METADATA")) { while (!startswithU(line, "END METADATA") || !istream) { nextline (istream, line); if (!startswithU(line, "END METADATA")) metadata += line + "\n"; } lineUpdateNeeded = true; } // Else line update not needed. // Make 3 vectors of prelut inputs + output values. std::vector<float> prelut_in[3]; std::vector<float> prelut_out[3]; bool useprelut[3] = { false, false, false }; // Parse the prelut block. for (int c = 0; c < 3; ++c) { // How many points do we have for this channel. if (lineUpdateNeeded) nextline (istream, line); int cpoints = 0; if(!StringToInt(&cpoints, line.c_str()) || cpoints<0) { std::ostringstream os; os << "Prelut does not specify valid dimension size on channel '"; os << c << ": '" << line << "' in " << fileName << "."; throw Exception(os.str().c_str()); } if(cpoints>=2) { StringVec inputparts, outputparts; nextline (istream, line); pystring::split(pystring::strip(line), inputparts); nextline (istream, line); pystring::split(pystring::strip(line), outputparts); if(static_cast<int>(inputparts.size()) != cpoints || static_cast<int>(outputparts.size()) != cpoints) { std::ostringstream os; os << "Prelut does not specify the expected number of data points. "; os << "Expected: " << cpoints << "."; os << "Found: " << inputparts.size() << ", " << outputparts.size() << "."; os << " In " << fileName << "."; throw Exception(os.str().c_str()); } if(!StringVecToFloatVec(prelut_in[c], inputparts) || !StringVecToFloatVec(prelut_out[c], outputparts)) { std::ostringstream os; os << "Prelut data is malformed, cannot convert to float array."; os << " In " << fileName << "."; throw Exception(os.str().c_str()); } useprelut[c] = (!VecsEqualWithRelError(&(prelut_in[c][0]), static_cast<int>(prelut_in[c].size()), &(prelut_out[c][0]), static_cast<int>(prelut_out[c].size()), 1e-6f)); } else { // Even though it's probably not part of the spec, why not allow for a size 0 // in a channel to be specified? It should be synonymous with identity, // and allows the code lower down to assume all 3 channels exist. prelut_in[c].push_back(0.0f); prelut_in[c].push_back(1.0f); prelut_out[c].push_back(0.0f); prelut_out[c].push_back(1.0f); useprelut[c] = false; } lineUpdateNeeded = true; } if (csptype == "1D") { // How many 1D LUT points do we have. nextline (istream, line); int points1D = std::stoi(line.c_str()); if (points1D <= 0) { std::ostringstream os; os << "A csp 1D LUT with invalid number of entries ("; os << points1D << "): " << line << " ."; os << " In " << fileName << "."; throw Exception(os.str().c_str()); } lut1d_ptr = std::make_shared<Lut1DOpData>(points1D); lut1d_ptr->setFileOutputBitDepth(BIT_DEPTH_F32); Array & lutArray = lut1d_ptr->getArray(); for(int i = 0; i < points1D; ++i) { // Scan for the three floats. nextline (istream, line); std::vector<std::string> lineParts; pystring::split(line, lineParts); std::vector<float> floatArray; if (!StringVecToFloatVec(floatArray, lineParts) || 3 != floatArray.size()) { std::ostringstream os; os << "Malformed 1D csp LUT. Each line of LUT values "; os << "must contain three numbers. Line: '"; os << line << "'. File: "; os << fileName << "."; throw Exception(os.str().c_str()); } // Store each channel. lutArray[i*3 + 0] = floatArray[0]; lutArray[i*3 + 1] = floatArray[1]; lutArray[i*3 + 2] = floatArray[2]; } } else if (csptype == "3D") { // Read the cube size. nextline (istream, line); std::vector<std::string> lineParts; pystring::split(line, lineParts); std::vector<int> cubeSize; if (!StringVecToIntVec(cubeSize, lineParts) || 3 != cubeSize.size()) { std::ostringstream os; os << "Malformed 3D csp in LUT file, couldn't read cube size. '"; os << line << "'. In file: "; os << fileName << "."; throw Exception(os.str().c_str()); } // TODO: Support nonuniform cube sizes. int lutSize = cubeSize[0]; if (lutSize != cubeSize[1] || lutSize != cubeSize[2]) { std::ostringstream os; os << "A csp 3D LUT with nonuniform cube sizes is not supported ("; os << cubeSize[0] << ", " << cubeSize[1] << ", " << cubeSize[2]; os << "): " << line << " ."; throw Exception(os.str().c_str()); } if (lutSize <= 0) { std::ostringstream os; os << "A csp 3D LUT with invalid cube size ("; os << lutSize << "): " << line << "' in " << fileName << "."; throw Exception(os.str().c_str()); } lut3d_ptr = std::make_shared<Lut3DOpData>(lutSize); lut3d_ptr->setFileOutputBitDepth(BIT_DEPTH_F32); Array & lutArray = lut3d_ptr->getArray(); int num3dentries = lutSize * lutSize * lutSize; int r = 0; int g = 0; int b = 0; for(int i=0; i<num3dentries; ++i) { // Load the cube. nextline (istream, line); // OpData::Lut3D Array index, b changes fastest. const unsigned long arrayIdx = GetLut3DIndex_BlueFast(r, g, b, lutSize, lutSize, lutSize); std::vector<std::string> lineParts; pystring::split(line, lineParts); std::vector<float> floatArray; if (!StringVecToFloatVec(floatArray, lineParts) || 3 != floatArray.size()) { std::ostringstream os; os << "Malformed 3D csp LUT, couldn't read cube row ("; os << i << "): " << line << "' in " << fileName << "."; throw Exception(os.str().c_str()); } lutArray[arrayIdx + 0] = floatArray[0]; lutArray[arrayIdx + 1] = floatArray[1]; lutArray[arrayIdx + 2] = floatArray[2]; // CSP stores the LUT in red-fastest order. r += 1; if (r == lutSize) { r = 0; g += 1; if (g == lutSize) { g = 0; b += 1; } } } } CachedFileCSPRcPtr cachedFile = CachedFileCSPRcPtr (new CachedFileCSP ()); cachedFile->metadata = metadata; if(useprelut[0] || useprelut[1] || useprelut[2]) { Lut1DOpDataRcPtr prelut_ptr = std::make_shared<Lut1DOpData>(NUM_PRELUT_SAMPLES); prelut_ptr->setFileOutputBitDepth(BIT_DEPTH_F32); for (int c = 0; c < 3; ++c) { size_t prelut_numpts = prelut_in[c].size(); float from_min = prelut_in[c][0]; float from_max = prelut_in[c][prelut_numpts-1]; // Allocate the interpolator. rsr_Interpolator1D_Raw * cprelut_raw = rsr_Interpolator1D_Raw_create(static_cast<unsigned int>(prelut_numpts)); // Copy our prelut data into the interpolator. for(size_t i=0; i<prelut_numpts; ++i) { cprelut_raw->stims[i] = prelut_in[c][i]; cprelut_raw->values[i] = prelut_out[c][i]; } // Create interpolater, to resample to simple 1D LUT. rsr_Interpolator1D * interpolater = rsr_Interpolator1D_createFromRaw(cprelut_raw); // Resample into 1D LUT. // TODO: Fancy spline analysis to determine required number of samples. cachedFile->prelut_from_min[c] = from_min; cachedFile->prelut_from_max[c] = from_max; Array & prelutArray = prelut_ptr->getArray(); for (int i = 0; i < NUM_PRELUT_SAMPLES; ++i) { float interpo = float(i) / float(NUM_PRELUT_SAMPLES-1); float srcval = lerpf(from_min, from_max, interpo); float newval = rsr_Interpolator1D_interpolate(srcval, interpolater); prelutArray[i*3 + c] = newval; } rsr_Interpolator1D_Raw_destroy(cprelut_raw); rsr_Interpolator1D_destroy(interpolater); } prelut_ptr->setInterpolation(PRELUT_INTERPOLATION); cachedFile->prelut = prelut_ptr; } if(csptype == "1D") { cachedFile->lut1D = lut1d_ptr; } else if (csptype == "3D") { cachedFile->lut3D = lut3d_ptr; } // If file contains neither it throws earlier. return cachedFile; } void LocalFileFormat::bake(const Baker & baker, const std::string & /*formatName*/, std::ostream & ostream) const { const int DEFAULT_CUBE_SIZE = 32; const int DEFAULT_SHAPER_SIZE = 1024; ConstConfigRcPtr config = baker.getConfig(); // TODO: Add 1D/3D LUT writing switch, using hasChannelCrosstalk. int cubeSize = baker.getCubeSize(); if(cubeSize==-1) cubeSize = DEFAULT_CUBE_SIZE; cubeSize = std::max(2, cubeSize); // smallest cube is 2x2x2 std::vector<float> cubeData; cubeData.resize(cubeSize*cubeSize*cubeSize*3); GenerateIdentityLut3D(&cubeData[0], cubeSize, 3, LUT3DORDER_FAST_RED); PackedImageDesc cubeImg(&cubeData[0], cubeSize*cubeSize*cubeSize, 1, 3); std::string looks = baker.getLooks(); std::vector<float> shaperInData; std::vector<float> shaperOutData; // Use an explicitly shaper space. // TODO: Use the optional allocation for the shaper space, // instead of the implied 0-1 uniform allocation. std::string shaperSpace = baker.getShaperSpace(); if(!shaperSpace.empty()) { int shaperSize = baker.getShaperSize(); if(shaperSize<0) shaperSize = DEFAULT_SHAPER_SIZE; if(shaperSize<2) { std::ostringstream os; os << "When a shaper space has been specified, '"; os << baker.getShaperSpace() << "', a shaper size less than 2 is not allowed."; throw Exception(os.str().c_str()); } shaperOutData.resize(shaperSize*3); shaperInData.resize(shaperSize*3); GenerateIdentityLut1D(&shaperOutData[0], shaperSize, 3); GenerateIdentityLut1D(&shaperInData[0], shaperSize, 3); ConstCPUProcessorRcPtr shaperToInput = config->getProcessor(baker.getShaperSpace(), baker.getInputSpace())->getDefaultCPUProcessor(); if(shaperToInput->hasChannelCrosstalk()) { // TODO: Automatically turn shaper into non-crosstalked version? std::ostringstream os; os << "The specified shaperSpace, '"; os << baker.getShaperSpace() << "' has channel crosstalk, which is not appropriate for shapers. "; os << "Please select an alternate shaper space or omit this option."; throw Exception(os.str().c_str()); } PackedImageDesc shaperInImg(&shaperInData[0], shaperSize, 1, 3); shaperToInput->apply(shaperInImg); ConstCPUProcessorRcPtr shaperToTarget; if (!looks.empty()) { LookTransformRcPtr transform = LookTransform::Create(); transform->setLooks(looks.c_str()); transform->setSrc(baker.getShaperSpace()); transform->setDst(baker.getTargetSpace()); shaperToTarget = config->getProcessor(transform, TRANSFORM_DIR_FORWARD)->getDefaultCPUProcessor(); } else { shaperToTarget = config->getProcessor(baker.getShaperSpace(), baker.getTargetSpace())->getDefaultCPUProcessor(); } shaperToTarget->apply(cubeImg); } else { // A shaper is not specified, let's fake one, using the input space allocation as // our guide. ConstColorSpaceRcPtr inputColorSpace = config->getColorSpace(baker.getInputSpace()); if(!inputColorSpace) { std::ostringstream os; os << "Could not find colorspace '" << baker.getInputSpace() << "'"; throw Exception(os.str().c_str()); } // Let's make an allocation transform for this colorspace. AllocationTransformRcPtr allocationTransform = AllocationTransform::Create(); allocationTransform->setAllocation(inputColorSpace->getAllocation()); // numVars may be '0'. int numVars = inputColorSpace->getAllocationNumVars(); if(numVars>0) { std::vector<float> vars(numVars); inputColorSpace->getAllocationVars(&vars[0]); allocationTransform->setVars(numVars, &vars[0]); } else { allocationTransform->setVars(0, NULL); } // What size shaper should we make? int shaperSize = baker.getShaperSize(); if(shaperSize<0) shaperSize = DEFAULT_SHAPER_SIZE; shaperSize = std::max(2, shaperSize); if(inputColorSpace->getAllocation() == ALLOCATION_UNIFORM) { // This is an awesome optimization. // If we know it's a uniform scaling, only 2 points will suffice! shaperSize = 2; } shaperOutData.resize(shaperSize*3); shaperInData.resize(shaperSize*3); GenerateIdentityLut1D(&shaperOutData[0], shaperSize, 3); GenerateIdentityLut1D(&shaperInData[0], shaperSize, 3); // Apply the forward to the allocation to the output shaper y axis, and the cube ConstCPUProcessorRcPtr shaperToInput = config->getProcessor(allocationTransform, TRANSFORM_DIR_INVERSE)->getDefaultCPUProcessor(); PackedImageDesc shaperInImg(&shaperInData[0], shaperSize, 1, 3); shaperToInput->apply(shaperInImg); shaperToInput->apply(cubeImg); // Apply the 3D LUT to the remainder (from the input to the output). ConstProcessorRcPtr inputToTarget; if (!looks.empty()) { LookTransformRcPtr transform = LookTransform::Create(); transform->setLooks(looks.c_str()); transform->setSrc(baker.getInputSpace()); transform->setDst(baker.getTargetSpace()); inputToTarget = config->getProcessor(transform, TRANSFORM_DIR_FORWARD); } else { inputToTarget = config->getProcessor(baker.getInputSpace(), baker.getTargetSpace()); } ConstCPUProcessorRcPtr cpu = inputToTarget->getDefaultCPUProcessor(); cpu->apply(cubeImg); } // Write out the file. ostream << "CSPLUTV100\n"; ostream << "3D\n"; ostream << "\n"; ostream << "BEGIN METADATA\n"; const auto & metadata = baker.getFormatMetadata(); const auto nb = metadata.getNumChildrenElements(); for (int i = 0; i < nb; ++i) { const auto & child = metadata.getChildElement(i); ostream << child.getValue() << "\n"; } ostream << "END METADATA\n"; ostream << "\n"; // Write out the 1D Prelut. ostream.setf(std::ios::fixed, std::ios::floatfield); ostream.precision(6); if(shaperInData.size()<2 || shaperOutData.size() != shaperInData.size()) { throw Exception("Internal shaper size exception."); } if(!shaperInData.empty()) { for(int c=0; c<3; ++c) { ostream << shaperInData.size()/3 << "\n"; for(unsigned int i = 0; i<shaperInData.size()/3; ++i) { if(i != 0) ostream << " "; ostream << shaperInData[3*i+c]; } ostream << "\n"; for(unsigned int i = 0; i<shaperInData.size()/3; ++i) { if(i != 0) ostream << " "; ostream << shaperOutData[3*i+c]; } ostream << "\n"; } } ostream << "\n"; // Write out the 3D Cube. if(cubeSize < 2) { throw Exception("Internal cube size exception."); } ostream << cubeSize << " " << cubeSize << " " << cubeSize << "\n"; for(int i=0; i<cubeSize*cubeSize*cubeSize; ++i) { ostream << cubeData[3*i+0] << " " << cubeData[3*i+1] << " " << cubeData[3*i+2] << "\n"; } ostream << "\n"; } void LocalFileFormat::buildFileOps(OpRcPtrVec & ops, const Config & /*config*/, const ConstContextRcPtr & /*context*/, CachedFileRcPtr untypedCachedFile, const FileTransform & fileTransform, TransformDirection dir) const { CachedFileCSPRcPtr cachedFile = DynamicPtrCast<CachedFileCSP>(untypedCachedFile); // This should never happen. if(!cachedFile) { std::ostringstream os; os << "Cannot build CSP Op. Invalid cache type."; throw Exception(os.str().c_str()); } TransformDirection newDir = fileTransform.getDirection(); newDir = CombineTransformDirections(dir, newDir); if(newDir == TRANSFORM_DIR_FORWARD) { if(cachedFile->prelut) { CreateMinMaxOp(ops, cachedFile->prelut_from_min, cachedFile->prelut_from_max, newDir); CreateLut1DOp(ops, cachedFile->prelut, newDir); } if (cachedFile->lut1D) { cachedFile->lut1D->setInterpolation(fileTransform.getInterpolation()); CreateLut1DOp(ops, cachedFile->lut1D, newDir); } else if (cachedFile->lut3D) { cachedFile->lut3D->setInterpolation(fileTransform.getInterpolation()); CreateLut3DOp(ops, cachedFile->lut3D, newDir); } } else if(newDir == TRANSFORM_DIR_INVERSE) { if (cachedFile->lut1D) { cachedFile->lut1D->setInterpolation(fileTransform.getInterpolation()); CreateLut1DOp(ops, cachedFile->lut1D, newDir); } else if (cachedFile->lut3D) { cachedFile->lut3D->setInterpolation(fileTransform.getInterpolation()); CreateLut3DOp(ops, cachedFile->lut3D, newDir); } if(cachedFile->prelut) { CreateLut1DOp(ops, cachedFile->prelut, newDir); CreateMinMaxOp(ops, cachedFile->prelut_from_min, cachedFile->prelut_from_max, newDir); } } return; } } FileFormat * CreateFileFormatCSP() { return new LocalFileFormat(); } } OCIO_NAMESPACE_EXIT /////////////////////////////////////////////////////////////////////////////// #ifdef OCIO_UNIT_TEST #include "UnitTest.h" namespace OCIO = OCIO_NAMESPACE; namespace { void compareFloats(const std::string& floats1, const std::string& floats2) { // Number comparison. OCIO::StringVec strings1; pystring::split(pystring::strip(floats1), strings1); std::vector<float> numbers1; OCIO::StringVecToFloatVec(numbers1, strings1); OCIO::StringVec strings2; pystring::split(pystring::strip(floats2), strings2); std::vector<float> numbers2; OCIO::StringVecToFloatVec(numbers2, strings2); OCIO_CHECK_EQUAL(numbers1.size(), numbers2.size()); for(unsigned int j=0; j<numbers1.size(); ++j) { OCIO_CHECK_CLOSE(numbers1[j], numbers2[j], 1e-5f); } } } OCIO_ADD_TEST(FileFormatCSP, simple1D) { std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "1D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "2" << "\n"; strebuf << "0.0 1.0" << "\n"; strebuf << "0.0 2.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.4 0.8 1.2 1.6 2.0" << "\n"; strebuf << "3" << "\n"; strebuf << "0.0 0.1 1.0" << "\n"; strebuf << "0.0 0.2 2.0" << "\n"; strebuf << "" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.2 0.3 0.1" << "\n"; strebuf << "0.4 0.5 0.2" << "\n"; strebuf << "0.5 0.6 0.3" << "\n"; strebuf << "0.6 0.8 0.4" << "\n"; strebuf << "1.0 0.9 0.5" << "\n"; float red[6] = { 0.0f, 0.2f, 0.4f, 0.5f, 0.6f, 1.0f }; float green[6] = { 0.0f, 0.3f, 0.5f, 0.6f, 0.8f, 0.9f }; float blue[6] = { 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f }; std::istringstream simple1D; simple1D.str(strebuf.str()); // Read file. std::string emptyString; OCIO::LocalFileFormat tester; OCIO::CachedFileRcPtr cachedFile = tester.read(simple1D, emptyString); OCIO::CachedFileCSPRcPtr csplut = OCIO::DynamicPtrCast<OCIO::CachedFileCSP>(cachedFile); // Check metadata. OCIO_CHECK_EQUAL(csplut->metadata, std::string("foobar\n")); // Check prelut data. OCIO_REQUIRE_ASSERT(csplut->prelut); OCIO_CHECK_EQUAL(csplut->prelut->getFileOutputBitDepth(), OCIO::BIT_DEPTH_F32); const OCIO::Array & prelutArray = csplut->prelut->getArray(); // Check prelut data (note: the spline is resampled into a 1D LUT). const unsigned long length = prelutArray.getLength(); for (unsigned int i = 0; i < length; i += 128) { float input = float(i) / float(length - 1); float output = prelutArray[i * 3]; OCIO_CHECK_CLOSE(input*2.0f, output, 1e-4); } // Check 1D data. OCIO_REQUIRE_ASSERT(csplut->lut1D); OCIO_CHECK_EQUAL(csplut->lut1D->getFileOutputBitDepth(), OCIO::BIT_DEPTH_F32); const OCIO::Array & lutArray = csplut->lut1D->getArray(); const unsigned long lutlength = lutArray.getLength(); OCIO_REQUIRE_EQUAL(lutlength, 6); // Red. unsigned int i; for (i = 0; i < lutlength; ++i) { OCIO_CHECK_EQUAL(red[i], lutArray[i * 3]); } // Green. for (i = 0; i < lutlength; ++i) { OCIO_CHECK_EQUAL(green[i], lutArray[i * 3 + 1]); } // Blue. for (i = 0; i < lutlength; ++i) { OCIO_CHECK_EQUAL(blue[i], lutArray[i * 3 + 2]); } // Check 3D data. OCIO_CHECK_ASSERT(!csplut->lut3D); } OCIO_ADD_TEST(FileFormatCSP, simple3D) { std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "3D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "11" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.2000000 0.4 0.6 0.8 1.0" << "\n"; strebuf << "5" << "\n"; strebuf << "0.0 0.25 0.5 0.6 0.7" << "\n"; strebuf << "0.0 0.25000001 0.5 0.6 0.7" << "\n"; strebuf << "" << "\n"; strebuf << "3 3 3" << "\n"; strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.5 0.0 0.0" << "\n"; strebuf << "1.0 0.0 0.0" << "\n"; strebuf << "0.0 0.5 0.0" << "\n"; strebuf << "0.5 0.5 0.0" << "\n"; strebuf << "1.0 0.5 0.0" << "\n"; strebuf << "0.0 1.0 0.0" << "\n"; strebuf << "0.5 1.0 0.0" << "\n"; strebuf << "1.0 1.0 0.0" << "\n"; strebuf << "0.0 0.0 0.5" << "\n"; strebuf << "0.5 0.0 0.5" << "\n"; strebuf << "1.0 0.0 0.5" << "\n"; strebuf << "0.0 0.5 0.5" << "\n"; strebuf << "0.5 0.5 0.5" << "\n"; strebuf << "1.0 0.5 0.5" << "\n"; strebuf << "0.0 1.0 0.5" << "\n"; strebuf << "0.5 1.0 0.5" << "\n"; strebuf << "1.0 1.0 0.5" << "\n"; strebuf << "0.0 0.0 1.0" << "\n"; strebuf << "0.5 0.0 1.0" << "\n"; strebuf << "1.0 0.0 1.0" << "\n"; strebuf << "0.0 0.5 1.0" << "\n"; strebuf << "0.5 0.5 1.0" << "\n"; strebuf << "1.0 0.5 1.0" << "\n"; strebuf << "0.0 1.0 1.0" << "\n"; strebuf << "0.5 1.0 1.0" << "\n"; strebuf << "1.0 1.0 1.0" << "\n"; float cube[3 * 3 * 3 * 3] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 1.0, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.5, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.0, 1.0, 0.5, 0.5, 0.0, 0.5, 0.5, 0.5, 0.5, 0.5, 1.0, 0.5, 1.0, 0.0, 0.5, 1.0, 0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 1.0, 0.0, 1.0, 1.0, 0.5, 0.0, 1.0, 0.5, 0.5, 1.0, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.5, 1.0, 1.0, 1.0 }; std::istringstream simple3D; simple3D.str(strebuf.str()); // Load file. std::string emptyString; OCIO::LocalFileFormat tester; OCIO::CachedFileRcPtr cachedFile = tester.read(simple3D, emptyString); OCIO::CachedFileCSPRcPtr csplut = OCIO::DynamicPtrCast<OCIO::CachedFileCSP>(cachedFile); // Check metadata. OCIO_CHECK_EQUAL(csplut->metadata, std::string("foobar\n")); // Check prelut data. OCIO_CHECK_ASSERT(!csplut->prelut); // As in & out preLut values are the same // there is nothing to do. // Check cube data. OCIO_REQUIRE_ASSERT(csplut->lut3D); const OCIO::Array & lutArray = csplut->lut3D->getArray(); const unsigned long lutlength = lutArray.getLength(); for(unsigned int i = 0; i < lutlength; ++i) { OCIO_CHECK_EQUAL(cube[i], lutArray[i]); } // Check 1D data. OCIO_CHECK_ASSERT(!csplut->lut1D); } OCIO_ADD_TEST(FileFormatCSP, complete3D) { // Check baker output. OCIO::ConfigRcPtr config = OCIO::Config::Create(); { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("lnf"); cs->setFamily("lnf"); config->addColorSpace(cs); config->setRole(OCIO::ROLE_REFERENCE, cs->getName()); } { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("shaper"); cs->setFamily("shaper"); OCIO::ExponentTransformRcPtr transform1 = OCIO::ExponentTransform::Create(); double test[4] = {2.6, 2.6, 2.6, 1.0}; transform1->setValue(test); cs->setTransform(transform1, OCIO::COLORSPACE_DIR_TO_REFERENCE); config->addColorSpace(cs); } { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("target"); cs->setFamily("target"); OCIO::CDLTransformRcPtr transform1 = OCIO::CDLTransform::Create(); double rgb[3] = {0.1, 0.1, 0.1}; transform1->setOffset(rgb); cs->setTransform(transform1, OCIO::COLORSPACE_DIR_FROM_REFERENCE); config->addColorSpace(cs); } std::ostringstream bout; bout << "CSPLUTV100" << "\n"; bout << "3D" << "\n"; bout << "" << "\n"; bout << "BEGIN METADATA" << "\n"; bout << "date: 2011:02:21 15:22:55" << "\n"; bout << "Baked by OCIO" << "\n"; bout << "END METADATA" << "\n"; bout << "" << "\n"; bout << "10" << "\n"; bout << "0.000000 0.003303 0.020028 0.057476 0.121430 0.216916 0.348468 0.520265 0.736213 1.000000" << "\n"; bout << "0.000000 0.111111 0.222222 0.333333 0.444444 0.555556 0.666667 0.777778 0.888889 1.000000" << "\n"; bout << "10" << "\n"; bout << "0.000000 0.003303 0.020028 0.057476 0.121430 0.216916 0.348468 0.520265 0.736213 1.000000" << "\n"; bout << "0.000000 0.111111 0.222222 0.333333 0.444444 0.555556 0.666667 0.777778 0.888889 1.000000" << "\n"; bout << "10" << "\n"; bout << "0.000000 0.003303 0.020028 0.057476 0.121430 0.216916 0.348468 0.520265 0.736213 1.000000" << "\n"; bout << "0.000000 0.111111 0.222222 0.333333 0.444444 0.555556 0.666667 0.777778 0.888889 1.000000" << "\n"; bout << "" << "\n"; bout << "2 2 2" << "\n"; bout << "0.100000 0.100000 0.100000" << "\n"; bout << "1.100000 0.100000 0.100000" << "\n"; bout << "0.100000 1.100000 0.100000" << "\n"; bout << "1.100000 1.100000 0.100000" << "\n"; bout << "0.100000 0.100000 1.100000" << "\n"; bout << "1.100000 0.100000 1.100000" << "\n"; bout << "0.100000 1.100000 1.100000" << "\n"; bout << "1.100000 1.100000 1.100000" << "\n"; bout << "" << "\n"; OCIO::BakerRcPtr baker = OCIO::Baker::Create(); baker->setConfig(config); baker->getFormatMetadata().addChildElement(OCIO::METADATA_DESCRIPTION, "date: 2011:02:21 15:22:55"); baker->getFormatMetadata().addChildElement(OCIO::METADATA_DESCRIPTION, "Baked by OCIO"); baker->setFormat("cinespace"); baker->setInputSpace("lnf"); baker->setShaperSpace("shaper"); baker->setTargetSpace("target"); baker->setShaperSize(10); baker->setCubeSize(2); std::ostringstream output; baker->bake(output); // std::vector<std::string> osvec; pystring::splitlines(output.str(), osvec); std::vector<std::string> resvec; pystring::splitlines(bout.str(), resvec); OCIO_CHECK_EQUAL(osvec.size(), resvec.size()); for(unsigned int i = 0; i < resvec.size(); ++i) { if(i>6) { // Number comparison. compareFloats(osvec[i], resvec[i]); } else { // text comparison OCIO_CHECK_EQUAL(osvec[i], resvec[i]); } } } OCIO_ADD_TEST(FileFormatCSP, shaper_hdr) { // Check baker output. OCIO::ConfigRcPtr config = OCIO::Config::Create(); { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("lnf"); cs->setFamily("lnf"); config->addColorSpace(cs); config->setRole(OCIO::ROLE_REFERENCE, cs->getName()); } { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("lnf_tweak"); cs->setFamily("lnf_tweak"); OCIO::CDLTransformRcPtr transform1 = OCIO::CDLTransform::Create(); double rgb[3] = {2.0, -2.0, 0.9}; transform1->setOffset(rgb); cs->setTransform(transform1, OCIO::COLORSPACE_DIR_FROM_REFERENCE); config->addColorSpace(cs); } { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("target"); cs->setFamily("target"); OCIO::CDLTransformRcPtr transform1 = OCIO::CDLTransform::Create(); double rgb[3] = {0.1, 0.1, 0.1}; transform1->setOffset(rgb); cs->setTransform(transform1, OCIO::COLORSPACE_DIR_FROM_REFERENCE); config->addColorSpace(cs); } std::ostringstream bout; bout << "CSPLUTV100" << "\n"; bout << "3D" << "\n"; bout << "" << "\n"; bout << "BEGIN METADATA" << "\n"; bout << "date: 2011:02:21 15:22:55" << "\n"; bout << "END METADATA" << "\n"; bout << "" << "\n"; bout << "10" << "\n"; bout << "2.000000 2.111111 2.222222 2.333333 2.444444 2.555556 2.666667 2.777778 2.888889 3.000000" << "\n"; bout << "0.000000 0.111111 0.222222 0.333333 0.444444 0.555556 0.666667 0.777778 0.888889 1.000000" << "\n"; bout << "10" << "\n"; bout << "-2.000000 -1.888889 -1.777778 -1.666667 -1.555556 -1.444444 -1.333333 -1.222222 -1.111111 -1.000000" << "\n"; bout << "0.000000 0.111111 0.222222 0.333333 0.444444 0.555556 0.666667 0.777778 0.888889 1.000000" << "\n"; bout << "10" << "\n"; bout << "0.900000 1.011111 1.122222 1.233333 1.344444 1.455556 1.566667 1.677778 1.788889 1.900000" << "\n"; bout << "0.000000 0.111111 0.222222 0.333333 0.444444 0.555556 0.666667 0.777778 0.888889 1.000000" << "\n"; bout << "" << "\n"; bout << "2 2 2" << "\n"; bout << "0.100000 0.100000 0.100000" << "\n"; bout << "1.100000 0.100000 0.100000" << "\n"; bout << "0.100000 1.100000 0.100000" << "\n"; bout << "1.100000 1.100000 0.100000" << "\n"; bout << "0.100000 0.100000 1.100000" << "\n"; bout << "1.100000 0.100000 1.100000" << "\n"; bout << "0.100000 1.100000 1.100000" << "\n"; bout << "1.100000 1.100000 1.100000" << "\n"; bout << "" << "\n"; OCIO::BakerRcPtr baker = OCIO::Baker::Create(); baker->setConfig(config); baker->getFormatMetadata().addChildElement(OCIO::METADATA_DESCRIPTION, "date: 2011:02:21 15:22:55"); baker->setFormat("cinespace"); baker->setInputSpace("lnf_tweak"); baker->setShaperSpace("lnf"); baker->setTargetSpace("target"); baker->setShaperSize(10); baker->setCubeSize(2); std::ostringstream output; baker->bake(output); // std::vector<std::string> osvec; pystring::splitlines(output.str(), osvec); std::vector<std::string> resvec; pystring::splitlines(bout.str(), resvec); OCIO_CHECK_EQUAL(osvec.size(), resvec.size()); for(unsigned int i = 0; i < resvec.size(); ++i) { if(i>6) { // Number comparison. compareFloats(osvec[i], resvec[i]); } else { // text comparison OCIO_CHECK_EQUAL(osvec[i], resvec[i]); } } } OCIO_ADD_TEST(FileFormatCSP, no_shaper) { // Check baker output. OCIO::ConfigRcPtr config = OCIO::Config::Create(); { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("lnf"); cs->setFamily("lnf"); config->addColorSpace(cs); config->setRole(OCIO::ROLE_REFERENCE, cs->getName()); } { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("target"); cs->setFamily("target"); OCIO::CDLTransformRcPtr transform1 = OCIO::CDLTransform::Create(); double rgb[3] = {0.1, 0.1, 0.1}; transform1->setOffset(rgb); cs->setTransform(transform1, OCIO::COLORSPACE_DIR_FROM_REFERENCE); config->addColorSpace(cs); } std::ostringstream bout; bout << "CSPLUTV100" << "\n"; bout << "3D" << "\n"; bout << "" << "\n"; bout << "BEGIN METADATA" << "\n"; bout << "date: 2011:02:21 15:22:55" << "\n"; bout << "END METADATA" << "\n"; bout << "" << "\n"; bout << "2" << "\n"; bout << "0.000000 1.000000" << "\n"; bout << "0.000000 1.000000" << "\n"; bout << "2" << "\n"; bout << "0.000000 1.000000" << "\n"; bout << "0.000000 1.000000" << "\n"; bout << "2" << "\n"; bout << "0.000000 1.000000" << "\n"; bout << "0.000000 1.000000" << "\n"; bout << "" << "\n"; bout << "2 2 2" << "\n"; bout << "0.100000 0.100000 0.100000" << "\n"; bout << "1.100000 0.100000 0.100000" << "\n"; bout << "0.100000 1.100000 0.100000" << "\n"; bout << "1.100000 1.100000 0.100000" << "\n"; bout << "0.100000 0.100000 1.100000" << "\n"; bout << "1.100000 0.100000 1.100000" << "\n"; bout << "0.100000 1.100000 1.100000" << "\n"; bout << "1.100000 1.100000 1.100000" << "\n"; bout << "" << "\n"; OCIO::BakerRcPtr baker = OCIO::Baker::Create(); baker->setConfig(config); baker->getFormatMetadata().addChildElement(OCIO::METADATA_DESCRIPTION, "date: 2011:02:21 15:22:55"); baker->setFormat("cinespace"); baker->setInputSpace("lnf"); baker->setTargetSpace("target"); baker->setShaperSize(10); baker->setCubeSize(2); std::ostringstream output; baker->bake(output); // std::vector<std::string> osvec; pystring::splitlines(output.str(), osvec); std::vector<std::string> resvec; pystring::splitlines(bout.str(), resvec); OCIO_CHECK_EQUAL(osvec.size(), resvec.size()); for(unsigned int i = 0; i < resvec.size(); ++i) { OCIO_CHECK_EQUAL(osvec[i], resvec[i]); } } OCIO_ADD_TEST(FileFormatCSP, less_strict_parse) { std::ostringstream strebuf; strebuf << " CspluTV100 malformed" << "\n"; strebuf << "3D" << "\n"; strebuf << "" << "\n"; strebuf << " BegIN MEtadATA malformed malformed malfo" << "\n"; strebuf << "foobar" << "\n"; strebuf << " end metadata malformed malformed m a l" << "\n"; strebuf << "" << "\n"; strebuf << "11" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.2000000 0.4 0.6 0.8 1.0" << "\n"; strebuf << "5" << "\n"; strebuf << "0.0 0.25 0.5 0.6 0.7" << "\n"; strebuf << "0.0 0.25000001 0.5 0.6 0.7" << "\n"; strebuf << "" << "\n"; strebuf << "2 2 2" << "\n"; strebuf << "0.100000 0.100000 0.100000" << "\n"; strebuf << "1.100000 0.100000 0.100000" << "\n"; strebuf << "0.100000 1.100000 0.100000" << "\n"; strebuf << "1.100000 1.100000 0.100000" << "\n"; strebuf << "0.100000 0.100000 1.100000" << "\n"; strebuf << "1.100000 0.100000 1.100000" << "\n"; strebuf << "0.100000 1.100000 1.100000" << "\n"; strebuf << "1.100000 1.100000 1.100000" << "\n"; std::istringstream simple3D; simple3D.str(strebuf.str()); // Load file. std::string emptyString; OCIO::LocalFileFormat tester; OCIO::CachedFileRcPtr cachedFile; OCIO_CHECK_NO_THROW(cachedFile = tester.read(simple3D, emptyString)); OCIO::CachedFileCSPRcPtr csplut = OCIO::DynamicPtrCast<OCIO::CachedFileCSP>(cachedFile); // Check metadata. OCIO_CHECK_EQUAL(csplut->metadata, std::string("foobar\n")); // Check prelut data. OCIO_CHECK_ASSERT(!csplut->prelut); // As in & out from the preLut are the same, // there is nothing to do. } OCIO_ADD_TEST(FileFormatCSP, failures1D) { { // Empty. std::istringstream lutStream; // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "file stream empty"); } { // Wrong first line. std::ostringstream strebuf; strebuf << "CSPLUTV2000" << "\n"; // Wrong. strebuf << "1D" << "\n"; strebuf << "" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "expected 'CSPLUTV100'"); } { // Missing LUT. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "Require 1D or 3D"); } { // Can't read prelut size. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "1D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "A" << "\n"; // <------------ Wrong. strebuf << "0.0 1.0" << "\n"; strebuf << "0.0 2.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.4 0.8 1.2 1.6 2.0" << "\n"; strebuf << "3" << "\n"; strebuf << "0.0 0.1 1.0" << "\n"; strebuf << "0.0 0.2 2.0" << "\n"; strebuf << "" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.2 0.3 0.1" << "\n"; strebuf << "0.4 0.5 0.2" << "\n"; strebuf << "0.5 0.6 0.3" << "\n"; strebuf << "0.6 0.8 0.4" << "\n"; strebuf << "1.0 0.9 0.5" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "Prelut does not specify valid dimension size"); } { // Prelut has too many points. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "1D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "2" << "\n"; strebuf << "0.0 1.0 1.0" << "\n"; // <-------- Wrong. strebuf << "0.0 2.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.4 0.8 1.2 1.6 2.0" << "\n"; strebuf << "3" << "\n"; strebuf << "0.0 0.1 1.0" << "\n"; strebuf << "0.0 0.2 2.0" << "\n"; strebuf << "" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.2 0.3 0.1" << "\n"; strebuf << "0.4 0.5 0.2" << "\n"; strebuf << "0.5 0.6 0.3" << "\n"; strebuf << "0.6 0.8 0.4" << "\n"; strebuf << "1.0 0.9 0.5" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("File.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "expected number of data points"); } { // Can't read a float in prelut. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "1D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "2" << "\n"; strebuf << "0.0 notFloat" << "\n"; strebuf << "0.0 2.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.4 0.8 1.2 1.6 2.0" << "\n"; strebuf << "3" << "\n"; strebuf << "0.0 0.1 1.0" << "\n"; strebuf << "0.0 0.2 2.0" << "\n"; strebuf << "" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.2 0.3 0.1" << "\n"; strebuf << "0.4 0.5 0.2" << "\n"; strebuf << "0.5 0.6 0.3" << "\n"; strebuf << "0.6 0.8 0.4" << "\n"; strebuf << "1.0 0.9 0.5" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "Prelut data is malformed"); } { // Bad number of LUT entries. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "1D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "2" << "\n"; strebuf << "0.0 1.0" << "\n"; strebuf << "0.0 2.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.4 0.8 1.2 1.6 2.0" << "\n"; strebuf << "3" << "\n"; strebuf << "0.0 0.1 1.0" << "\n"; strebuf << "0.0 0.2 2.0" << "\n"; strebuf << "" << "\n"; strebuf << "-6" << "\n"; // <------------ Wrong. strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.2 0.3 0.1" << "\n"; strebuf << "0.4 0.5 0.2" << "\n"; strebuf << "0.5 0.6 0.3" << "\n"; strebuf << "0.6 0.8 0.4" << "\n"; strebuf << "1.0 0.9 0.5" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "1D LUT with invalid number of entries"); } { // Too many components on LUT entry. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "1D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "2" << "\n"; strebuf << "0.0 1.0" << "\n"; strebuf << "0.0 2.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.4 0.8 1.2 1.6 2.0" << "\n"; strebuf << "3" << "\n"; strebuf << "0.0 0.1 1.0" << "\n"; strebuf << "0.0 0.2 2.0" << "\n"; strebuf << "" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.0 0.0 0.0" << "\n"; // <------------ Wrong. strebuf << "0.2 0.3 0.1" << "\n"; strebuf << "0.4 0.5 0.2" << "\n"; strebuf << "0.5 0.6 0.3" << "\n"; strebuf << "0.6 0.8 0.4" << "\n"; strebuf << "1.0 0.9 0.5" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "must contain three numbers"); } } OCIO_ADD_TEST(FileFormatCSP, failures3D) { { // Cube size has only 2 entries. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "3D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "11" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.2000000 0.4 0.6 0.8 1.0" << "\n"; strebuf << "5" << "\n"; strebuf << "0.0 0.25 0.5 0.6 0.7" << "\n"; strebuf << "0.0 0.25000001 0.5 0.6 0.7" << "\n"; strebuf << "" << "\n"; strebuf << "3 3" << "\n"; // <------------ Wrong. strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.5 0.0 0.0" << "\n"; strebuf << "1.0 0.0 0.0" << "\n"; strebuf << "0.0 0.5 0.0" << "\n"; strebuf << "0.5 0.5 0.0" << "\n"; strebuf << "1.0 0.5 0.0" << "\n"; strebuf << "0.0 1.0 0.0" << "\n"; strebuf << "0.5 1.0 0.0" << "\n"; strebuf << "1.0 1.0 0.0" << "\n"; strebuf << "0.0 0.0 0.5" << "\n"; strebuf << "0.5 0.0 0.5" << "\n"; strebuf << "1.0 0.0 0.5" << "\n"; strebuf << "0.0 0.5 0.5" << "\n"; strebuf << "0.5 0.5 0.5" << "\n"; strebuf << "1.0 0.5 0.5" << "\n"; strebuf << "0.0 1.0 0.5" << "\n"; strebuf << "0.5 1.0 0.5" << "\n"; strebuf << "1.0 1.0 0.5" << "\n"; strebuf << "0.0 0.0 1.0" << "\n"; strebuf << "0.5 0.0 1.0" << "\n"; strebuf << "1.0 0.0 1.0" << "\n"; strebuf << "0.0 0.5 1.0" << "\n"; strebuf << "0.5 0.5 1.0" << "\n"; strebuf << "1.0 0.5 1.0" << "\n"; strebuf << "0.0 1.0 1.0" << "\n"; strebuf << "0.5 1.0 1.0" << "\n"; strebuf << "1.0 1.0 1.0" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "couldn't read cube size"); } { // Cube sizes are not equal. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "3D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "11" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.2000000 0.4 0.6 0.8 1.0" << "\n"; strebuf << "5" << "\n"; strebuf << "0.0 0.25 0.5 0.6 0.7" << "\n"; strebuf << "0.0 0.25000001 0.5 0.6 0.7" << "\n"; strebuf << "" << "\n"; strebuf << "3 3 4" << "\n"; // <------------ Wrong. strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.5 0.0 0.0" << "\n"; strebuf << "1.0 0.0 0.0" << "\n"; strebuf << "0.0 0.5 0.0" << "\n"; strebuf << "0.5 0.5 0.0" << "\n"; strebuf << "1.0 0.5 0.0" << "\n"; strebuf << "0.0 1.0 0.0" << "\n"; strebuf << "0.5 1.0 0.0" << "\n"; strebuf << "1.0 1.0 0.0" << "\n"; strebuf << "0.0 0.0 0.5" << "\n"; strebuf << "0.5 0.0 0.5" << "\n"; strebuf << "1.0 0.0 0.5" << "\n"; strebuf << "0.0 0.5 0.5" << "\n"; strebuf << "0.5 0.5 0.5" << "\n"; strebuf << "1.0 0.5 0.5" << "\n"; strebuf << "0.0 1.0 0.5" << "\n"; strebuf << "0.5 1.0 0.5" << "\n"; strebuf << "1.0 1.0 0.5" << "\n"; strebuf << "0.0 0.0 1.0" << "\n"; strebuf << "0.5 0.0 1.0" << "\n"; strebuf << "1.0 0.0 1.0" << "\n"; strebuf << "0.0 0.5 1.0" << "\n"; strebuf << "0.5 0.5 1.0" << "\n"; strebuf << "1.0 0.5 1.0" << "\n"; strebuf << "0.0 1.0 1.0" << "\n"; strebuf << "0.5 1.0 1.0" << "\n"; strebuf << "1.0 1.0 1.0" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "nonuniform cube sizes"); } { // Cube size is not >0. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "3D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "11" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.2000000 0.4 0.6 0.8 1.0" << "\n"; strebuf << "5" << "\n"; strebuf << "0.0 0.25 0.5 0.6 0.7" << "\n"; strebuf << "0.0 0.25000001 0.5 0.6 0.7" << "\n"; strebuf << "" << "\n"; strebuf << "-3 -3 -3" << "\n"; // <------------ Wrong. strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.5 0.0 0.0" << "\n"; strebuf << "1.0 0.0 0.0" << "\n"; strebuf << "0.0 0.5 0.0" << "\n"; strebuf << "0.5 0.5 0.0" << "\n"; strebuf << "1.0 0.5 0.0" << "\n"; strebuf << "0.0 1.0 0.0" << "\n"; strebuf << "0.5 1.0 0.0" << "\n"; strebuf << "1.0 1.0 0.0" << "\n"; strebuf << "0.0 0.0 0.5" << "\n"; strebuf << "0.5 0.0 0.5" << "\n"; strebuf << "1.0 0.0 0.5" << "\n"; strebuf << "0.0 0.5 0.5" << "\n"; strebuf << "0.5 0.5 0.5" << "\n"; strebuf << "1.0 0.5 0.5" << "\n"; strebuf << "0.0 1.0 0.5" << "\n"; strebuf << "0.5 1.0 0.5" << "\n"; strebuf << "1.0 1.0 0.5" << "\n"; strebuf << "0.0 0.0 1.0" << "\n"; strebuf << "0.5 0.0 1.0" << "\n"; strebuf << "1.0 0.0 1.0" << "\n"; strebuf << "0.0 0.5 1.0" << "\n"; strebuf << "0.5 0.5 1.0" << "\n"; strebuf << "1.0 0.5 1.0" << "\n"; strebuf << "0.0 1.0 1.0" << "\n"; strebuf << "0.5 1.0 1.0" << "\n"; strebuf << "1.0 1.0 1.0" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "invalid cube size"); } { // One LUT entry has 4 components. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "3D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "11" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.2000000 0.4 0.6 0.8 1.0" << "\n"; strebuf << "5" << "\n"; strebuf << "0.0 0.25 0.5 0.6 0.7" << "\n"; strebuf << "0.0 0.25000001 0.5 0.6 0.7" << "\n"; strebuf << "" << "\n"; strebuf << "3 3 3" << "\n"; strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.5 0.0 0.0" << "\n"; strebuf << "1.0 0.0 0.0" << "\n"; strebuf << "0.0 0.5 0.0" << "\n"; strebuf << "0.5 0.5 0.0 1.0" << "\n"; // <------------ Wrong. strebuf << "1.0 0.5 0.0" << "\n"; strebuf << "0.0 1.0 0.0" << "\n"; strebuf << "0.5 1.0 0.0" << "\n"; strebuf << "1.0 1.0 0.0" << "\n"; strebuf << "0.0 0.0 0.5" << "\n"; strebuf << "0.5 0.0 0.5" << "\n"; strebuf << "1.0 0.0 0.5" << "\n"; strebuf << "0.0 0.5 0.5" << "\n"; strebuf << "0.5 0.5 0.5" << "\n"; strebuf << "1.0 0.5 0.5" << "\n"; strebuf << "0.0 1.0 0.5" << "\n"; strebuf << "0.5 1.0 0.5" << "\n"; strebuf << "1.0 1.0 0.5" << "\n"; strebuf << "0.0 0.0 1.0" << "\n"; strebuf << "0.5 0.0 1.0" << "\n"; strebuf << "1.0 0.0 1.0" << "\n"; strebuf << "0.0 0.5 1.0" << "\n"; strebuf << "0.5 0.5 1.0" << "\n"; strebuf << "1.0 0.5 1.0" << "\n"; strebuf << "0.0 1.0 1.0" << "\n"; strebuf << "0.5 1.0 1.0" << "\n"; strebuf << "1.0 1.0 1.0" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "couldn't read cube row"); } { // One LUT entry has 2 components. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "3D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "11" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.2000000 0.4 0.6 0.8 1.0" << "\n"; strebuf << "5" << "\n"; strebuf << "0.0 0.25 0.5 0.6 0.7" << "\n"; strebuf << "0.0 0.25000001 0.5 0.6 0.7" << "\n"; strebuf << "" << "\n"; strebuf << "3 3 3" << "\n"; strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.5 0.0 0.0" << "\n"; strebuf << "1.0 0.0 0.0" << "\n"; strebuf << "0.0 0.5 0.0" << "\n"; strebuf << "0.5 0.5 0.0" << "\n"; strebuf << "1.0 0.5 0.0" << "\n"; strebuf << "0.0 1.0 0.0" << "\n"; strebuf << "0.5 1.0 0.0" << "\n"; strebuf << "1.0 1.0" << "\n"; // <------------ Wrong. strebuf << "0.0 0.0 0.5" << "\n"; strebuf << "0.5 0.0 0.5" << "\n"; strebuf << "1.0 0.0 0.5" << "\n"; strebuf << "0.0 0.5 0.5" << "\n"; strebuf << "0.5 0.5 0.5" << "\n"; strebuf << "1.0 0.5 0.5" << "\n"; strebuf << "0.0 1.0 0.5" << "\n"; strebuf << "0.5 1.0 0.5" << "\n"; strebuf << "1.0 1.0 0.5" << "\n"; strebuf << "0.0 0.0 1.0" << "\n"; strebuf << "0.5 0.0 1.0" << "\n"; strebuf << "1.0 0.0 1.0" << "\n"; strebuf << "0.0 0.5 1.0" << "\n"; strebuf << "0.5 0.5 1.0" << "\n"; strebuf << "1.0 0.5 1.0" << "\n"; strebuf << "0.0 1.0 1.0" << "\n"; strebuf << "0.5 1.0 1.0" << "\n"; strebuf << "1.0 1.0 1.0" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "couldn't read cube row"); } { // One LUT entry can't be converted to 3 floats. std::ostringstream strebuf; strebuf << "CSPLUTV100" << "\n"; strebuf << "3D" << "\n"; strebuf << "" << "\n"; strebuf << "BEGIN METADATA" << "\n"; strebuf << "foobar" << "\n"; strebuf << "END METADATA" << "\n"; strebuf << "" << "\n"; strebuf << "11" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" << "\n"; strebuf << "6" << "\n"; strebuf << "0.0 0.2 0.4 0.6 0.8 1.0" << "\n"; strebuf << "0.0 0.2000000 0.4 0.6 0.8 1.0" << "\n"; strebuf << "5" << "\n"; strebuf << "0.0 0.25 0.5 0.6 0.7" << "\n"; strebuf << "0.0 0.25000001 0.5 0.6 0.7" << "\n"; strebuf << "" << "\n"; strebuf << "3 3 3" << "\n"; strebuf << "0.0 0.0 0.0" << "\n"; strebuf << "0.5 0.0 0.0" << "\n"; strebuf << "1.0 0.0 0.0" << "\n"; strebuf << "0.0 0.5 0.0" << "\n"; strebuf << "0.5 0.5 0.0" << "\n"; strebuf << "1.0 0.5 One" << "\n"; // <------------ Wrong. strebuf << "0.0 1.0 0.0" << "\n"; strebuf << "0.5 1.0 0.0" << "\n"; strebuf << "1.0 1.0 0.0" << "\n"; strebuf << "0.0 0.0 0.5" << "\n"; strebuf << "0.5 0.0 0.5" << "\n"; strebuf << "1.0 0.0 0.5" << "\n"; strebuf << "0.0 0.5 0.5" << "\n"; strebuf << "0.5 0.5 0.5" << "\n"; strebuf << "1.0 0.5 0.5" << "\n"; strebuf << "0.0 1.0 0.5" << "\n"; strebuf << "0.5 1.0 0.5" << "\n"; strebuf << "1.0 1.0 0.5" << "\n"; strebuf << "0.0 0.0 1.0" << "\n"; strebuf << "0.5 0.0 1.0" << "\n"; strebuf << "1.0 0.0 1.0" << "\n"; strebuf << "0.0 0.5 1.0" << "\n"; strebuf << "0.5 0.5 1.0" << "\n"; strebuf << "1.0 0.5 1.0" << "\n"; strebuf << "0.0 1.0 1.0" << "\n"; strebuf << "0.5 1.0 1.0" << "\n"; strebuf << "1.0 1.0 1.0" << "\n"; std::istringstream lutStream; lutStream.str(strebuf.str()); // Read file. std::string fileName("file.name"); OCIO::LocalFileFormat tester; OCIO_CHECK_THROW_WHAT(tester.read(lutStream, fileName), OCIO::Exception, "couldn't read cube row"); } } // TODO: More strenuous tests of prelut resampling (non-noop preluts) #endif // OCIO_UNIT_TEST
39.974882
142
0.437087
[ "object", "vector", "transform", "3d" ]
a36367b482b7ff95931aabd47711102929531b6d
30,478
cpp
C++
deps/src/boost_1_65_1/libs/graph_parallel/test/algorithm_performance.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
deps/src/boost_1_65_1/libs/graph_parallel/test/algorithm_performance.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
deps/src/boost_1_65_1/libs/graph_parallel/test/algorithm_performance.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Copyright 2004 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Nick Edmonds // Andrew Lumsdaine // #define PBGL_ACCOUNTING #include <boost/graph/use_mpi.hpp> #include <boost/graph/distributed/compressed_sparse_row_graph.hpp> #include <boost/graph/distributed/adjacency_list.hpp> #include <boost/graph/distributed/mpi_process_group.hpp> #include <boost/test/minimal.hpp> #include <boost/random.hpp> #include <boost/property_map/parallel/distributed_property_map.hpp> #include <boost/graph/distributed/graphviz.hpp> #include <boost/graph/iteration_macros.hpp> #include <boost/graph/properties.hpp> #include <boost/graph/rmat_graph_generator.hpp> #include <boost/graph/small_world_generator.hpp> #include <boost/graph/erdos_renyi_generator.hpp> #include <boost/graph/distributed/connected_components.hpp> #include <boost/graph/distributed/connected_components_parallel_search.hpp> #include <boost/graph/distributed/betweenness_centrality.hpp> #include <boost/graph/distributed/delta_stepping_shortest_paths.hpp> #include <time.h> #include <sys/time.h> #include <iostream> #include <iomanip> #include <vector> #include <stdint.h> // Edge distribution tags select a generator struct rmat_edge_distribution_tag { }; struct rmat_unique_edge_distribution_tag { }; using namespace boost; using boost::graph::distributed::mpi_process_group; /**************************************************************************** * Timing ****************************************************************************/ #ifndef PBGL_ACCOUNTING typedef double time_type; inline time_type get_time() { timeval tp; gettimeofday(&tp, 0); return tp.tv_sec + tp.tv_usec / 1000000.0; } std::string print_time(time_type t) { std::ostringstream out; out << std::setiosflags(std::ios::fixed) << std::setprecision(2) << t; return out.str(); } #endif // PBGL_ACCOUNTING /**************************************************************************** * Edge weight generator iterator * ****************************************************************************/ template<typename F, typename RandomGenerator> class generator_iterator { public: typedef std::input_iterator_tag iterator_category; typedef typename F::result_type value_type; typedef const value_type& reference; typedef const value_type* pointer; typedef void difference_type; explicit generator_iterator(RandomGenerator& gen, const F& f = F()) : f(f), gen(&gen) { value = this->f(gen); } reference operator*() const { return value; } pointer operator->() const { return &value; } generator_iterator& operator++() { value = f(*gen); return *this; } generator_iterator operator++(int) { generator_iterator temp(*this); ++(*this); return temp; } bool operator==(const generator_iterator& other) const { return f == other.f; } bool operator!=(const generator_iterator& other) const { return !(*this == other); } private: F f; RandomGenerator* gen; value_type value; }; template<typename F, typename RandomGenerator> inline generator_iterator<F, RandomGenerator> make_generator_iterator( RandomGenerator& gen, const F& f) { return generator_iterator<F, RandomGenerator>(gen, f); } /**************************************************************************** * Edge Property * ****************************************************************************/ typedef int weight_type; struct WeightedEdge { WeightedEdge(weight_type weight = 0) : weight(weight) { } weight_type weight; template<typename Archiver> void serialize(Archiver& ar, const unsigned int /*version*/) { ar & weight; } }; /**************************************************************************** * Algorithm Tests * ****************************************************************************/ template <typename Graph> void test_directed_sequential_algorithms(const Graph& g) { } template <typename Graph> void test_undirected_sequential_algorithms(const Graph& g) { std::vector<unsigned int> componentS(num_vertices(g)); typedef iterator_property_map< std::vector<unsigned int>::iterator, typename property_map<Graph, vertex_index_t>::type> ComponentMap; ComponentMap component(componentS.begin(), get(vertex_index, g)); time_type start = get_time(); unsigned int num_components = connected_components(g, component); time_type end = get_time(); std::cerr << " Sequential connected Components time = " << print_time(end - start) << " seconds.\n" << " " << num_components << " components identified\n"; } template <typename Graph, typename EdgeWeightMap> void test_directed_csr_only_algorithms(const Graph& g, EdgeWeightMap weight, typename graph_traits<Graph>::vertices_size_type num_sources, typename property_traits<EdgeWeightMap>::value_type C) { typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor; typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename graph_traits<Graph>::edges_size_type edges_size_type; typedef typename boost::graph::parallel::process_group_type<Graph>::type process_group_type; process_group_type pg = process_group(g); typename process_group_type::process_id_type id = process_id(pg); typename process_group_type::process_size_type p = num_processes(pg); vertices_size_type n = num_vertices(g); n = boost::parallel::all_reduce(pg, n, std::plus<vertices_size_type>()); edges_size_type m = num_edges(g); m = boost::parallel::all_reduce(pg, m, std::plus<edges_size_type>()); // // Betweenness Centrality (Approximate) // queue<vertex_descriptor> delta_stepping_vertices; { // Distributed Centrality Map typedef typename property_map<Graph, vertex_index_t>::const_type IndexMap; typedef iterator_property_map<std::vector<int>::iterator, IndexMap> CentralityMap; std::vector<int> centralityS(num_vertices(g), 0); CentralityMap centrality(centralityS.begin(), get(vertex_index, g)); // Calculate number of vertices of degree 0 vertices_size_type n0 = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (out_degree(v, g) == 0) n0++; } n0 = boost::parallel::all_reduce(pg, n0, std::plus<vertices_size_type>()); queue<vertex_descriptor> sources; { assert(num_sources >= p); // Don't feel like adding a special case for num_sources < p minstd_rand gen; uniform_int<vertices_size_type> rand_vertex(0, num_vertices(g) - 1); std::vector<vertex_descriptor> all_sources, local_sources; vertices_size_type local_vertices = vertices_size_type(floor((double)num_sources / p)); local_vertices += (id < (num_sources - (p * local_vertices)) ? 1 : 0); while (local_vertices > 0) { vertex_iterator iter = vertices(g).first; std::advance(iter, rand_vertex(gen)); if (out_degree(*iter, g) != 0 && std::find(local_sources.begin(), local_sources.end(), *iter) == local_sources.end()) { local_sources.push_back(*iter); --local_vertices; } } all_gather(pg, local_sources.begin(), local_sources.end(), all_sources); std::sort(all_sources.begin(), all_sources.end()); for (typename std::vector<vertex_descriptor>::iterator iter = all_sources.begin(); iter != all_sources.end(); ++iter) { sources.push(*iter); delta_stepping_vertices.push(*iter); } } // NOTE: The delta below assumes uniform edge weight distribution time_type start = get_time(); brandes_betweenness_centrality(g, buffer(sources).weight_map(weight). centrality_map(centrality).lookahead((m / n) * (C / 2))); time_type end = get_time(); edges_size_type exactTEPs = edges_size_type(floor(7 * n* (n - n0) / (end - start))); if (id == 0) std::cerr << " Betweenness Centrality Approximate (" << num_sources << " sources) = " << print_time(end - start) << " (" << exactTEPs << " TEPs)\n"; } // // Delta stepping performance (to compare to SSSP inside BC // if (false) { typedef typename property_map<Graph, vertex_index_t>::const_type IndexMap; typedef iterator_property_map<std::vector<int>::iterator, IndexMap> DistanceMap; std::vector<int> distanceS(num_vertices(g), 0); DistanceMap distance(distanceS.begin(), get(vertex_index, g)); while(!delta_stepping_vertices.empty()) { time_type start = get_time(); delta_stepping_shortest_paths(g, delta_stepping_vertices.top(), dummy_property_map(), distance, weight); time_type end = get_time(); delta_stepping_vertices.pop(); distance.reset(); if (id == 0) std::cerr << " Delta-stepping shortest paths = " << print_time(end - start) << std::endl; } } } template <typename Graph> void test_directed_algorithms(const Graph& g) { } template <typename Graph> void test_undirected_algorithms(const Graph& g) { typedef typename boost::graph::parallel::process_group_type<Graph>::type process_group_type; process_group_type pg = process_group(g); typename process_group_type::process_id_type id = process_id(pg); typename process_group_type::process_size_type p = num_processes(pg); // Connected Components std::vector<unsigned int> local_components_vec(num_vertices(g)); typedef iterator_property_map< std::vector<unsigned int>::iterator, typename property_map<Graph, vertex_index_t>::type> ComponentMap; ComponentMap component(local_components_vec.begin(), get(vertex_index, g)); int num_components; time_type start = get_time(); num_components = connected_components(g, component); time_type end = get_time(); if (id == 0) std::cerr << " Connected Components time = " << print_time(end - start) << " seconds.\n" << " " << num_components << " components identified\n"; start = get_time(); num_components = boost::graph::distributed::connected_components_ps(g, component); end = get_time(); if (id == 0) std::cerr << " Connected Components (parallel search) time = " << print_time(end - start) << " seconds.\n" << " " << num_components << " components identified\n"; } /**************************************************************************** * Graph Type Tests * ****************************************************************************/ // TODO: Re-seed PRNG before sequential tests to get the same graph as the // distributed case? // // Compressed Sparse Row // // R-MAT template <typename ProcessGroup, typename RandomGenerator, typename Distribution> void test_csr(const ProcessGroup& pg, RandomGenerator& gen, Distribution& distrib, bool sequential_tests, size_t N, size_t M, size_t C, double a, double b, double c, double d, size_t num_sources, rmat_edge_distribution_tag) { if (process_id(pg) == 0) std::cerr << " R-MAT\n"; typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge, no_property, distributedS<mpi_process_group> > Graph; Graph g(sorted_rmat_iterator<RandomGenerator, Graph>(gen, N, M, a, b, c, d), sorted_rmat_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_directed_algorithms(g); test_directed_csr_only_algorithms(g, get(&WeightedEdge::weight, g), num_sources, C); if (sequential_tests && process_id(pg) == 0) { typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge> seqGraph; seqGraph sg(edges_are_sorted, sorted_rmat_iterator<RandomGenerator, seqGraph>(gen, N, M, a, b, c, d), sorted_rmat_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_directed_sequential_algorithms(sg); } } // R-MAT with unique edges template <typename ProcessGroup, typename RandomGenerator, typename Distribution> void test_csr(const ProcessGroup& pg, RandomGenerator& gen, Distribution& distrib, bool sequential_tests, size_t N, size_t M, size_t C, double a, double b, double c, double d, size_t num_sources, rmat_unique_edge_distribution_tag) { if (process_id(pg) == 0) std::cerr << " R-MAT - unique\n"; typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge, no_property, distributedS<mpi_process_group> > Graph; // Last boolean parameter makes R-MAT bidirectional Graph g(sorted_unique_rmat_iterator<RandomGenerator, Graph>(gen, N, M, a, b, c, d), sorted_unique_rmat_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_directed_algorithms(g); test_directed_csr_only_algorithms(g, get(&WeightedEdge::weight, g), num_sources, C); if (sequential_tests && process_id(pg) == 0) { typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge> seqGraph; seqGraph sg(edges_are_sorted, sorted_unique_rmat_iterator<RandomGenerator, seqGraph>(gen, N, M, a, b, c, d), sorted_unique_rmat_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_directed_sequential_algorithms(sg); } } // Erdos-Renyi template <typename ProcessGroup, typename RandomGenerator, typename Distribution> void test_csr(const ProcessGroup& pg, RandomGenerator& gen, Distribution& distrib, bool sequential_tests, size_t N, size_t M, size_t C, size_t num_sources) { if (process_id(pg) == 0) std::cerr << " Erdos-Renyi\n"; double _p = static_cast<double>(M) / (N*N); typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge, no_property, distributedS<mpi_process_group> > Graph; Graph g(sorted_erdos_renyi_iterator<RandomGenerator, Graph>(gen, N, _p/2), sorted_erdos_renyi_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_directed_algorithms(g); test_directed_csr_only_algorithms(g, get(&WeightedEdge::weight, g), num_sources, C); if (sequential_tests && process_id(pg) == 0) { typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge> seqGraph; seqGraph sg(edges_are_sorted, sorted_erdos_renyi_iterator<RandomGenerator, seqGraph>(gen, N, _p/2), sorted_erdos_renyi_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_directed_sequential_algorithms(sg); } } // Small World template <typename ProcessGroup, typename RandomGenerator, typename Distribution> void test_csr(const ProcessGroup& pg, RandomGenerator& gen, Distribution& distrib, bool sequential_tests, size_t N, size_t M, size_t C, double p, size_t num_sources) { if (process_id(pg) == 0) std::cerr << " Small-World\n"; int k = M / N; typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge, no_property, distributedS<mpi_process_group> > Graph; Graph g(small_world_iterator<RandomGenerator, Graph>(gen, N, k, p), small_world_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_directed_algorithms(g); test_directed_csr_only_algorithms(g, get(&WeightedEdge::weight, g), num_sources, C); if (sequential_tests && process_id(pg) == 0) { typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge> seqGraph; seqGraph sg(edges_are_sorted, small_world_iterator<RandomGenerator, seqGraph>(gen, N, k, p), small_world_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_directed_sequential_algorithms(sg); } } // // Adjacency List // // R-MAT template <typename ProcessGroup, typename RandomGenerator, typename Distribution> void test_adjacency_list(const ProcessGroup& pg, RandomGenerator& gen, Distribution& distrib, bool sequential_tests, size_t N, size_t M, size_t C, double a, double b, double c, double d, rmat_edge_distribution_tag) { if (process_id(pg) == 0) std::cerr << "R-MAT\n"; { typedef adjacency_list<vecS, distributedS<mpi_process_group, vecS>, directedS, no_property, WeightedEdge> Graph; Graph g(rmat_iterator<RandomGenerator, Graph>(gen, N, M, a, b, c, d), rmat_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_directed_algorithms(g); } { typedef adjacency_list<vecS, distributedS<mpi_process_group, vecS>, undirectedS, no_property, WeightedEdge> Graph; Graph g(rmat_iterator<RandomGenerator, Graph>(gen, N, M, a, b, c, d), rmat_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_undirected_algorithms(g); } if (sequential_tests && process_id(pg) == 0) { { typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_weight_t, int> > seqGraph; seqGraph sg(rmat_iterator<RandomGenerator, seqGraph>(gen, N, M, a, b, c, d), rmat_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_directed_sequential_algorithms(sg); } { typedef adjacency_list<vecS, vecS, undirectedS, no_property, property<edge_weight_t, int> > seqGraph; seqGraph sg(rmat_iterator<RandomGenerator, seqGraph>(gen, N, M, a, b, c, d), rmat_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_undirected_sequential_algorithms(sg); } } } // R-MAT with unique edges template <typename ProcessGroup, typename RandomGenerator, typename Distribution> void test_adjacency_list(const ProcessGroup& pg, RandomGenerator& gen, Distribution& distrib, bool sequential_tests, size_t N, size_t M, size_t C, double a, double b, double c, double d, rmat_unique_edge_distribution_tag) { if (process_id(pg) == 0) std::cerr << " R-MAT - unique\n"; { typedef adjacency_list<vecS, distributedS<mpi_process_group, vecS>, directedS, no_property, WeightedEdge> Graph; Graph g(sorted_unique_rmat_iterator<RandomGenerator, Graph>(gen, N, M, a, b, c, d), sorted_unique_rmat_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_directed_algorithms(g); } { typedef adjacency_list<vecS, distributedS<mpi_process_group, vecS>, undirectedS, no_property, WeightedEdge> Graph; Graph g(sorted_unique_rmat_iterator<RandomGenerator, Graph>(gen, N, M, a, b, c, d), sorted_unique_rmat_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_undirected_algorithms(g); } if (sequential_tests && process_id(pg) == 0) { { typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_weight_t, int> > seqGraph; seqGraph sg(sorted_unique_rmat_iterator<RandomGenerator, seqGraph>(gen, N, M, a, b, c, d), sorted_unique_rmat_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_directed_sequential_algorithms(sg); } { typedef adjacency_list<vecS, vecS, undirectedS, no_property, property<edge_weight_t, int> > seqGraph; seqGraph sg(sorted_unique_rmat_iterator<RandomGenerator, seqGraph>(gen, N, M, a, b, c, d), sorted_unique_rmat_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_undirected_sequential_algorithms(sg); } } } // Erdos-Renyi template <typename ProcessGroup, typename RandomGenerator, typename Distribution> void test_adjacency_list(const ProcessGroup& pg, RandomGenerator& gen, Distribution& distrib, bool sequential_tests, size_t N, size_t M, size_t C) { if (process_id(pg) == 0) std::cerr << " Erdos-Renyi\n"; double _p = static_cast<double>(M) / N*N; { typedef adjacency_list<vecS, distributedS<mpi_process_group, vecS>, directedS, no_property, WeightedEdge> Graph; Graph g(erdos_renyi_iterator<RandomGenerator, Graph>(gen, N, _p/2), erdos_renyi_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_directed_algorithms(g); } { typedef adjacency_list<vecS, distributedS<mpi_process_group, vecS>, undirectedS, no_property, WeightedEdge> Graph; Graph g(erdos_renyi_iterator<RandomGenerator, Graph>(gen, N, _p/2), erdos_renyi_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_undirected_algorithms(g); } if (sequential_tests && process_id(pg) == 0) { { typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_weight_t, int> > seqGraph; seqGraph sg(erdos_renyi_iterator<RandomGenerator, seqGraph>(gen, N, _p/2), erdos_renyi_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_directed_sequential_algorithms(sg); } { typedef adjacency_list<vecS, vecS, undirectedS, no_property, property<edge_weight_t, int> > seqGraph; seqGraph sg(erdos_renyi_iterator<RandomGenerator, seqGraph>(gen, N, _p/2), erdos_renyi_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_undirected_sequential_algorithms(sg); } } } // Small World template <typename ProcessGroup, typename RandomGenerator, typename Distribution> void test_adjacency_list(const ProcessGroup& pg, RandomGenerator& gen, Distribution& distrib, bool sequential_tests, size_t N, size_t M, size_t C, double p) { if (process_id(pg) == 0) std::cerr << " Small-World\n"; int k = M / N; { typedef adjacency_list<vecS, distributedS<mpi_process_group, vecS>, directedS, no_property, WeightedEdge> Graph; Graph g(small_world_iterator<RandomGenerator, Graph>(gen, N, k, p), small_world_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_directed_algorithms(g); } { typedef adjacency_list<vecS, distributedS<mpi_process_group, vecS>, undirectedS, no_property, WeightedEdge> Graph; Graph g(small_world_iterator<RandomGenerator, Graph>(gen, N, k, p), small_world_iterator<RandomGenerator, Graph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N, pg, distrib); test_undirected_algorithms(g); } if (sequential_tests && process_id(pg) == 0) { { typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_weight_t, int> > seqGraph; seqGraph sg(small_world_iterator<RandomGenerator, seqGraph>(gen, N, k, p), small_world_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_directed_sequential_algorithms(sg); } { typedef adjacency_list<vecS, vecS, undirectedS, no_property, property<edge_weight_t, int> > seqGraph; seqGraph sg(small_world_iterator<RandomGenerator, seqGraph>(gen, N, k, p), small_world_iterator<RandomGenerator, seqGraph>(), make_generator_iterator(gen, uniform_int<int>(1, C)), N); test_undirected_sequential_algorithms(sg); } } } void usage() { std::cerr << "Algorithm Performance Test\n" << "Usage : algorithm_performance [options]\n\n" << "Options are:\n" << "\t--vertices v\t\t\tNumber of vertices in the graph\n" << "\t--edges v\t\t\tNumber of edges in the graph\n" << "\t--seed s\t\t\tSeed for synchronized random number generator\n" << "\t--max-weight miw\t\tMaximum integer edge weight\n" << "\t--rewire-probability\t\tRewire-probabitility (p) for small-world graphs\n" << "\t--dot\t\t\t\tEmit a dot file containing the graph\n" << "\t--verify\t\t\tVerify result\n" << "\t--degree-dist\t\t\tOutput degree distribution of graph\n" << "\t--sequential-graph\t\tRun sequential graph tests\n" << "\t--erdos-renyi\t\t\tRun tests on Erdos-Renyi graphs\n" << "\t--small-world\t\t\tRun tests on Small World graphs\n" << "\t--rmat\t\t\t\tRun tests on R-MAT graphs\n" << "\t--rmat-unique\t\t\tRun tests on R-MAT graphs with no duplicate edges\n" << "\t--csr <bool>\t\t\tRun tests using CSR graphs\n" << "\t--adjacency-list <bool>\t\tRun tests using Adjacency List graphs\n"; } int test_main(int argc, char* argv[]) { mpi::environment env(argc, argv); rand48 gen; // Default args size_t n = 100, m = 8*n, c = 100, num_sources = 32, num_headers = 16 * 1024, batch_buffer_size = 1024 * 1024; uint64_t seed = 1; bool emit_dot_file = false, verify = false, sequential_graph = false, show_degree_dist = false, erdos_renyi = false, small_world = false, rmat = false, rmat_unique = false, csr = false, adj_list = false; double p = 0.1, rmat_a = 0.5, rmat_b = 0.25, rmat_c = 0.1, rmat_d = 0.15; // Parse args for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "--vertices") n = boost::lexical_cast<size_t>( argv[i+1] ); if (arg == "--seed") seed = boost::lexical_cast<uint64_t>( argv[i+1] ); if (arg == "--edges") m = boost::lexical_cast<size_t>( argv[i+1] ); if (arg == "--max-weight") c = boost::lexical_cast<int>( argv[i+1] ); if (arg == "--batch-buffer-size") { batch_buffer_size = boost::lexical_cast<size_t>( argv[i+1] ); num_headers = batch_buffer_size / 16; num_headers = num_headers > 0 ? num_headers : 1; } if (arg == "--rewire-probability") p = boost::lexical_cast<double>( argv[i+1] ); if (arg == "--num-sources") num_sources = boost::lexical_cast<size_t>( argv[i + 1] ); if (arg == "--erdos-renyi") erdos_renyi = true; if (arg == "--small-world") small_world = true; if (arg == "--rmat") rmat = true; if (arg == "--rmat-unique") rmat_unique = true; if (arg == "--dot") emit_dot_file = true; if (arg == "--verify") verify = true; if (arg == "--degree-dist") show_degree_dist = true; if (arg == "--sequential-graph") sequential_graph = true; if (arg == "--csr") csr = std::string(argv[i+1]) == "true"; if (arg == "--adjacency-list") adj_list = std::string(argv[i+1]) == "true"; } mpi_process_group pg(num_headers, batch_buffer_size); if (argc == 1) { if (process_id(pg) == 0) usage(); exit(-1); } gen.seed(seed); parallel::variant_distribution<mpi_process_group> distrib = parallel::block(pg, n); if (csr) { if (process_id(pg) == 0) std::cerr << "CSR Graph Tests\n"; if (erdos_renyi) test_csr(pg, gen, distrib, sequential_graph, n, m, c, num_sources); if (small_world) test_csr(pg, gen, distrib, sequential_graph, n, m, c, p, num_sources); if (rmat) test_csr(pg, gen, distrib, sequential_graph, n, m, c, rmat_a, rmat_b, rmat_c, rmat_d, num_sources, rmat_edge_distribution_tag()); if (rmat_unique) test_csr(pg, gen, distrib, sequential_graph, n, m, c, rmat_a, rmat_b, rmat_c, rmat_d, num_sources, rmat_unique_edge_distribution_tag()); } gen.seed(seed); // DEBUG if (adj_list) { if (process_id(pg) == 0) std::cerr << "Adjacency List Graph Tests\n"; if (erdos_renyi) test_adjacency_list(pg, gen, distrib, sequential_graph, n, m, c); if (small_world) test_adjacency_list(pg, gen, distrib, sequential_graph, n, m, c, p); if (rmat) test_adjacency_list(pg, gen, distrib, sequential_graph, n, m, c, rmat_a, rmat_b, rmat_c, rmat_d, rmat_edge_distribution_tag()); if (rmat_unique) test_adjacency_list(pg, gen, distrib, sequential_graph, n, m, c, rmat_a, rmat_b, rmat_c, rmat_d, rmat_unique_edge_distribution_tag()); } return 0; }
34.322072
101
0.632555
[ "vector" ]
a36484c16b69ee3de5d468c255f396ca8cfcd5ac
467
cpp
C++
119-Pascals-Triangle-II/Pascals-Triangle-2-DC.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
4
2018-08-07T11:45:32.000Z
2019-05-19T08:52:19.000Z
119-Pascals-Triangle-II/Pascals-Triangle-2-DC.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
null
null
null
119-Pascals-Triangle-II/Pascals-Triangle-2-DC.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: vector<int> getRow(int rowIndex) { if(rowIndex == 0){ return {1}; } //Decrease and Conqure auto last = getRow(rowIndex - 1); vector<int> n(rowIndex+1,1); for(int i =0; i<last.size()-1; i++){ n[i+1] = last[i]+last[i+1]; } return n; } }; int main(){ return 0; }
16.678571
44
0.505353
[ "vector" ]
a368097bdcbd54a9558183f04379c4adbf9a96b9
38,964
cc
C++
src/vnsw/agent/pkt/pkt_sandesh_flow.cc
EWERK-DIGITAL/tf-controller
311ea863b03d425a67d04d27c1f1b9cf1e20c926
[ "Apache-2.0" ]
37
2020-09-21T10:42:26.000Z
2022-01-09T10:16:40.000Z
src/vnsw/agent/pkt/pkt_sandesh_flow.cc
EWERK-DIGITAL/tf-controller
311ea863b03d425a67d04d27c1f1b9cf1e20c926
[ "Apache-2.0" ]
null
null
null
src/vnsw/agent/pkt/pkt_sandesh_flow.cc
EWERK-DIGITAL/tf-controller
311ea863b03d425a67d04d27c1f1b9cf1e20c926
[ "Apache-2.0" ]
21
2020-08-25T12:48:42.000Z
2022-03-22T04:32:18.000Z
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <pkt/pkt_sandesh_flow.h> #include <pkt/flow_mgmt.h> #include <pkt/flow_mgmt/flow_entry_info.h> #include <pkt/flow_mgmt/flow_mgmt_entry.h> #include <vector> #include <boost/date_time/posix_time/posix_time.hpp> #include <sstream> #include <algorithm> #include <cmn/agent_stats.h> #include <uve/agent_uve.h> #include <vrouter/flow_stats/flow_stats_collector.h> #include <vrouter/ksync/ksync_init.h> #include <vrouter/ksync/ksync_flow_index_manager.h> static string InetRouteFlowMgmtKeyToString(uint16_t id, InetRouteFlowMgmtKey *key) { std::stringstream ss; uint16_t plen = key->plen(); ss << id << PktSandeshFlow::kDelimiter; ss << key->vrf_id() << PktSandeshFlow::kDelimiter; ss << key->ip().to_string() << PktSandeshFlow::kDelimiter; ss << plen; return ss.str(); } #define SET_SANDESH_FLOW_DATA(agent, data, fe, info) \ data.set_vrf(fe->data().vrf); \ data.set_sip(fe->key().src_addr.to_string()); \ data.set_dip(fe->key().dst_addr.to_string()); \ data.set_src_port((unsigned)fe->key().src_port); \ data.set_dst_port((unsigned)fe->key().dst_port); \ data.set_protocol(fe->key().protocol); \ data.set_dest_vrf(fe->data().dest_vrf); \ data.set_uuid(UuidToString(fe->uuid())); \ data.set_action(fe->match_p().action_info.action); \ std::vector<ActionStr> action_str_l; \ SetActionStr(fe->match_p().action_info, action_str_l); \ if ((fe->match_p().action_info.action & TrafficAction::DROP_FLAGS) != 0) {\ data.set_drop_reason(fe->DropReasonStr(fe->data().drop_reason)); \ } \ data.set_action_str(action_str_l); \ std::vector<MirrorActionSpec>::const_iterator mait; \ std::vector<MirrorInfo> mirror_l; \ for (mait = fe->match_p().action_info.mirror_l.begin(); \ mait != fe->match_p().action_info.mirror_l.end(); \ ++mait) { \ MirrorInfo minfo; \ minfo.set_mirror_destination((*mait).ip.to_string()); \ minfo.set_mirror_port((*mait).port); \ mirror_l.push_back(minfo); \ } \ data.set_mirror_l(mirror_l); \ if (fe->is_flags_set(FlowEntry::IngressDir)) { \ data.set_direction("ingress"); \ } else { \ data.set_direction("egress"); \ } \ if (info) { \ data.set_stats_bytes(info->bytes()); \ data.set_stats_packets(info->packets()); \ } \ if (fe->is_flags_set(FlowEntry::NatFlow)) { \ data.set_nat("enabled"); \ } else { \ data.set_nat("disabled"); \ } \ data.set_gen_id(fe->gen_id()); \ data.set_flow_handle(fe->flow_handle()); \ data.set_refcount(fe->GetRefCount()); \ data.set_implicit_deny(fe->ImplicitDenyFlow() ? "yes" : "no"); \ data.set_short_flow( \ fe->is_flags_set(FlowEntry::ShortFlow) ? \ string("yes (") + fe->DropReasonStr(fe->short_flow_reason()) + \ ")": "no"); \ data.set_local_flow(fe->is_flags_set(FlowEntry::LocalFlow) ? "yes" : "no"); \ if (!fe->data().OriginVnSrcList().empty()) { \ data.set_src_vn_list(fe->data().OriginVnSrcList()); \ } else { \ data.set_src_vn_list(fe->data().SourceVnList()); \ } \ if (!fe->data().OriginVnDstList().empty()) { \ data.set_dst_vn_list(fe->data().OriginVnDstList()); \ } else { \ data.set_dst_vn_list(fe->data().DestinationVnList()); \ } \ if (!fe->data().origin_vn_src.empty()) { \ data.set_src_vn_match(fe->data().origin_vn_src); \ } else { \ data.set_src_vn_match(fe->data().source_vn_match); \ } \ if (!fe->data().origin_vn_dst.empty()) { \ data.set_dst_vn_match(fe->data().origin_vn_dst); \ } else { \ data.set_dst_vn_match(fe->data().dest_vn_match); \ } \ if (fe->is_flags_set(FlowEntry::EcmpFlow) && \ fe->data().component_nh_idx != CompositeNH::kInvalidComponentNHIdx) { \ data.set_ecmp_index(fe->data().component_nh_idx); \ } \ data.set_reverse_flow(fe->is_flags_set(FlowEntry::ReverseFlow) ? "yes" : "no"); \ Ip4Address fip(fe->fip()); \ data.set_fip(fip.to_string()); \ uint32_t fip_intf_id = fe->InterfaceKeyToId(agent, fe->fip_vmi()); \ data.set_fip_vm_interface_idx(fip_intf_id); \ SetAclInfo(data, fe); \ data.set_nh(fe->key().nh); \ if (fe->data().src_ip_nh.get() != NULL) { \ data.set_src_ip_nh(fe->data().src_ip_nh.get()->id()); \ } \ if (fe->data().rpf_nh.get() != NULL) { \ data.set_rpf_nh(fe->data().rpf_nh.get()->id()); \ } \ data.set_peer_vrouter(fe->peer_vrouter()); \ data.set_tunnel_type(fe->tunnel_type().ToString()); \ data.set_enable_rpf(fe->data().enable_rpf);\ if (fe->fsc()) {\ data.set_aging_protocol(fe->fsc()->flow_aging_key().proto);\ data.set_aging_port(fe->fsc()->flow_aging_key().port);\ }\ data.set_l3_flow(fe->l3_flow());\ uint16_t id = fe->flow_table()? fe->flow_table()->table_index() : 0xFFFF;\ data.set_table_id(id);\ data.set_deleted(fe->deleted());\ SandeshFlowIndexInfo flow_index_info;\ fe->SetEventSandeshData(&flow_index_info);\ data.set_flow_index_info(flow_index_info); \ data.set_fw_policy_match(fe->fw_policy_name_uuid()); \ FlowEntryInfo *mgmt_info = fe->flow_mgmt_info(); \ if (mgmt_info) {\ const FlowMgmtKeyTree &key_tree = mgmt_info->tree(); \ FlowMgmtKeyTree::const_iterator kt_it = key_tree.begin(); \ std::vector<SandeshInetRouteFlowMgmtEntryLink> key_list;\ while (kt_it != key_tree.end()) { \ InetRouteFlowMgmtKey *key = dynamic_cast<InetRouteFlowMgmtKey *> \ (kt_it->first);\ ++kt_it;\ if (!key) {\ continue;\ }\ if (id == 0xFFFF) {\ continue;\ }\ string key_str = InetRouteFlowMgmtKeyToString(id, key);\ SandeshInetRouteFlowMgmtEntryLink entry;\ entry.set_inet_route_flow_mgmt_key(key_str);\ key_list.push_back(entry);\ }\ data.set_inet_rt_keys(key_list);\ }\ data.set_local_tag_list(fe->local_tagset());\ data.set_remote_tag_list(fe->remote_tagset());\ data.set_remote_prefix(fe->RemotePrefix());\ const Interface *itfe = fe->intf_entry();\ if (itfe && (itfe->type() == Interface::VM_INTERFACE)) {\ const VmInterface *vmi_e = static_cast<const VmInterface *>(itfe);\ data.set_vmi(vmi_e->cfg_name());\ }\ data.set_underlay_gw_index(fe->data().underlay_gw_index_);\ const std::string PktSandeshFlow::start_key = "0-0-0-0-0-0.0.0.0-0.0.0.0"; //////////////////////////////////////////////////////////////////////////////// static void SetOneAclInfo(FlowAclInfo *policy, uint32_t action, const MatchAclParamsList &acl_list) { MatchAclParamsList::const_iterator it; std::vector<FlowAclUuid> acl; for (it = acl_list.begin(); it != acl_list.end(); it++) { FlowAclUuid f; f.uuid = UuidToString(it->acl->GetUuid()); acl.push_back(f); } policy->set_acl(acl); policy->set_action(action); std::vector<ActionStr> action_str_l; for (it = acl_list.begin(); it != acl_list.end(); it++) { FlowAction action_info = it->action_info; action_info.action = action; SetActionStr(action_info, action_str_l); } policy->set_action_str(action_str_l); } static void SetAclInfo(SandeshFlowData &data, FlowEntry *fe) { FlowAclInfo policy; SetOneAclInfo(&policy, fe->match_p().policy_action, fe->match_p().m_acl_l); data.set_policy(policy); SetOneAclInfo(&policy, fe->match_p().out_policy_action, fe->match_p().m_out_acl_l); data.set_out_policy(policy); SetOneAclInfo(&policy, fe->match_p().sg_policy.action, fe->match_p().sg_policy.m_acl_l); data.set_sg(policy); SetOneAclInfo(&policy, fe->match_p().sg_policy.out_action, fe->match_p().sg_policy.m_out_acl_l); data.set_out_sg(policy); SetOneAclInfo(&policy, fe->match_p().sg_policy.reverse_action, fe->match_p().sg_policy.m_reverse_acl_l); data.set_reverse_sg(policy); SetOneAclInfo(&policy, fe->match_p().sg_policy.reverse_out_action, fe->match_p().sg_policy.m_reverse_out_acl_l); data.set_reverse_out_sg(policy); SetOneAclInfo(&policy, fe->match_p().vrf_assign_acl_action, fe->match_p().m_vrf_assign_acl_l); data.set_vrf_assign_acl(policy); FlowAction action_info; action_info.action = fe->match_p().sg_policy.action_summary; std::vector<ActionStr> action_str_l; SetActionStr(action_info, action_str_l); data.set_sg_action_summary(action_str_l); SetOneAclInfo(&policy, fe->match_p().mirror_action, fe->match_p().m_mirror_acl_l); data.set_mirror(policy); SetOneAclInfo(&policy, fe->match_p().out_mirror_action, fe->match_p().m_out_mirror_acl_l); data.set_out_mirror(policy); SetOneAclInfo(&policy, fe->match_p().aps_policy.action, fe->match_p().aps_policy.m_acl_l); data.set_policy_set(policy); SetOneAclInfo(&policy, fe->match_p().aps_policy.out_action, fe->match_p().aps_policy.m_out_acl_l); data.set_out_policy_set(policy); SetOneAclInfo(&policy, fe->match_p().aps_policy.reverse_action, fe->match_p().aps_policy.m_reverse_acl_l); data.set_reverse_policy_set(policy); SetOneAclInfo(&policy, fe->match_p().aps_policy.reverse_out_action, fe->match_p().aps_policy.m_reverse_out_acl_l); data.set_reverse_out_policy_set(policy); action_info.action = fe->match_p().aps_policy.action_summary; action_str_l.clear(); SetActionStr(action_info, action_str_l); data.set_aps_action_summary(action_str_l); SetOneAclInfo(&policy, fe->match_p().fwaas_policy.action, fe->match_p().fwaas_policy.m_acl_l); data.set_fwaas_policy_set(policy); SetOneAclInfo(&policy, fe->match_p().fwaas_policy.out_action, fe->match_p().fwaas_policy.m_out_acl_l); data.set_fwaas_out_policy_set(policy); SetOneAclInfo(&policy, fe->match_p().fwaas_policy.reverse_action, fe->match_p().fwaas_policy.m_reverse_acl_l); data.set_fwaas_reverse_policy_set(policy); SetOneAclInfo(&policy, fe->match_p().fwaas_policy.reverse_out_action, fe->match_p().fwaas_policy.m_reverse_out_acl_l); data.set_fwaas_reverse_out_policy_set(policy); action_info.action = fe->match_p().fwaas_policy.action_summary; action_str_l.clear(); SetActionStr(action_info, action_str_l); data.set_fwaas_action_summary(action_str_l); data.set_sg_rule_uuid(fe->sg_rule_uuid()); data.set_nw_ace_uuid(fe->nw_ace_uuid()); } //////////////////////////////////////////////////////////////////////////////// PktSandeshFlow::PktSandeshFlow(Agent *agent, FlowRecordsResp *obj, std::string resp_ctx, std::string key): Task((TaskScheduler::GetInstance()->GetTaskId("Agent::PktFlowResponder")), 0), resp_obj_(obj), resp_data_(resp_ctx), flow_iteration_key_(), key_valid_(false), delete_op_(false), agent_(agent), partition_id_(0) { if (key != agent_->NullString()) { if (SetFlowKey(key)) { key_valid_ = true; } } } PktSandeshFlow::~PktSandeshFlow() { } void PktSandeshFlow::SetSandeshFlowData(std::vector<SandeshFlowData> &list, FlowEntry *fe, const FlowExportInfo *info) { SandeshFlowData data; SET_SANDESH_FLOW_DATA(agent_, data, fe, info); list.push_back(data); } void PktSandeshFlow::SendResponse(SandeshResponse *resp) { resp->set_context(resp_data_); resp->set_more(false); resp->Response(); } string PktSandeshFlow::GetFlowKey(const FlowKey &key, uint16_t partition_id) { std::stringstream ss; ss << partition_id << kDelimiter; ss << key.nh << kDelimiter; ss << key.src_port << kDelimiter; ss << key.dst_port << kDelimiter; ss << (uint16_t)key.protocol << kDelimiter; ss << key.src_addr.to_string() << kDelimiter; ss << key.dst_addr.to_string(); return ss.str(); } bool PktSandeshFlow::SetFlowKey(string key) { using std::istringstream; const char ch = kDelimiter; size_t n = std::count(key.begin(), key.end(), ch); if (n != 6) { return false; } std::stringstream ss(key); string item, sip, dip; uint32_t proto = 0; if (getline(ss, item, ch)) { istringstream(item) >> partition_id_; } if (getline(ss, item, ch)) { istringstream(item) >> flow_iteration_key_.nh; } if (getline(ss, item, ch)) { istringstream(item) >> flow_iteration_key_.src_port; } if (getline(ss, item, ch)) { istringstream(item) >> flow_iteration_key_.dst_port; } if (getline(ss, item, ch)) { istringstream(item) >> proto; } if (getline(ss, item, ch)) { sip = item; } if (getline(ss, item, ch)) { dip = item; } boost::system::error_code ec; flow_iteration_key_.src_addr = IpAddress::from_string(sip.c_str(), ec); flow_iteration_key_.dst_addr = IpAddress::from_string(dip.c_str(), ec); if (flow_iteration_key_.src_addr.is_v4()) { flow_iteration_key_.family = Address::INET; } else if (flow_iteration_key_.src_addr.is_v6()) { flow_iteration_key_.family = Address::INET6; } flow_iteration_key_.protocol = proto; return true; } bool PktSandeshFlow::Run() { FlowTable::FlowEntryMap::iterator it; std::vector<SandeshFlowData>& list = const_cast<std::vector<SandeshFlowData>&>(resp_obj_->get_flow_list()); int count = 0; bool flow_key_set = false; if (partition_id_ >= agent_->flow_thread_count()) { FlowErrorResp *resp = new FlowErrorResp(); SendResponse(resp); return true; } FlowTable *flow_obj = agent_->pkt()->flow_table(partition_id_); if (delete_op_) { for (int i =0; i < agent_->flow_thread_count(); i++){ flow_obj = agent_->pkt()->flow_table(i); flow_obj->DeleteAll(); } SendResponse(resp_obj_); return true; } if (key_valid_) { it = flow_obj->flow_entry_map_.upper_bound(flow_iteration_key_); } else { FlowErrorResp *resp = new FlowErrorResp(); SendResponse(resp); return true; } while (it == flow_obj->flow_entry_map_.end() && ++partition_id_ < agent_->flow_thread_count()) { flow_obj = agent_->pkt()->flow_table(partition_id_); it = flow_obj->flow_entry_map_.begin(); } while (it != flow_obj->flow_entry_map_.end()) { FlowEntry *fe = it->second; FlowStatsCollector *fec = fe->fsc(); const FlowExportInfo *info = NULL; if (fec) { info = fec->FindFlowExportInfo(fe); } SetSandeshFlowData(list, fe, info); ++it; count++; if (count == kMaxFlowResponse) { if (it != flow_obj->flow_entry_map_.end()) { resp_obj_->set_flow_key(GetFlowKey(fe->key(), partition_id_)); flow_key_set = true; } else { FlowKey key; resp_obj_->set_flow_key(GetFlowKey(key, ++partition_id_)); flow_key_set = true; } break; } while (it == flow_obj->flow_entry_map_.end()) { if (++partition_id_ < agent_->flow_thread_count()) { flow_obj = agent_->pkt()->flow_table(partition_id_); it = flow_obj->flow_entry_map_.begin(); if (it != flow_obj->flow_entry_map_.end()) { break; } } else { break; } } } if (!flow_key_set) { resp_obj_->set_flow_key(PktSandeshFlow::start_key); } SendResponse(resp_obj_); return true; } //////////////////////////////////////////////////////////////////////////////// void NextFlowRecordsSet::HandleRequest() const { Agent *agent = Agent::GetInstance(); FlowRecordsResp *resp = new FlowRecordsResp(); PktSandeshFlow *task = new PktSandeshFlow(agent, resp, context(), get_flow_key()); TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Enqueue(task); } void FetchAllFlowRecords::HandleRequest() const { Agent *agent = Agent::GetInstance(); FlowRecordsResp *resp = new FlowRecordsResp(); PktSandeshFlow *task = new PktSandeshFlow(agent, resp, context(), PktSandeshFlow::start_key); TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Enqueue(task); } void DeleteAllFlowRecords::HandleRequest() const { FlowRecordsResp *resp = new FlowRecordsResp(); PktSandeshFlow *task = new PktSandeshFlow(Agent::GetInstance(), resp, context(), PktSandeshFlow::start_key); task->set_delete_op(true); TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Enqueue(task); } void FetchFlowRecord::HandleRequest() const { FlowKey key; Agent *agent = Agent::GetInstance(); FlowTable *flow_obj = NULL; key.nh = get_nh(); boost::system::error_code ec; key.src_addr = IpAddress::from_string(get_sip(), ec); key.dst_addr = IpAddress::from_string(get_dip(), ec); if (key.src_addr.is_v4()) { key.family = Address::INET; } else if (key.src_addr.is_v6()) { key.family = Address::INET6; } key.src_port = (unsigned)get_src_port(); key.dst_port = (unsigned)get_dst_port(); key.protocol = get_protocol(); FlowTable::FlowEntryMap::iterator it; for (int i = 0; i < agent->flow_thread_count(); i++) { flow_obj = agent->pkt()->flow_table(i); it = flow_obj->flow_entry_map_.find(key); if (it != flow_obj->flow_entry_map_.end()) break; } SandeshResponse *resp; if (flow_obj && it != flow_obj->flow_entry_map_.end()) { FlowRecordResp *flow_resp = new FlowRecordResp(); FlowEntry *fe = it->second; FlowStatsCollector *fec = fe->fsc(); const FlowExportInfo *info = NULL; if (fec) { info = fec->FindFlowExportInfo(fe); } SandeshFlowData data; SET_SANDESH_FLOW_DATA(agent, data, fe, info); flow_resp->set_record(data); resp = flow_resp; } else { resp = new FlowErrorResp(); } resp->set_context(context()); resp->set_more(false); resp->Response(); } // Sandesh interface to modify flow aging interval // Intended for use in testing only void FlowAgeTimeReq::HandleRequest() const { Agent *agent = Agent::GetInstance(); uint32_t age_time = get_new_age_time(); FlowStatsCollectorObject *obj = agent->flow_stats_manager()->default_flow_stats_collector_obj(); FlowAgeTimeResp *resp = new FlowAgeTimeResp(); if (obj == NULL) { goto done; } resp->set_old_age_time(obj->GetAgeTimeInSeconds()); if (age_time && age_time != resp->get_old_age_time()) { obj->UpdateAgeTimeInSeconds(age_time); resp->set_new_age_time(age_time); } else { resp->set_new_age_time(resp->get_old_age_time()); } done: resp->set_context(context()); resp->set_more(false); resp->Response(); } void FetchLinkLocalFlowInfo::HandleRequest() const { LinkLocalFlowInfoResp *resp = new LinkLocalFlowInfoResp(); std::vector<LinkLocalFlowInfo> &list = const_cast<std::vector<LinkLocalFlowInfo>&> (resp->get_linklocal_flow_list()); const FlowTable::LinkLocalFlowInfoMap &flow_map = Agent::GetInstance()->pkt()->flow_table(0)->linklocal_flow_info_map(); FlowTable::LinkLocalFlowInfoMap::const_iterator it = flow_map.begin(); while (it != flow_map.end()) { LinkLocalFlowInfo info; info.fd = it->first; info.flow_index = it->second.flow_index; info.source_addr = it->second.flow_key.src_addr.to_string(); info.dest_addr = it->second.flow_key.dst_addr.to_string(); info.protocol = it->second.flow_key.protocol; info.source_port = it->second.flow_key.src_port; info.dest_port = it->second.flow_key.dst_port; info.timestamp = integerToString(UTCUsecToPTime(it->second.timestamp)); list.push_back(info); ++it; } resp->set_context(context()); resp->set_more(false); resp->Response(); } bool PktSandeshFlowStats::Run() { std::vector<SandeshFlowData>& list = const_cast<std::vector<SandeshFlowData>&>(resp_->get_flow_list()); int count = 0; bool flow_key_set = false; if (partition_id_ > agent_->flow_thread_count()) { FlowErrorResp *resp = new FlowErrorResp(); SendResponse(resp); return true; } FlowTable *flow_obj = agent_->pkt()->flow_table(partition_id_); FlowStatsManager *fm = agent_->flow_stats_manager(); const FlowStatsCollectorObject *fsc_obj = fm->Find(proto_, port_); if (!fsc_obj) { FlowErrorResp *resp = new FlowErrorResp(); SendResponse(resp); return true; } FlowTable::FlowEntryMap::iterator it; if (key_valid_) { it = flow_obj->flow_entry_map_.upper_bound(flow_iteration_key_); } else { FlowErrorResp *resp = new FlowErrorResp(); SendResponse(resp); return true; } while (it == flow_obj->flow_entry_map_.end() && ++partition_id_ < agent_->flow_thread_count()) { flow_obj = agent_->pkt()->flow_table(partition_id_); it = flow_obj->flow_entry_map_.begin(); } while (it != flow_obj->flow_entry_map_.end()) { FlowEntry *fe = it->second; const FlowExportInfo *info = NULL; if (fe->fsc()) { info = fe->fsc()->FindFlowExportInfo(fe); } SetSandeshFlowData(list, fe, info); ++it; count++; if (count == kMaxFlowResponse) { if (it != flow_obj->flow_entry_map_.end()) { std::ostringstream ostr; ostr << proto_ << ":" << port_ << ":" << GetFlowKey(fe->key(), partition_id_); resp_->set_flow_key(ostr.str()); flow_key_set = true; } else { std::ostringstream ostr; FlowKey key; ostr << proto_ << ":" << port_ << ":" << GetFlowKey(key, ++partition_id_); resp_->set_flow_key(ostr.str()); flow_key_set = true; } break; } while (it == flow_obj->flow_entry_map_.end()) { if (++partition_id_ < agent_->flow_thread_count()) { flow_obj = agent_->pkt()->flow_table(partition_id_); it = flow_obj->flow_entry_map_.begin(); if (it != flow_obj->flow_entry_map_.end()) { break; } } else { break; } } } if (!flow_key_set) { std::ostringstream ostr; ostr << proto_ << ":" << port_ << ":" <<PktSandeshFlow::start_key; resp_->set_flow_key(ostr.str()); } SendResponse(resp_); return true; } bool PktSandeshFlowStats::SetProto(string &key) { size_t n = std::count(key.begin(), key.end(), ':'); if (n != 2) { return false; } std::stringstream ss(key); string item; if (getline(ss, item, ':')) { std::istringstream(item) >> proto_; } if (getline(ss, item, ':')) { std::istringstream(item) >> port_; } if (getline(ss, item)) { SetFlowKey(item); } return true; } PktSandeshFlowStats::PktSandeshFlowStats(Agent *agent, FlowStatsCollectorRecordsResp *obj, std::string resp_ctx, std::string key): PktSandeshFlow(agent, NULL, resp_ctx, key), resp_(obj) { if (key != agent_->NullString()) { if (SetProto(key)) { key_valid_ = true; } } } void ShowFlowStatsCollector::HandleRequest() const { Agent *agent = Agent::GetInstance(); FlowStatsCollectorRecordsResp *resp = new FlowStatsCollectorRecordsResp(); std::ostringstream ostr; ostr << get_protocol() << ":" << get_port() << ":" << PktSandeshFlow::start_key; PktSandeshFlowStats *task = new PktSandeshFlowStats(agent, resp, context(), ostr.str()); TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Enqueue(task); } void NextFlowStatsRecordsSet::HandleRequest() const { Agent *agent = Agent::GetInstance(); FlowStatsCollectorRecordsResp *resp = new FlowStatsCollectorRecordsResp(); PktSandeshFlow *task = new PktSandeshFlowStats(agent, resp, context(), get_flow_key()); TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Enqueue(task); } void SandeshFlowTableInfoRequest::HandleRequest() const { Agent *agent = Agent::GetInstance(); FlowProto *proto = agent->pkt()->get_flow_proto(); SandeshFlowTableInfoResp *resp = new SandeshFlowTableInfoResp(); resp->set_flow_count(proto->FlowCount()); resp->set_total_added(agent->stats()->flow_created()); resp->set_max_flows(agent->stats()->max_flow_count()); resp->set_total_deleted(agent->stats()->flow_aged()); std::vector<SandeshFlowTableInfo> info_list; for (uint16_t i = 0; i < proto->flow_table_count(); i++) { FlowTable *table = proto->GetTable(i); SandeshFlowTableInfo info; info.set_index(table->table_index()); info.set_count(table->Size()); info.set_total_add(table->free_list()->total_alloc()); info.set_total_del(table->free_list()->total_free()); info.set_freelist_count(table->free_list()->free_count()); info_list.push_back(info); } resp->set_table_list(info_list); resp->set_context(context()); resp->set_more(false); resp->Response(); } //////////////////////////////////////////////////////////////////////////////// static InetRouteFlowMgmtKey* StringToInetRouteFlowMgmtKey(const string &key, uint16_t *id) { using std::istringstream; Agent *agent = Agent::GetInstance(); const char ch = PktSandeshFlow::kDelimiter; size_t n = std::count(key.begin(), key.end(), ch); if (n != 3) { return NULL; } std::stringstream ss(key); string item, ip_str; uint32_t vrf_id = 0; uint16_t plen = 0, mgr_id = 0; if (getline(ss, item, ch)) { istringstream(item) >> mgr_id; } if (mgr_id >= agent->pkt()->flow_mgmt_manager_list().size()) { return NULL; } *id = mgr_id; if (getline(ss, item, ch)) { istringstream(item) >> vrf_id; } if (getline(ss, item, ch)) { ip_str = item; } if (getline(ss, item, ch)) { istringstream(item) >> plen; } boost::system::error_code ec; IpAddress ip = IpAddress::from_string(ip_str.c_str(), ec); if (ec) { return NULL; } InetRouteFlowMgmtKey* ret = new InetRouteFlowMgmtKey(vrf_id, ip, plen); return ret; } void FlowsPerInetRouteFlowMgmtKeyReq::HandleRequest() const { FlowsPerInetRouteFlowMgmtKeyResp *resp= new FlowsPerInetRouteFlowMgmtKeyResp(); resp->set_context(context()); resp->set_more(false); std::vector<SandeshFlowData> &resp_list = const_cast<std::vector<SandeshFlowData>&>(resp->get_flow_list()); Agent *agent = Agent::GetInstance(); uint16_t mgr_id = 0; FlowMgmtManager *mgr = NULL; InetRouteFlowMgmtKey *ikey = StringToInetRouteFlowMgmtKey(get_key(), &mgr_id); if (!ikey) { resp->Response(); return; } mgr = agent->pkt()->flow_mgmt_manager(mgr_id); InetRouteFlowMgmtTree* tree = mgr->ip4_route_flow_mgmt_tree(); FlowMgmtEntry *entry = tree->Find(ikey); delete ikey; if (!entry) { resp->Response(); return; } if (entry->Size() == 0) { resp->Response(); return; } const FlowMgmtEntry::FlowList &flow_list = entry->flow_list(); FlowMgmtEntry::FlowList::const_iterator it = flow_list.begin(); while (it != flow_list.end()) { const FlowMgmtKeyNode *node = &(*it); FlowEntry *fe = node->flow_entry(); SandeshFlowData data; const FlowExportInfo *info = NULL; SET_SANDESH_FLOW_DATA(agent, data, fe, info); resp_list.push_back(data); it++; } resp->Response(); } void Inet4FlowTreeReq::HandleRequest() const { Agent *agent = Agent::GetInstance(); std::vector<FlowMgmtManager *>::const_iterator it = agent->pkt()->flow_mgmt_manager_iterator_begin(); Inet4FlowTreeResponse *resp = new Inet4FlowTreeResponse(); std::vector<SandeshInetRouteFlowMgmtEntryLink> &resp_list = const_cast<std::vector<SandeshInetRouteFlowMgmtEntryLink>&> (resp->get_keys()); uint16_t mgr_idx = 0; while (it != agent->pkt()->flow_mgmt_manager_iterator_end()) { FlowMgmtManager *mgr = *it; it++; InetRouteFlowMgmtTree* tree = mgr->ip4_route_flow_mgmt_tree(); FlowMgmtTree::Tree &list = tree->tree(); FlowMgmtTree::Tree::iterator tree_it = list.begin(); while(tree_it != list.end()) { InetRouteFlowMgmtKey *key = static_cast<InetRouteFlowMgmtKey *> (tree_it->first); string key_str = InetRouteFlowMgmtKeyToString(mgr_idx, key); SandeshInetRouteFlowMgmtEntryLink entry; entry.set_inet_route_flow_mgmt_key(key_str); resp_list.push_back(entry); ++tree_it; } ++mgr_idx; } resp->set_context(context()); resp->set_more(false); resp->Response(); } void SNatPortConfigRequest::HandleRequest() const { Agent *agent = Agent::GetInstance(); PortTableManager *pm = agent->pkt()->get_flow_proto()->port_table_manager(); SNatPortResponse *resp = new SNatPortResponse(); std::vector<PortConfigData> &config_list = const_cast<std::vector<PortConfigData>&>(resp->get_port_config_list()); for(uint16_t protocol = 0; protocol < IPPROTO_MAX; protocol++) { const PortTable *pt = pm->GetPortTable(protocol); if (pt == NULL) { continue; } const PortConfig *pc = pt->port_config(); //Only count specified PortConfigData spc; spc.port_count = pc->port_count; spc.protocol = protocol; std::vector<PortConfig::PortRange>::const_iterator it = pc->port_range.begin(); for(;it != pc->port_range.end(); it++) { PortConfigRange pcr; pcr.port_start = it->port_start; pcr.port_end = it->port_end; spc.port_range.push_back(pcr); } spc.set_bound_port_list((pt->GetPortList())); config_list.push_back(spc); } resp->set_context(context()); resp->set_more(false); resp->Response(); } static void HandlePortFlowReq(uint16_t protocol, uint16_t port, bool match_proto, bool match_port, std::string context) { Agent *agent = Agent::GetInstance(); PortTableManager *pm = agent->pkt()->get_flow_proto()->port_table_manager(); SNatPortFlowResponse *resp = new SNatPortFlowResponse(); std::vector<SNatPortFlow> &list = const_cast<std::vector<SNatPortFlow>&>(resp->get_port_flow_list()); uint16_t flow_count = 0; uint16_t next_port = 0; uint16_t proto = 0; for(; proto < IPPROTO_MAX; proto++) { const PortTable *pt = pm->GetPortTable(proto); next_port = 0; if (match_proto && proto != protocol) { continue; } if (proto < protocol) { continue; } if (pt == NULL) { continue; } std::vector<uint16_t> ports = pt->GetPortList(); std::vector<uint16_t>::const_iterator it = ports.begin(); for(; it != ports.end(); it++) { if (match_port && port != *it) { continue; } if (match_port && port > *it) { break; } if (port > *it) { continue; } std::vector<FlowKey> flow_list; pt->GetFlowKeyList(*it, flow_list); flow_count += flow_list.size(); SNatPortFlow snf; snf.port = *it; snf.protocol = proto; std::vector<FlowKey>::iterator flow_it = flow_list.begin(); for (; flow_it != flow_list.end(); flow_it++) { SNatFlowKey flow_key; flow_key.nh = flow_it->nh; flow_key.sip = flow_it->src_addr.to_string(); flow_key.dip = flow_it->dst_addr.to_string(); flow_key.src_port = flow_it->src_port; flow_key.dst_port = flow_it->dst_port; flow_key.protocol = flow_it->protocol; snf.flows.push_back(flow_key); } list.push_back(snf); if (flow_count >= 1) { break; } } if (it != ports.end() && match_port == false) { next_port = *it + 1; } if (match_port == false) { port = 0; } if (flow_count >= 1) { break; } } bool next = true; if (match_proto && next_port == 0) { next = false; } if (proto == IPPROTO_MAX) { next = false; } if (next) { std::stringstream str; str << proto << ":" << next_port << ":" << match_proto << ":" << match_port; resp->set_flow_key(str.str()); } resp->set_context(context); resp->set_more(false); resp->Response(); } void SNatPerPortFlowList::HandleRequest() const { bool match_proto = false; if (protocol != 0) { match_proto = true; } bool match_port = false; if (port != 0) { match_port = true; } HandlePortFlowReq(protocol, port, match_proto, match_port, context()); } void NextPerPortFlowList::HandleRequest() const { using std::istringstream; uint16_t proto = 0; uint16_t port = 0; bool match_proto = false; bool match_port = false; std::string colon; std::stringstream ss(port_key); string item; const char ch = ':'; size_t n = std::count(port_key.begin(), port_key.end(), ch); if (n != 3) { goto fail; } if (getline(ss, item, ch)) { istringstream(item) >> proto; } if (getline(ss, item, ch)) { istringstream(item) >> port; } if (getline(ss, item, ch)) { istringstream(item) >> match_proto; } if (getline(ss, item, ch)) { istringstream(item) >> match_port; } HandlePortFlowReq(proto, port, match_proto, match_port, context()); fail: FlowErrorResp *resp = new FlowErrorResp(); resp->set_context(context()); resp->set_more(false); resp->Response(); }
36.793201
92
0.548763
[ "vector" ]
a368af86a3da6cf90e2d12b975fe156e45d98fe6
9,221
cc
C++
paddle/fluid/operators/layer_norm_op_mlu.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/fluid/operators/layer_norm_op_mlu.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
null
null
null
paddle/fluid/operators/layer_norm_op_mlu.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
1
2021-09-24T11:23:36.000Z
2021-09-24T11:23:36.000Z
/* Copyright (c) 2022 PaddlePaddle 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 "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/mlu/mlu_baseop.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; using DDim = framework::DDim; template <typename T> class LayerNormMLUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { const auto begin_norm_axis = ctx.Attr<int>("begin_norm_axis"); const auto epsilon = ctx.Attr<float>("epsilon"); const auto* x = ctx.Input<Tensor>("X"); const auto* scale = ctx.Input<Tensor>("Scale"); const auto* bias = ctx.Input<Tensor>("Bias"); auto* y = ctx.Output<Tensor>("Y"); auto* mean = ctx.Output<Tensor>("Mean"); auto* variance = ctx.Output<Tensor>("Variance"); auto place = ctx.GetPlace(); y->mutable_data<T>(place); mean->mutable_data<T>(place); variance->mutable_data<T>(place); const auto& x_dims = x->dims(); std::vector<int> scale_bias_axes; std::vector<int> mean_var_axes; for (auto i = 0; i < x_dims.size(); ++i) { if (i >= begin_norm_axis) { scale_bias_axes.push_back(x_dims[i]); } else { mean_var_axes.push_back(x_dims[i]); } } MLUCnnlTensorDesc x_desc(*x); MLUCnnlTensorDesc y_desc(*y); MLUCnnlTensorDesc mean_var_desc(mean_var_axes.size(), mean_var_axes.data(), ToCnnlDataType<T>()); // cnnl only support both of scale and bias is NULL or not. if (!scale && !bias) { MLUCnnl::LayerNormForward( ctx, begin_norm_axis, x_desc.get(), GetBasePtr(x), nullptr /*scale_bias_desc*/, nullptr /*scale*/, nullptr /*bias*/, epsilon, y_desc.get(), GetBasePtr(y), mean_var_desc.get(), GetBasePtr(mean), GetBasePtr(variance)); } else { Tensor tmp_scale(x->dtype()); if (!scale) { tmp_scale.mutable_data<T>(phi::make_ddim(scale_bias_axes), place); FillMLUTensorWithHostValue(ctx, static_cast<T>(1), &tmp_scale); } else { tmp_scale = *scale; } Tensor tmp_bias(x->dtype()); if (!bias) { tmp_bias.mutable_data<T>(phi::make_ddim(scale_bias_axes), place); FillMLUTensorWithHostValue(ctx, static_cast<T>(0), &tmp_bias); } else { tmp_bias = *bias; } // scale and bias should have same type with x/y MLUCnnlTensorDesc float32_desc(scale_bias_axes.size(), scale_bias_axes.data(), CNNL_DTYPE_FLOAT); MLUCnnlTensorDesc float16_desc(scale_bias_axes.size(), scale_bias_axes.data(), CNNL_DTYPE_HALF); cnnlCastDataType_t cast_type = GetCastDataType(VT::FP32, VT::FP16); Tensor final_scale(x->dtype()); if (final_scale.dtype() == DataType::FLOAT16 && tmp_scale.dtype() == DataType::FLOAT32) { final_scale.mutable_data<T>(phi::make_ddim(scale_bias_axes), place); // cast scale to fp16 MLUCnnl::Cast(ctx, cast_type, float32_desc.get(), GetBasePtr(&tmp_scale), float16_desc.get(), GetBasePtr(&final_scale)); } else { final_scale = tmp_scale; } Tensor final_bias(x->dtype()); if (final_bias.dtype() == DataType::FLOAT16 && tmp_bias.dtype() == DataType::FLOAT32) { final_bias.mutable_data<T>(phi::make_ddim(scale_bias_axes), place); // cast bias to fp16 MLUCnnl::Cast(ctx, cast_type, float32_desc.get(), GetBasePtr(&tmp_bias), float16_desc.get(), GetBasePtr(&final_bias)); } else { final_bias = tmp_bias; } MLUCnnlTensorDesc scale_bias_desc( scale_bias_axes.size(), scale_bias_axes.data(), ToCnnlDataType<T>()); MLUCnnl::LayerNormForward( ctx, begin_norm_axis, x_desc.get(), GetBasePtr(x), scale_bias_desc.get(), GetBasePtr(&final_scale), GetBasePtr(&final_bias), epsilon, y_desc.get(), GetBasePtr(y), mean_var_desc.get(), GetBasePtr(mean), GetBasePtr(variance)); } } }; template <typename T> class LayerNormGradMLUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { const auto begin_norm_axis = ctx.Attr<int>("begin_norm_axis"); const auto* x = ctx.Input<Tensor>("X"); const auto* mean = ctx.Input<Tensor>("Mean"); const auto* variance = ctx.Input<Tensor>("Variance"); const auto* scale = ctx.Input<Tensor>("Scale"); const auto* dy = ctx.Input<Tensor>(framework::GradVarName("Y")); auto* dx = ctx.Output<Tensor>(framework::GradVarName("X")); auto* dscale = ctx.Output<Tensor>(framework::GradVarName("Scale")); auto* dbias = ctx.Output<Tensor>(framework::GradVarName("Bias")); auto place = ctx.GetPlace(); dx->mutable_data<T>(place); const auto& x_dims = x->dims(); std::vector<int> scale_bias_axes; std::vector<int> mean_var_axes; for (auto i = 0; i < x_dims.size(); ++i) { if (i >= begin_norm_axis) { scale_bias_axes.push_back(x_dims[i]); } else { mean_var_axes.push_back(x_dims[i]); } } MLUCnnlTensorDesc x_desc(*x); MLUCnnlTensorDesc dy_desc(*dy); MLUCnnlTensorDesc mean_var_desc(mean_var_axes.size(), mean_var_axes.data(), ToCnnlDataType<T>()); MLUCnnlTensorDesc dx_desc(*dx); Tensor tmp_scale(x->dtype()); if (!scale) { tmp_scale.mutable_data<T>(phi::make_ddim(scale_bias_axes), place); FillMLUTensorWithHostValue(ctx, static_cast<T>(1), &tmp_scale); } else { tmp_scale = *scale; } MLUCnnlTensorDesc float32_desc(scale_bias_axes.size(), scale_bias_axes.data(), CNNL_DTYPE_FLOAT); MLUCnnlTensorDesc float16_desc(scale_bias_axes.size(), scale_bias_axes.data(), CNNL_DTYPE_HALF); cnnlCastDataType_t cast_fp32_to_fp16 = GetCastDataType(VT::FP32, VT::FP16); cnnlCastDataType_t cast_fp16_to_fp32 = GetCastDataType(VT::FP16, VT::FP32); Tensor final_scale(x->dtype()); if (final_scale.dtype() == DataType::FLOAT16 && tmp_scale.dtype() == DataType::FLOAT32) { final_scale.mutable_data<T>(phi::make_ddim(scale_bias_axes), place); // cast scale to fp16 MLUCnnl::Cast(ctx, cast_fp32_to_fp16, float32_desc.get(), GetBasePtr(&tmp_scale), float16_desc.get(), GetBasePtr(&final_scale)); } else { final_scale = tmp_scale; } Tensor tmp_dscale(x->dtype()); if (dscale && (tmp_dscale.dtype() == dscale->dtype())) { dscale->mutable_data<T>(place); tmp_dscale = *dscale; } else { tmp_dscale.mutable_data<T>(phi::make_ddim(scale_bias_axes), place); } Tensor tmp_dbias(x->dtype()); if (dbias && (tmp_dbias.dtype() == dbias->dtype())) { dbias->mutable_data<T>(place); tmp_dbias = *dbias; } else { tmp_dbias.mutable_data<T>(phi::make_ddim(scale_bias_axes), place); } MLUCnnlTensorDesc scale_desc(scale_bias_axes.size(), scale_bias_axes.data(), ToCnnlDataType<T>()); MLUCnnl::LayerNormBackward( ctx, begin_norm_axis, x_desc.get(), GetBasePtr(x), dy_desc.get(), GetBasePtr(dy), scale_desc.get(), GetBasePtr(&final_scale), mean_var_desc.get(), GetBasePtr(mean), GetBasePtr(variance), dx_desc.get(), GetBasePtr(dx), GetBasePtr(&tmp_dscale), GetBasePtr(&tmp_dbias)); if (dscale && (tmp_dscale.dtype() == DataType::FLOAT16 && dscale->dtype() == DataType::FLOAT32)) { dscale->mutable_data<T>(place); MLUCnnl::Cast(ctx, cast_fp16_to_fp32, float16_desc.get(), GetBasePtr(&tmp_dscale), float32_desc.get(), GetBasePtr(dscale)); } if (dbias && (tmp_dbias.dtype() == DataType::FLOAT16 && dbias->dtype() == DataType::FLOAT32)) { dbias->mutable_data<T>(place); MLUCnnl::Cast(ctx, cast_fp16_to_fp32, float16_desc.get(), GetBasePtr(&tmp_dbias), float32_desc.get(), GetBasePtr(dbias)); } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; namespace plat = paddle::platform; REGISTER_OP_MLU_KERNEL(layer_norm, ops::LayerNormMLUKernel<float>, ops::LayerNormMLUKernel<plat::float16>); REGISTER_OP_MLU_KERNEL(layer_norm_grad, ops::LayerNormGradMLUKernel<float>, ops::LayerNormGradMLUKernel<plat::float16>);
39.238298
80
0.633879
[ "vector" ]
a369afc311b1d8a73a2fde08b04ebc6746bfb1c6
1,788
cpp
C++
Surface_mesh_segmentation/test/Surface_mesh_segmentation/K_means_clustering_test_2.cpp
brucerennie/cgal
314b94aafa9b08a1d086accd2cadff1aae1b57a9
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Surface_mesh_segmentation/test/Surface_mesh_segmentation/K_means_clustering_test_2.cpp
brucerennie/cgal
314b94aafa9b08a1d086accd2cadff1aae1b57a9
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Surface_mesh_segmentation/test/Surface_mesh_segmentation/K_means_clustering_test_2.cpp
brucerennie/cgal
314b94aafa9b08a1d086accd2cadff1aae1b57a9
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
#include <iostream> #include <string> #include <CGAL/Surface_mesh_segmentation/internal/K_means_clustering.h> typedef CGAL::internal::K_means_clustering K_means; /** * Test where number of points equal to number of centers, * Specifically useful for testing random and plus initializations (i.e. Selector class) */ int main(void) { for(std::size_t init_type = 0; init_type < 2; ++init_type) { K_means::Initialization_types init_type_enum = init_type == 0 ? K_means::RANDOM_INITIALIZATION : K_means::PLUS_INITIALIZATION; // Test case: number of points equals to number of clusters // and all points are unique for(std::size_t center_size = 1; center_size < 100; ++center_size) { // unique point generate std::vector<double> points; for(std::size_t i = 0; i < center_size; ++i) { points.push_back(static_cast<double>(i)); } // test kmeans, expected result: each point has its own cluster K_means kmeans(center_size, points, init_type_enum); std::vector<std::size_t> center_ids; kmeans.fill_with_center_ids(center_ids); for(std::size_t i = 0; i < center_size -1; ++i) { if(center_ids[i] >= center_ids[i +1]) // center ids are ordered according to mean { // and since points are generated ascendingly ... std::string init_type_s = init_type_enum == K_means::RANDOM_INITIALIZATION ? "Random " : "Plus plus "; std::cerr << "Init type: " << init_type_s << "center size: " << center_size << std::endl; CGAL_assertion(false); } } } } }
41.581395
100
0.589485
[ "vector" ]
a36b56b8850dfaec88f36bd199f590a6434f2060
3,966
hpp
C++
components/document/document.hpp
cyberduckninja/RocketJoe
f0cfb51850423c218c3630f7a664afb48b2b8319
[ "BSD-3-Clause" ]
9
2020-07-20T15:32:07.000Z
2021-06-04T13:02:58.000Z
components/document/document.hpp
cyberduckninja/RocketJoe
f0cfb51850423c218c3630f7a664afb48b2b8319
[ "BSD-3-Clause" ]
22
2020-06-06T07:27:00.000Z
2021-01-14T23:11:22.000Z
components/document/document.hpp
cyberduckninja/RocketJoe
f0cfb51850423c218c3630f7a664afb48b2b8319
[ "BSD-3-Clause" ]
3
2020-08-29T07:07:49.000Z
2021-06-04T13:02:59.000Z
#pragma once #include <memory> #include <string> #include <msgpack.hpp> #include "support/ref_counted.hpp" #include "document/mutable/mutable_array.h" namespace document::impl { class mutable_dict_t; class dict_t; class dict_iterator_t; } namespace components::document { class document_t final { using storage_t = ::document::impl::mutable_dict_t*; using const_storage_t = const ::document::impl::dict_t*; using iterator = ::document::impl::dict_iterator_t; public: using value_t = const ::document::impl::value_t*; document_t(); explicit document_t(const ::document::impl::dict_t *dict, bool is_owner = false); document_t(const document_t &src); document_t(document_t &&src); ~document_t(); void add_null(const std::string &key); void add_bool(const std::string &key, bool value); void add_ulong(const std::string &key, ulong value); void add_long(const std::string &key, long value); void add_double(const std::string &key, double value); void add_string(const std::string &key, std::string value); void add_array(const std::string &key, ::document::impl::array_t *array); void add_dict(const std::string &key, ::document::impl::dict_t *dict); void add_dict(const std::string &key, const document_t &dict); void add_dict(const std::string &key, document_t &&dict); bool is_exists(const std::string &key) const; bool is_null(const std::string &key) const; bool is_bool(const std::string &key) const; bool is_ulong(const std::string &key) const; bool is_long(const std::string &key) const; bool is_double(const std::string &key) const; bool is_string(const std::string &key) const; bool is_array(const std::string &key) const; bool is_dict(const std::string &key) const; const ::document::impl::value_t *get(const std::string &key) const; bool get_bool(const std::string &key) const; ulong get_ulong(const std::string &key) const; long get_long(const std::string &key) const; double get_double(const std::string &key) const; std::string get_string(const std::string &key) const; const ::document::impl::array_t *get_array(const std::string &key) const; document_t get_dict(const std::string &key) const; const_storage_t get_storage() const; template <class T> T get_as(const std::string &) const; ::document::retained_const_t<::document::impl::value_t> value() const; iterator begin() const; std::string to_json() const; static document_t from_json(const std::string &json); static ::document::retained_t<::document::impl::mutable_array_t> create_array(); static msgpack::type::object_type get_msgpack_type(const ::document::impl::value_t *value); static msgpack::object get_msgpack_object(const ::document::impl::value_t *value); private: storage_t storage_; bool is_owner_; }; template <class T> T document_t::get_as(const std::string &) const { static_assert(true, "not supported"); return T(); } template<> inline bool document_t::get_as<bool>(const std::string &key) const { return get_bool(key); } template<> inline ulong document_t::get_as<ulong>(const std::string &key) const { return get_ulong(key); } template<> inline long document_t::get_as<long>(const std::string &key) const { return get_long(key); } template<> inline double document_t::get_as<double>(const std::string &key) const { return get_double(key); } template<> inline std::string document_t::get_as<std::string>(const std::string &key) const { return get_string(key); } template<> inline const ::document::impl::array_t *document_t::get_as<const ::document::impl::array_t *>(const std::string &key) const { return get_array(key); } template<> inline document_t document_t::get_as<document_t>(const std::string &key) const { return get_dict(key); } using document_ptr = std::unique_ptr<document_t>; auto make_document() -> document_ptr; }
32.77686
136
0.707514
[ "object" ]
a36b69c4d7c7896d9235fb586cfa80f4b03a3f1b
8,146
cpp
C++
editor/import_defaults_editor.cpp
goblinengine/godot
af8a02ddafd64f0195956c74c6a60bf389af278f
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
editor/import_defaults_editor.cpp
goblinengine/godot
af8a02ddafd64f0195956c74c6a60bf389af278f
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
editor/import_defaults_editor.cpp
goblinengine/godot
af8a02ddafd64f0195956c74c6a60bf389af278f
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
/*************************************************************************/ /* import_defaults_editor.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "import_defaults_editor.h" class ImportDefaultsEditorSettings : public Object { GDCLASS(ImportDefaultsEditorSettings, Object) friend class ImportDefaultsEditor; List<PropertyInfo> properties; Map<StringName, Variant> values; Map<StringName, Variant> default_values; Ref<ResourceImporter> importer; protected: bool _set(const StringName &p_name, const Variant &p_value) { if (values.has(p_name)) { values[p_name] = p_value; return true; } else { return false; } } bool _get(const StringName &p_name, Variant &r_ret) const { if (values.has(p_name)) { r_ret = values[p_name]; return true; } else { r_ret = Variant(); return false; } } void _get_property_list(List<PropertyInfo> *p_list) const { if (importer.is_null()) { return; } for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { if (importer->get_option_visibility(E->get().name, values)) { p_list->push_back(E->get()); } } } }; void ImportDefaultsEditor::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { inspector->set_property_name_style(EditorPropertyNameProcessor::get_settings_style()); } break; case NOTIFICATION_PREDELETE: { inspector->edit(nullptr); } break; } } void ImportDefaultsEditor::_reset() { if (settings->importer.is_valid()) { settings->values = settings->default_values; settings->_change_notify(); } } void ImportDefaultsEditor::_save() { if (settings->importer.is_valid()) { Dictionary modified; for (Map<StringName, Variant>::Element *E = settings->values.front(); E; E = E->next()) { if (E->get() != settings->default_values[E->key()]) { modified[E->key()] = E->get(); } } if (modified.size()) { ProjectSettings::get_singleton()->set("importer_defaults/" + settings->importer->get_importer_name(), modified); } else { ProjectSettings::get_singleton()->set("importer_defaults/" + settings->importer->get_importer_name(), Variant()); } // Calling ProjectSettings::set() causes the signal "project_settings_changed" to be sent to ProjectSettings. // ProjectSettingsEditor subscribes to this and can reads the settings updated here. } } void ImportDefaultsEditor::_update_importer() { List<Ref<ResourceImporter>> importer_list; ResourceFormatImporter::get_singleton()->get_importers(&importer_list); Ref<ResourceImporter> importer; for (List<Ref<ResourceImporter>>::Element *E = importer_list.front(); E; E = E->next()) { if (E->get()->get_visible_name() == importers->get_item_text(importers->get_selected())) { importer = E->get(); break; } } settings->properties.clear(); settings->values.clear(); settings->importer = importer; if (importer.is_valid()) { List<ResourceImporter::ImportOption> options; importer->get_import_options(&options); Dictionary d; if (ProjectSettings::get_singleton()->has_setting("importer_defaults/" + importer->get_importer_name())) { d = ProjectSettings::get_singleton()->get("importer_defaults/" + importer->get_importer_name()); } for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) { settings->properties.push_back(E->get().option); if (d.has(E->get().option.name)) { settings->values[E->get().option.name] = d[E->get().option.name]; } else { settings->values[E->get().option.name] = E->get().default_value; } settings->default_values[E->get().option.name] = E->get().default_value; } save_defaults->set_disabled(false); reset_defaults->set_disabled(false); } else { save_defaults->set_disabled(true); reset_defaults->set_disabled(true); } settings->_change_notify(); inspector->edit(settings); } void ImportDefaultsEditor::_importer_selected(int p_index) { _update_importer(); } void ImportDefaultsEditor::clear() { String last_selected; if (importers->get_selected() > 0) { last_selected = importers->get_item_text(importers->get_selected()); } importers->clear(); importers->add_item("<" + TTR("Select Importer") + ">"); importers->set_item_disabled(0, true); List<Ref<ResourceImporter>> importer_list; ResourceFormatImporter::get_singleton()->get_importers(&importer_list); Vector<String> names; for (List<Ref<ResourceImporter>>::Element *E = importer_list.front(); E; E = E->next()) { String vn = E->get()->get_visible_name(); names.push_back(vn); } names.sort(); for (int i = 0; i < names.size(); i++) { importers->add_item(names[i]); if (names[i] == last_selected) { importers->select(i + 1); } } } void ImportDefaultsEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_reset"), &ImportDefaultsEditor::_reset); ClassDB::bind_method(D_METHOD("_save"), &ImportDefaultsEditor::_save); ClassDB::bind_method(D_METHOD("_importer_selected"), &ImportDefaultsEditor::_importer_selected); ADD_SIGNAL(MethodInfo("project_settings_changed")); } ImportDefaultsEditor::ImportDefaultsEditor() { HBoxContainer *hb = memnew(HBoxContainer); hb->add_child(memnew(Label(TTR("Importer:")))); importers = memnew(OptionButton); hb->add_child(importers); hb->add_spacer(); importers->connect("item_selected", this, "_importer_selected"); reset_defaults = memnew(Button); reset_defaults->set_text(TTR("Reset to Defaults")); reset_defaults->set_disabled(true); reset_defaults->connect("pressed", this, "_reset"); hb->add_child(reset_defaults); add_child(hb); inspector = memnew(EditorInspector); add_child(inspector); inspector->set_v_size_flags(SIZE_EXPAND_FILL); CenterContainer *cc = memnew(CenterContainer); save_defaults = memnew(Button); save_defaults->set_text(TTR("Save")); save_defaults->connect("pressed", this, "_save"); cc->add_child(save_defaults); add_child(cc); settings = memnew(ImportDefaultsEditorSettings); } ImportDefaultsEditor::~ImportDefaultsEditor() { memdelete(settings); }
35.72807
116
0.644365
[ "object", "vector" ]
a36f64b93381abd7e271869acff8476908750a32
3,433
cc
C++
manipulation/kuka_iiwa/test/iiwa_status_sender_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
manipulation/kuka_iiwa/test/iiwa_status_sender_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
manipulation/kuka_iiwa/test/iiwa_status_sender_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/manipulation/kuka_iiwa/iiwa_status_sender.h" #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { using Eigen::VectorXd; constexpr int N = kIiwaArmNumJoints; class IiwaStatusSenderTest : public testing::Test { public: IiwaStatusSenderTest() : dut_(), context_ptr_(dut_.CreateDefaultContext()), context_(*context_ptr_) {} const lcmt_iiwa_status& output() const { const lcmt_iiwa_status& result = dut_.get_output_port().Eval<lcmt_iiwa_status>(context_); DRAKE_DEMAND(result.num_joints == N); DRAKE_DEMAND(result.joint_position_commanded.size() == N); DRAKE_DEMAND(result.joint_position_measured.size() == N); DRAKE_DEMAND(result.joint_velocity_estimated.size() == N); DRAKE_DEMAND(result.joint_torque_commanded.size() == N); DRAKE_DEMAND(result.joint_torque_measured.size() == N); DRAKE_DEMAND(result.joint_torque_external.size() == N); return result; } static std::vector<double> as_vector(const Eigen::VectorXd& v) { return {v.data(), v.data() + v.size()}; } void Fix(const systems::InputPort<double>& port, const Eigen::VectorXd& v) { port.FixValue(&context_, v); } protected: IiwaStatusSender dut_; std::unique_ptr<systems::Context<double>> context_ptr_; systems::Context<double>& context_; }; TEST_F(IiwaStatusSenderTest, AcceptanceTest) { const VectorXd q0_commanded = VectorXd::LinSpaced(N, 0.1, 0.2); const VectorXd q0_measured = VectorXd::LinSpaced(N, 0.11, 0.22); const VectorXd v0_estimated = VectorXd::LinSpaced(N, 0.2, 0.3); const VectorXd t0_commanded = VectorXd::LinSpaced(N, 0.4, 0.5); const VectorXd t0_measured = VectorXd::LinSpaced(N, 0.44, 0.55); const VectorXd t0_external = VectorXd::LinSpaced(N, 0.6, 0.7); // Fix only the required inputs ... Fix(dut_.get_position_commanded_input_port(), q0_commanded); Fix(dut_.get_position_measured_input_port(), q0_measured); Fix(dut_.get_torque_commanded_input_port(), t0_commanded); // ... so that some outputs have passthrough values ... EXPECT_EQ(output().joint_position_commanded, as_vector(q0_commanded)); EXPECT_EQ(output().joint_position_measured, as_vector(q0_measured)); EXPECT_EQ(output().joint_torque_commanded, as_vector(t0_commanded)); // ... and some outputs have default values. EXPECT_EQ(output().joint_velocity_estimated, std::vector<double>(N, 0.0)); EXPECT_EQ(output().joint_torque_measured, as_vector(t0_commanded)); EXPECT_EQ(output().joint_torque_external, std::vector<double>(N, 0.0)); // Fix all of the inputs ... Fix(dut_.get_velocity_estimated_input_port(), v0_estimated); Fix(dut_.get_torque_measured_input_port(), t0_measured); Fix(dut_.get_torque_external_input_port(), t0_external); // ... so all outputs have values. EXPECT_EQ(output().joint_position_commanded, as_vector(q0_commanded)); EXPECT_EQ(output().joint_position_measured, as_vector(q0_measured)); EXPECT_EQ(output().joint_torque_commanded, as_vector(t0_commanded)); EXPECT_EQ(output().joint_velocity_estimated, as_vector(v0_estimated)); EXPECT_EQ(output().joint_torque_measured, as_vector(t0_measured)); EXPECT_EQ(output().joint_torque_external, as_vector(t0_external)); } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
39.011364
78
0.74483
[ "vector" ]
a37030b028964a712c95767fb553f0844b025586
17,155
cpp
C++
src/Handler.cpp
erlichmen/libmediasoupclient
f843c272f809a68d59615f7c3e6d3a536e221d76
[ "ISC" ]
null
null
null
src/Handler.cpp
erlichmen/libmediasoupclient
f843c272f809a68d59615f7c3e6d3a536e221d76
[ "ISC" ]
null
null
null
src/Handler.cpp
erlichmen/libmediasoupclient
f843c272f809a68d59615f7c3e6d3a536e221d76
[ "ISC" ]
null
null
null
#define MSC_CLASS "Handler" #include "Handler.hpp" #include "Logger.hpp" #include "MediaSoupClientErrors.hpp" #include "PeerConnection.hpp" #include "sdptransform.hpp" #include "sdp/Utils.hpp" #include <cinttypes> // PRIu64, etc using json = nlohmann::json; static json SctpNumStreams = { { "OS", 1024u }, { "MIS", 1024u } }; namespace mediasoupclient { /* Handler static methods. */ json Handler::GetNativeRtpCapabilities(const PeerConnection::Options* peerConnectionOptions) { MSC_TRACE(); std::unique_ptr<PeerConnection::PrivateListener> privateListener( new PeerConnection::PrivateListener()); std::unique_ptr<PeerConnection> pc( new PeerConnection(privateListener.get(), peerConnectionOptions)); (void)pc->AddTransceiver(cricket::MediaType::MEDIA_TYPE_AUDIO); (void)pc->AddTransceiver(cricket::MediaType::MEDIA_TYPE_VIDEO); webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; // May throw. auto offer = pc->CreateOffer(options); auto sdpObject = sdptransform::parse(offer); auto nativeRtpCapabilities = Sdp::Utils::extractRtpCapabilities(sdpObject); return nativeRtpCapabilities; } json Handler::GetNativeSctpCapabilities() { MSC_TRACE(); json caps = { "numStreams", SctpNumStreams }; return caps; } /* Handler instance methods. */ Handler::Handler( PrivateListener* privateListener, const json& iceParameters, const json& iceCandidates, const json& dtlsParameters, const json& sctpParameters, const PeerConnection::Options* peerConnectionOptions) : privateListener(privateListener) { MSC_TRACE(); this->pc.reset(new PeerConnection(this, peerConnectionOptions)); this->remoteSdp.reset( new Sdp::RemoteSdp(iceParameters, iceCandidates, dtlsParameters, sctpParameters)); }; void Handler::Close() { MSC_TRACE(); this->pc->Close(); }; json Handler::GetTransportStats() { MSC_TRACE(); return this->pc->GetStats(); } void Handler::UpdateIceServers(const json& iceServerUris) { MSC_TRACE(); auto configuration = this->pc->GetConfiguration(); configuration.servers.clear(); for (auto& iceServerUri : iceServerUris) { webrtc::PeerConnectionInterface::IceServer iceServer; iceServer.uri = iceServerUri; configuration.servers.push_back(iceServer); } if (this->pc->SetConfiguration(configuration)) return; MSC_THROW_ERROR("failed to update ICE servers"); }; void Handler::OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState newState) { MSC_TRACE(); return this->privateListener->OnConnectionStateChange(newState); } void Handler::SetupTransport(const std::string& localDtlsRole, json localSdpObject) { MSC_TRACE(); if (localSdpObject.empty()) localSdpObject = sdptransform::parse(this->pc->GetLocalDescription()); // Get our local DTLS parameters. auto dtlsParameters = Sdp::Utils::extractDtlsParameters(localSdpObject); // Set our DTLS role. dtlsParameters["role"] = localDtlsRole; std::string remoteDtlsRole = localDtlsRole == "client" ? "server" : "client"; this->remoteSdp->UpdateDtlsRole(remoteDtlsRole); // May throw. this->privateListener->OnConnect(dtlsParameters); this->transportReady = true; }; /* SendHandler instance methods. */ SendHandler::SendHandler( Handler::PrivateListener* privateListener, const json& iceParameters, const json& iceCandidates, const json& dtlsParameters, const json& sctpParameters, const PeerConnection::Options* peerConnectionOptions, const json& sendingRtpParametersByKind, const json& sendingRemoteRtpParametersByKind) : Handler( privateListener, iceParameters, iceCandidates, dtlsParameters, sctpParameters, peerConnectionOptions) { MSC_TRACE(); this->sendingRtpParametersByKind = sendingRtpParametersByKind; this->sendingRemoteRtpParametersByKind = sendingRemoteRtpParametersByKind; }; SendHandler::SendData SendHandler::Send( webrtc::MediaStreamTrackInterface* track, const std::vector<webrtc::RtpEncodingParameters>* encodings, const json* codecOptions) { MSC_TRACE(); // Check if the track is a null pointer. if (!track) MSC_THROW_TYPE_ERROR("missing track"); MSC_DEBUG("[kind:%s, track->id():%s]", track->kind().c_str(), track->id().c_str()); // https://bugs.chromium.org/p/webrtc/issues/detail?id=7600 // Once the issue is solved, no SDP will be required to enable simulcast. webrtc::RtpTransceiverInterface* transceiver = this->pc->AddTransceiver(track); if (!transceiver) MSC_THROW_ERROR("error creating transceiver"); transceiver->SetDirection(webrtc::RtpTransceiverDirection::kSendOnly); std::string offer; std::string localId; json& sendingRtpParameters = this->sendingRtpParametersByKind[track->kind()]; try { webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; offer = this->pc->CreateOffer(options); auto localSdpObject = sdptransform::parse(offer); // Transport is not ready. if (!this->transportReady) this->SetupTransport("server", localSdpObject); if (encodings != nullptr && encodings->size() > 1) { MSC_DEBUG("enabling legacy simulcast"); // We know that our media section is the last one. auto numMediaSection = localSdpObject["media"].size(); json& offerMediaObject = localSdpObject["media"][numMediaSection - 1]; Sdp::Utils::addLegacySimulcast(offerMediaObject, encodings->size()); offer = sdptransform::write(localSdpObject); } MSC_DEBUG("calling pc->SetLocalDescription():\n%s", offer.c_str()); this->pc->SetLocalDescription(PeerConnection::SdpType::OFFER, offer); // We can now get the transceiver.mid. localId = transceiver->mid().value(); // Set MID. sendingRtpParameters["mid"] = localId; } catch (std::exception& error) { // Panic here. Try to undo things. transceiver->SetDirection(webrtc::RtpTransceiverDirection::kInactive); transceiver->sender()->SetTrack(nullptr); throw; } auto localSdp = this->pc->GetLocalDescription(); auto localSdpObject = sdptransform::parse(localSdp); // We know that our media section is the last one. auto numMediaSection = localSdpObject["media"].size(); json& offerMediaObject = localSdpObject["media"][numMediaSection - 1]; // Set RTCP CNAME. sendingRtpParameters["rtcp"]["cname"] = Sdp::Utils::getCname(offerMediaObject); // Set RTP encodings. sendingRtpParameters["encodings"] = Sdp::Utils::getRtpEncodings(offerMediaObject); // If VP8 and there is effective simulcast, add scalabilityMode to each encoding. auto mimeType = sendingRtpParameters["codecs"][0]["mimeType"].get<std::string>(); std::transform(mimeType.begin(), mimeType.end(), mimeType.begin(), ::tolower); // clang-format off if ( sendingRtpParameters["encodings"].size() > 1 && (mimeType == "video/vp8" || mimeType == "video/h264") ) // clang-format on { for (auto& encoding : sendingRtpParameters["encodings"]) { encoding["scalabilityMode"] = "S1T3"; } } this->remoteSdp->Send( offerMediaObject, sendingRtpParameters, this->sendingRemoteRtpParametersByKind[track->kind()], codecOptions); auto answer = this->remoteSdp->GetSdp(); MSC_DEBUG("calling pc->SetRemoteDescription():\n%s", answer.c_str()); this->pc->SetRemoteDescription(PeerConnection::SdpType::ANSWER, answer); // Store in the map. this->mapMidTransceiver[localId] = transceiver; SendData sendData; sendData.localId = localId; sendData.rtpSender = transceiver->sender(); sendData.rtpParameters = sendingRtpParameters; return sendData; } void SendHandler::StopSending(const std::string& localId) { MSC_TRACE(); MSC_DEBUG("[localId:%s]", localId.c_str()); auto locaIdIt = this->mapMidTransceiver.find(localId); if (locaIdIt == this->mapMidTransceiver.end()) MSC_THROW_ERROR("associated RtpTransceiver not found"); auto* transceiver = locaIdIt->second; transceiver->sender()->SetTrack(nullptr); this->pc->RemoveTrack(transceiver->sender()); this->remoteSdp->DisableMediaSection(transceiver->mid().value()); // May throw. webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; auto offer = this->pc->CreateOffer(options); MSC_DEBUG("calling pc->SetLocalDescription():\n%s", offer.c_str()); // May throw. this->pc->SetLocalDescription(PeerConnection::SdpType::OFFER, offer); auto localSdpObj = sdptransform::parse(this->pc->GetLocalDescription()); auto answer = this->remoteSdp->GetSdp(); MSC_DEBUG("calling pc->SetRemoteDescription():\n%s", answer.c_str()); // May throw. this->pc->SetRemoteDescription(PeerConnection::SdpType::ANSWER, answer); } void SendHandler::ReplaceTrack(const std::string& localId, webrtc::MediaStreamTrackInterface* track) { MSC_TRACE(); MSC_DEBUG( "[localId:%s, track->id():%s]", localId.c_str(), track == nullptr ? "nullptr" : track->id().c_str()); auto localIdIt = this->mapMidTransceiver.find(localId); if (localIdIt == this->mapMidTransceiver.end()) MSC_THROW_ERROR("associated RtpTransceiver not found"); auto* transceiver = localIdIt->second; transceiver->sender()->SetTrack(track); } void SendHandler::SetMaxSpatialLayer(const std::string& localId, uint8_t spatialLayer) { MSC_TRACE(); MSC_DEBUG("[localId:%s, spatialLayer:%" PRIu8 "]", localId.c_str(), spatialLayer); auto localIdIt = this->mapMidTransceiver.find(localId); if (localIdIt == this->mapMidTransceiver.end()) MSC_THROW_ERROR("associated RtpTransceiver not found"); auto* transceiver = localIdIt->second; auto parameters = transceiver->sender()->GetParameters(); bool hasLowEncoding{ false }, hasMediumEncoding{ false }, hasHighEncoding{ false }; webrtc::RtpEncodingParameters* lowEncoding{ nullptr }; webrtc::RtpEncodingParameters* mediumEncoding{ nullptr }; webrtc::RtpEncodingParameters* highEncoding{ nullptr }; if (!parameters.encodings.empty()) { hasLowEncoding = true; lowEncoding = &parameters.encodings[0]; } if (parameters.encodings.size() > 1) { hasMediumEncoding = true; mediumEncoding = &parameters.encodings[1]; } if (parameters.encodings.size() > 2) { hasHighEncoding = true; highEncoding = &parameters.encodings[2]; } // Edit encodings. if (spatialLayer == 1u) { hasLowEncoding && (lowEncoding->active = true); hasMediumEncoding && (mediumEncoding->active = false); hasHighEncoding && (highEncoding->active = false); } else if (spatialLayer == 2u) { hasLowEncoding && (lowEncoding->active = true); hasMediumEncoding && (mediumEncoding->active = true); hasHighEncoding && (highEncoding->active = false); } else if (spatialLayer == 3u) { hasLowEncoding && (lowEncoding->active = true); hasMediumEncoding && (mediumEncoding->active = true); hasHighEncoding && (highEncoding->active = true); } auto result = transceiver->sender()->SetParameters(parameters); if (!result.ok()) MSC_THROW_ERROR("%s", result.message()); } json SendHandler::GetSenderStats(const std::string& localId) { MSC_TRACE(); MSC_DEBUG("[localId:%s]", localId.c_str()); auto localIdIt = this->mapMidTransceiver.find(localId); if (localIdIt == this->mapMidTransceiver.end()) MSC_THROW_ERROR("associated RtpTransceiver not found"); auto* transceiver = localIdIt->second; auto stats = this->pc->GetStats(transceiver->sender()); return stats; } void SendHandler::RestartIce(const json& iceParameters) { MSC_TRACE(); // Provide the remote SDP handler with new remote ICE parameters. this->remoteSdp->UpdateIceParameters(iceParameters); if (!this->transportReady) return; webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; options.ice_restart = true; // May throw. auto offer = this->pc->CreateOffer(options); MSC_DEBUG("calling pc->SetLocalDescription():\n%s", offer.c_str()); // May throw. this->pc->SetLocalDescription(PeerConnection::SdpType::OFFER, offer); auto localSdpObj = sdptransform::parse(this->pc->GetLocalDescription()); auto answer = this->remoteSdp->GetSdp(); MSC_DEBUG("calling pc->SetRemoteDescription():\n%s", answer.c_str()); // May throw. this->pc->SetRemoteDescription(PeerConnection::SdpType::ANSWER, answer); } /* RecvHandler methods */ RecvHandler::RecvHandler( Handler::PrivateListener* privateListener, const json& iceParameters, const json& iceCandidates, const json& dtlsParameters, const json& sctpParameters, const PeerConnection::Options* peerConnectionOptions) : Handler( privateListener, iceParameters, iceCandidates, dtlsParameters, sctpParameters, peerConnectionOptions) { MSC_TRACE(); }; RecvHandler::RecvData RecvHandler::Receive( const std::string& id, const std::string& kind, const json* rtpParameters) { MSC_TRACE(); MSC_DEBUG("[id:%s, kind:%s]", id.c_str(), kind.c_str()); auto localId = std::to_string(this->nextMid); auto& cname = (*rtpParameters)["rtcp"]["cname"]; this->remoteSdp->Receive(localId, kind, *rtpParameters, cname, id); auto offer = this->remoteSdp->GetSdp(); MSC_DEBUG("calling pc->setRemoteDescription():\n%s", offer.c_str()); // May throw. this->pc->SetRemoteDescription(PeerConnection::SdpType::OFFER, offer); webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; // May throw. auto answer = this->pc->CreateAnswer(options); auto localSdpObject = sdptransform::parse(answer); auto mediaIt = find_if( localSdpObject["media"].begin(), localSdpObject["media"].end(), [&localId](const json& m) { return m["mid"].get<std::string>() == localId; }); auto& answerMediaObject = *mediaIt; // May need to modify codec parameters in the answer based on codec // parameters in the offer. Sdp::Utils::applyCodecParameters(*rtpParameters, answerMediaObject); answer = sdptransform::write(localSdpObject); if (!this->transportReady) this->SetupTransport("client", localSdpObject); MSC_DEBUG("calling pc->SetLocalDescription():\n%s", answer.c_str()); // May throw. this->pc->SetLocalDescription(PeerConnection::SdpType::ANSWER, answer); auto transceivers = this->pc->GetTransceivers(); auto transceiverIt = std::find_if( transceivers.begin(), transceivers.end(), [&localId](webrtc::RtpTransceiverInterface* t) { return t->mid() == localId; }); if (transceiverIt == transceivers.end()) MSC_THROW_ERROR("new RTCRtpTransceiver not found"); auto& transceiver = *transceiverIt; // Store in the map. this->mapMidTransceiver[localId] = transceiver; // Increase next MID. this->nextMid++; RecvData recvData; recvData.localId = localId; recvData.rtpReceiver = transceiver->receiver(); recvData.track = transceiver->receiver()->track(); return recvData; } void RecvHandler::StopReceiving(const std::string& localId) { MSC_TRACE(); MSC_DEBUG("[localId:%s]", localId.c_str()); auto localIdIt = this->mapMidTransceiver.find(localId); if (localIdIt == this->mapMidTransceiver.end()) MSC_THROW_ERROR("associated RtpTransceiver not found"); auto& transceiver = localIdIt->second; MSC_DEBUG("disabling mid:%s", transceiver->mid().value().c_str()); this->remoteSdp->DisableMediaSection(transceiver->mid().value()); auto offer = this->remoteSdp->GetSdp(); MSC_DEBUG("calling pc->setRemoteDescription():\n%s", offer.c_str()); // May throw. this->pc->SetRemoteDescription(PeerConnection::SdpType::OFFER, offer); webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; // May throw. auto answer = this->pc->CreateAnswer(options); MSC_DEBUG("calling pc->SetLocalDescription():\n%s", answer.c_str()); // May throw. this->pc->SetLocalDescription(PeerConnection::SdpType::ANSWER, answer); } json RecvHandler::GetReceiverStats(const std::string& localId) { MSC_TRACE(); MSC_DEBUG("[localId:%s]", localId.c_str()); auto localIdIt = this->mapMidTransceiver.find(localId); if (localIdIt == this->mapMidTransceiver.end()) MSC_THROW_ERROR("associated RtpTransceiver not found"); auto& transceiver = localIdIt->second; // May throw. auto stats = this->pc->GetStats(transceiver->receiver()); return stats; } void RecvHandler::RestartIce(const json& iceParameters) { MSC_TRACE(); // Provide the remote SDP handler with new remote ICE parameters. this->remoteSdp->UpdateIceParameters(iceParameters); if (!this->transportReady) return; auto offer = this->remoteSdp->GetSdp(); MSC_DEBUG("calling pc->setRemoteDescription():\n%s", offer.c_str()); // May throw. this->pc->SetRemoteDescription(PeerConnection::SdpType::OFFER, offer); webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; // May throw. auto answer = this->pc->CreateAnswer(options); MSC_DEBUG("calling pc->SetLocalDescription():\n%s", answer.c_str()); // May throw. this->pc->SetLocalDescription(PeerConnection::SdpType::ANSWER, answer); } } // namespace mediasoupclient
27.985318
108
0.71093
[ "vector", "transform" ]
a372ea8f481dd9c62373af27068d1e0a2f1f0cf6
77,748
cpp
C++
taichi/codegen/codegen_llvm.cpp
Jack12xl/taichi
80eba2ee9f0a471f86f1786625ebda04bf3c7236
[ "MIT" ]
2
2021-06-25T12:18:54.000Z
2021-12-07T14:54:45.000Z
taichi/codegen/codegen_llvm.cpp
Jack12xl/taichi
80eba2ee9f0a471f86f1786625ebda04bf3c7236
[ "MIT" ]
null
null
null
taichi/codegen/codegen_llvm.cpp
Jack12xl/taichi
80eba2ee9f0a471f86f1786625ebda04bf3c7236
[ "MIT" ]
1
2021-12-07T14:54:49.000Z
2021-12-07T14:54:49.000Z
#include "taichi/codegen/codegen_llvm.h" #include "taichi/ir/statements.h" #include "taichi/struct/struct_llvm.h" #include "taichi/util/file_sequence_writer.h" TLANG_NAMESPACE_BEGIN // TODO: sort function definitions to match declaration order in header // OffloadedTask OffloadedTask::OffloadedTask(CodeGenLLVM *codegen) : codegen(codegen) { func = nullptr; } void OffloadedTask::begin(const std::string &name) { this->name = name; } void OffloadedTask::end() { codegen->offloaded_tasks.push_back(*this); } void OffloadedTask::operator()(Context *context) { TI_ASSERT(func); func(context); } void OffloadedTask::compile() { TI_ASSERT(!func); auto kernel_symbol = codegen->tlctx->lookup_function_pointer(name); TI_ASSERT_INFO(kernel_symbol, "Function not found"); func = (task_fp_type)kernel_symbol; } // TODO(k-ye): Hide FunctionCreationGuard inside cpp file FunctionCreationGuard::FunctionCreationGuard( CodeGenLLVM *mb, std::vector<llvm::Type *> arguments) : mb(mb) { // Create the loop body function auto body_function_type = llvm::FunctionType::get( llvm::Type::getVoidTy(*mb->llvm_context), arguments, false); body = llvm::Function::Create(body_function_type, llvm::Function::InternalLinkage, "function_body", mb->module.get()); old_func = mb->func; // emit into loop body function mb->func = body; allocas = llvm::BasicBlock::Create(*mb->llvm_context, "allocs", body); old_entry = mb->entry_block; mb->entry_block = allocas; entry = llvm::BasicBlock::Create(*mb->llvm_context, "entry", mb->func); ip = mb->builder->saveIP(); mb->builder->SetInsertPoint(entry); auto body_bb = llvm::BasicBlock::Create(*mb->llvm_context, "function_body", mb->func); mb->builder->CreateBr(body_bb); mb->builder->SetInsertPoint(body_bb); } FunctionCreationGuard::~FunctionCreationGuard() { mb->builder->CreateRetVoid(); mb->func = old_func; mb->builder->restoreIP(ip); { llvm::IRBuilderBase::InsertPointGuard gurad(*mb->builder); mb->builder->SetInsertPoint(allocas); mb->builder->CreateBr(entry); mb->entry_block = old_entry; } } namespace { class CodeGenStmtGuard { public: using Getter = std::function<llvm::BasicBlock *(void)>; using Setter = std::function<void(llvm::BasicBlock *)>; explicit CodeGenStmtGuard(Getter getter, Setter setter) : saved_stmt_(getter()), setter_(std::move(setter)) { } ~CodeGenStmtGuard() { setter_(saved_stmt_); } CodeGenStmtGuard(CodeGenStmtGuard &&) = default; CodeGenStmtGuard &operator=(CodeGenStmtGuard &&) = default; private: llvm::BasicBlock *saved_stmt_; Setter setter_; }; CodeGenStmtGuard make_loop_reentry_guard(CodeGenLLVM *cg) { return CodeGenStmtGuard([cg]() { return cg->current_loop_reentry; }, [cg](llvm::BasicBlock *saved_stmt) { cg->current_loop_reentry = saved_stmt; }); } CodeGenStmtGuard make_while_after_loop_guard(CodeGenLLVM *cg) { return CodeGenStmtGuard([cg]() { return cg->current_while_after_loop; }, [cg](llvm::BasicBlock *saved_stmt) { cg->current_while_after_loop = saved_stmt; }); } } // namespace // CodeGenLLVM uint64 CodeGenLLVM::task_counter = 0; void CodeGenLLVM::visit(Block *stmt_list) { for (auto &stmt : stmt_list->statements) { stmt->accept(this); } } void CodeGenLLVM::visit(AllocaStmt *stmt) { if (stmt->ret_type->is<TensorType>()) { auto tensor_type = stmt->ret_type->cast<TensorType>(); auto type = tlctx->get_data_type(tensor_type->get_element_type()); auto array_size = tlctx->get_constant(tensor_type->get_num_elements()); // Return type is [array_size x type]*. llvm_val[stmt] = create_entry_block_alloca(type, 0, array_size); // Initialize as zero for (int i = 0; i < tensor_type->get_num_elements(); ++i) { auto origin_address = builder->CreatePtrToInt( llvm_val[stmt], llvm::Type::getInt64Ty(*llvm_context)); int address_offset = i * data_type_size(tensor_type->get_element_type()); auto target_address = builder->CreateAdd( origin_address, tlctx->get_constant((int64)address_offset)); auto target_ptr = builder->CreateIntToPtr( target_address, llvm::PointerType::get(type, 0)); builder->CreateStore( tlctx->get_constant(tensor_type->get_element_type(), 0), target_ptr); } } else { TI_ASSERT(stmt->width() == 1); llvm_val[stmt] = create_entry_block_alloca(stmt->ret_type, stmt->ret_type.is_pointer()); // initialize as zero if element is not a pointer if (!stmt->ret_type.is_pointer()) builder->CreateStore(tlctx->get_constant(stmt->ret_type, 0), llvm_val[stmt]); } } void CodeGenLLVM::visit(RandStmt *stmt) { llvm_val[stmt] = create_call( fmt::format("rand_{}", data_type_name(stmt->ret_type)), {get_context()}); } void CodeGenLLVM::emit_extra_unary(UnaryOpStmt *stmt) { auto input = llvm_val[stmt->operand]; auto input_taichi_type = stmt->operand->ret_type; auto op = stmt->op_type; auto input_type = input->getType(); #define UNARY_STD(x) \ else if (op == UnaryOpType::x) { \ if (input_taichi_type->is_primitive(PrimitiveTypeID::f32)) { \ llvm_val[stmt] = \ builder->CreateCall(get_runtime_function(#x "_f32"), input); \ } else if (input_taichi_type->is_primitive(PrimitiveTypeID::f64)) { \ llvm_val[stmt] = \ builder->CreateCall(get_runtime_function(#x "_f64"), input); \ } else if (input_taichi_type->is_primitive(PrimitiveTypeID::i32)) { \ llvm_val[stmt] = \ builder->CreateCall(get_runtime_function(#x "_i32"), input); \ } else { \ TI_NOT_IMPLEMENTED \ } \ } if (false) { } UNARY_STD(abs) UNARY_STD(exp) UNARY_STD(log) UNARY_STD(tan) UNARY_STD(tanh) UNARY_STD(sgn) UNARY_STD(logic_not) UNARY_STD(acos) UNARY_STD(asin) UNARY_STD(cos) UNARY_STD(sin) else if (op == UnaryOpType::sqrt) { llvm_val[stmt] = builder->CreateIntrinsic(llvm::Intrinsic::sqrt, {input_type}, {input}); } else { TI_P(unary_op_type_name(op)); TI_NOT_IMPLEMENTED } #undef UNARY_STD } std::unique_ptr<RuntimeObject> CodeGenLLVM::emit_struct_meta_object( SNode *snode) { std::unique_ptr<RuntimeObject> meta; if (snode->type == SNodeType::dense) { meta = std::make_unique<RuntimeObject>("DenseMeta", this, builder.get()); emit_struct_meta_base("Dense", meta->ptr, snode); meta->call("set_morton_dim", tlctx->get_constant((int)snode->_morton)); } else if (snode->type == SNodeType::pointer) { meta = std::make_unique<RuntimeObject>("PointerMeta", this, builder.get()); emit_struct_meta_base("Pointer", meta->ptr, snode); } else if (snode->type == SNodeType::root) { meta = std::make_unique<RuntimeObject>("RootMeta", this, builder.get()); emit_struct_meta_base("Root", meta->ptr, snode); } else if (snode->type == SNodeType::dynamic) { meta = std::make_unique<RuntimeObject>("DynamicMeta", this, builder.get()); emit_struct_meta_base("Dynamic", meta->ptr, snode); meta->call("set_chunk_size", tlctx->get_constant(snode->chunk_size)); } else if (snode->type == SNodeType::bitmasked) { meta = std::make_unique<RuntimeObject>("BitmaskedMeta", this, builder.get()); emit_struct_meta_base("Bitmasked", meta->ptr, snode); } else { TI_P(snode_type_name(snode->type)); TI_NOT_IMPLEMENTED; } return meta; } void CodeGenLLVM::emit_struct_meta_base(const std::string &name, llvm::Value *node_meta, SNode *snode) { RuntimeObject common("StructMeta", this, builder.get(), node_meta); std::size_t element_size; if (snode->type == SNodeType::dense) { auto body_type = StructCompilerLLVM::get_llvm_body_type(module.get(), snode); auto element_ty = body_type->getArrayElementType(); element_size = tlctx->get_type_size(element_ty); } else if (snode->type == SNodeType::pointer) { auto element_ty = StructCompilerLLVM::get_llvm_node_type( module.get(), snode->ch[0].get()); element_size = tlctx->get_type_size(element_ty); } else { auto element_ty = StructCompilerLLVM::get_llvm_element_type(module.get(), snode); element_size = tlctx->get_type_size(element_ty); } common.set("snode_id", tlctx->get_constant(snode->id)); common.set("element_size", tlctx->get_constant((uint64)element_size)); common.set("max_num_elements", tlctx->get_constant(snode->max_num_elements())); common.set("context", get_context()); /* uint8 *(*lookup_element)(uint8 *, int i); uint8 *(*from_parent_element)(uint8 *); bool (*is_active)(uint8 *, int i); int (*get_num_elements)(uint8 *); void (*refine_coordinates)(PhysicalCoordinates *inp_coord, PhysicalCoordinates *refined_coord, int index); */ std::vector<std::string> functions = {"lookup_element", "is_active", "get_num_elements"}; for (auto const &f : functions) common.set(f, get_runtime_function(fmt::format("{}_{}", name, f))); // "from_parent_element", "refine_coordinates" are different for different // snodes, even if they have the same type. if (snode->parent) common.set("from_parent_element", get_runtime_function(snode->get_ch_from_parent_func_name())); if (snode->type != SNodeType::place) common.set("refine_coordinates", get_runtime_function(snode->refine_coordinates_func_name())); } CodeGenLLVM::CodeGenLLVM(Kernel *kernel, IRNode *ir, std::unique_ptr<llvm::Module> &&module) // TODO: simplify LLVMModuleBuilder ctor input : LLVMModuleBuilder( module == nullptr ? kernel->program->get_llvm_program_impl() ->get_llvm_context(kernel->arch) ->clone_struct_module() : std::move(module), kernel->program->get_llvm_program_impl()->get_llvm_context( kernel->arch)), kernel(kernel), ir(ir), prog(kernel->program) { if (ir == nullptr) this->ir = kernel->ir.get(); initialize_context(); context_ty = get_runtime_type("Context"); physical_coordinate_ty = get_runtime_type(kLLVMPhysicalCoordinatesName); kernel_name = kernel->name + "_kernel"; } llvm::Value *CodeGenLLVM::cast_int(llvm::Value *input_val, Type *from, Type *to) { if (from == to) return input_val; auto from_size = 0; if (from->is<CustomIntType>()) { from_size = data_type_size(from->cast<CustomIntType>()->get_compute_type()); } else { from_size = data_type_size(from); } if (from_size < data_type_size(to)) { if (is_signed(from)) { return builder->CreateSExt(input_val, tlctx->get_data_type(to)); } else { return builder->CreateZExt(input_val, tlctx->get_data_type(to)); } } else { return builder->CreateTrunc(input_val, tlctx->get_data_type(to)); } } void CodeGenLLVM::visit(UnaryOpStmt *stmt) { auto input = llvm_val[stmt->operand]; auto input_type = input->getType(); auto op = stmt->op_type; #define UNARY_INTRINSIC(x) \ else if (op == UnaryOpType::x) { \ llvm_val[stmt] = \ builder->CreateIntrinsic(llvm::Intrinsic::x, {input_type}, {input}); \ } if (stmt->op_type == UnaryOpType::cast_value) { llvm::CastInst::CastOps cast_op; auto from = stmt->operand->ret_type; auto to = stmt->cast_type; if (from == to) { llvm_val[stmt] = llvm_val[stmt->operand]; } else if (is_real(from) != is_real(to)) { if (is_real(from) && is_integral(to)) { cast_op = llvm::Instruction::CastOps::FPToSI; } else if (is_integral(from) && is_real(to)) { cast_op = llvm::Instruction::CastOps::SIToFP; } else { TI_P(data_type_name(from)); TI_P(data_type_name(to)); TI_NOT_IMPLEMENTED; } llvm_val[stmt] = builder->CreateCast(cast_op, llvm_val[stmt->operand], tlctx->get_data_type(stmt->cast_type)); } else if (is_real(from) && is_real(to)) { if (data_type_size(from) < data_type_size(to)) { llvm_val[stmt] = builder->CreateFPExt( llvm_val[stmt->operand], tlctx->get_data_type(stmt->cast_type)); } else { llvm_val[stmt] = builder->CreateFPTrunc( llvm_val[stmt->operand], tlctx->get_data_type(stmt->cast_type)); } } else if (!is_real(from) && !is_real(to)) { // TODO: implement casting into custom integer type TI_ASSERT(!to->is<CustomIntType>()); llvm_val[stmt] = cast_int(llvm_val[stmt->operand], from, to); } } else if (stmt->op_type == UnaryOpType::cast_bits) { TI_ASSERT(data_type_size(stmt->ret_type) == data_type_size(stmt->cast_type)); if (stmt->operand->ret_type.is_pointer()) { TI_ASSERT(is_integral(stmt->cast_type)); llvm_val[stmt] = builder->CreatePtrToInt( llvm_val[stmt->operand], tlctx->get_data_type(stmt->cast_type)); } else { llvm_val[stmt] = builder->CreateBitCast( llvm_val[stmt->operand], tlctx->get_data_type(stmt->cast_type)); } } else if (op == UnaryOpType::rsqrt) { llvm::Function *sqrt_fn = llvm::Intrinsic::getDeclaration( module.get(), llvm::Intrinsic::sqrt, input->getType()); auto intermediate = builder->CreateCall(sqrt_fn, input, "sqrt"); llvm_val[stmt] = builder->CreateFDiv( tlctx->get_constant(stmt->ret_type, 1.0), intermediate); } else if (op == UnaryOpType::bit_not) { llvm_val[stmt] = builder->CreateNot(input); } else if (op == UnaryOpType::neg) { if (is_real(stmt->operand->ret_type)) { llvm_val[stmt] = builder->CreateFNeg(input, "neg"); } else { llvm_val[stmt] = builder->CreateNeg(input, "neg"); } } UNARY_INTRINSIC(floor) UNARY_INTRINSIC(ceil) else emit_extra_unary(stmt); #undef UNARY_INTRINSIC } void CodeGenLLVM::visit(BinaryOpStmt *stmt) { auto op = stmt->op_type; auto ret_type = stmt->ret_type; if (op == BinaryOpType::add) { if (is_real(stmt->ret_type)) { llvm_val[stmt] = builder->CreateFAdd(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { llvm_val[stmt] = builder->CreateAdd(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } else if (op == BinaryOpType::sub) { if (is_real(stmt->ret_type)) { llvm_val[stmt] = builder->CreateFSub(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { llvm_val[stmt] = builder->CreateSub(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } else if (op == BinaryOpType::mul) { if (is_real(stmt->ret_type)) { llvm_val[stmt] = builder->CreateFMul(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { llvm_val[stmt] = builder->CreateMul(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } else if (op == BinaryOpType::floordiv) { if (is_integral(ret_type)) llvm_val[stmt] = create_call(fmt::format("floordiv_{}", data_type_name(ret_type)), {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); else { auto div = builder->CreateFDiv(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); llvm_val[stmt] = builder->CreateIntrinsic( llvm::Intrinsic::floor, {tlctx->get_data_type(ret_type)}, {div}); } } else if (op == BinaryOpType::div) { if (is_real(stmt->ret_type)) { llvm_val[stmt] = builder->CreateFDiv(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { llvm_val[stmt] = builder->CreateSDiv(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } else if (op == BinaryOpType::mod) { llvm_val[stmt] = builder->CreateSRem(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else if (op == BinaryOpType::bit_and) { llvm_val[stmt] = builder->CreateAnd(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else if (op == BinaryOpType::bit_or) { llvm_val[stmt] = builder->CreateOr(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else if (op == BinaryOpType::bit_xor) { llvm_val[stmt] = builder->CreateXor(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else if (op == BinaryOpType::bit_shl) { llvm_val[stmt] = builder->CreateShl(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else if (op == BinaryOpType::bit_sar) { if (is_signed(stmt->lhs->element_type())) { llvm_val[stmt] = builder->CreateAShr(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { llvm_val[stmt] = builder->CreateLShr(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } else if (op == BinaryOpType::max) { if (is_real(ret_type)) { llvm_val[stmt] = builder->CreateMaxNum(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else if (ret_type->is_primitive(PrimitiveTypeID::i32)) { llvm_val[stmt] = create_call("max_i32", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else { TI_P(data_type_name(ret_type)); TI_NOT_IMPLEMENTED } } else if (op == BinaryOpType::atan2) { if (arch_is_cpu(current_arch())) { if (ret_type->is_primitive(PrimitiveTypeID::f32)) { llvm_val[stmt] = create_call( "atan2_f32", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else if (ret_type->is_primitive(PrimitiveTypeID::f64)) { llvm_val[stmt] = create_call( "atan2_f64", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else { TI_P(data_type_name(ret_type)); TI_NOT_IMPLEMENTED } } else if (current_arch() == Arch::cuda) { if (ret_type->is_primitive(PrimitiveTypeID::f32)) { llvm_val[stmt] = create_call( "__nv_atan2f", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else if (ret_type->is_primitive(PrimitiveTypeID::f64)) { llvm_val[stmt] = create_call( "__nv_atan2", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else { TI_P(data_type_name(ret_type)); TI_NOT_IMPLEMENTED } } else { TI_NOT_IMPLEMENTED } } else if (op == BinaryOpType::pow) { if (arch_is_cpu(current_arch())) { if (ret_type->is_primitive(PrimitiveTypeID::f32)) { llvm_val[stmt] = create_call("pow_f32", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else if (ret_type->is_primitive(PrimitiveTypeID::f64)) { llvm_val[stmt] = create_call("pow_f64", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else if (ret_type->is_primitive(PrimitiveTypeID::i32)) { llvm_val[stmt] = create_call("pow_i32", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else if (ret_type->is_primitive(PrimitiveTypeID::i64)) { llvm_val[stmt] = create_call("pow_i64", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else { TI_P(data_type_name(ret_type)); TI_NOT_IMPLEMENTED } } else if (current_arch() == Arch::cuda) { if (ret_type->is_primitive(PrimitiveTypeID::f32)) { llvm_val[stmt] = create_call( "__nv_powf", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else if (ret_type->is_primitive(PrimitiveTypeID::f64)) { llvm_val[stmt] = create_call("__nv_pow", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else if (ret_type->is_primitive(PrimitiveTypeID::i32)) { llvm_val[stmt] = create_call("pow_i32", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else if (ret_type->is_primitive(PrimitiveTypeID::i64)) { llvm_val[stmt] = create_call("pow_i64", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else { TI_P(data_type_name(ret_type)); TI_NOT_IMPLEMENTED } } else { TI_NOT_IMPLEMENTED } } else if (op == BinaryOpType::min) { if (is_real(ret_type)) { llvm_val[stmt] = builder->CreateMinNum(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else if (ret_type->is_primitive(PrimitiveTypeID::i32)) { llvm_val[stmt] = create_call("min_i32", {llvm_val[stmt->lhs], llvm_val[stmt->rhs]}); } else { TI_P(data_type_name(ret_type)); TI_NOT_IMPLEMENTED } } else if (is_comparison(op)) { llvm::Value *cmp = nullptr; auto input_type = stmt->lhs->ret_type; if (op == BinaryOpType::cmp_eq) { if (is_real(input_type)) { cmp = builder->CreateFCmpOEQ(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { cmp = builder->CreateICmpEQ(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } else if (op == BinaryOpType::cmp_le) { if (is_real(input_type)) { cmp = builder->CreateFCmpOLE(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { if (is_signed(input_type)) { cmp = builder->CreateICmpSLE(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { cmp = builder->CreateICmpULE(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } } else if (op == BinaryOpType::cmp_ge) { if (is_real(input_type)) { cmp = builder->CreateFCmpOGE(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { if (is_signed(input_type)) { cmp = builder->CreateICmpSGE(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { cmp = builder->CreateICmpUGE(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } } else if (op == BinaryOpType::cmp_lt) { if (is_real(input_type)) { cmp = builder->CreateFCmpOLT(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { if (is_signed(input_type)) { cmp = builder->CreateICmpSLT(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { cmp = builder->CreateICmpULT(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } } else if (op == BinaryOpType::cmp_gt) { if (is_real(input_type)) { cmp = builder->CreateFCmpOGT(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { if (is_signed(input_type)) { cmp = builder->CreateICmpSGT(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { cmp = builder->CreateICmpUGT(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } } else if (op == BinaryOpType::cmp_ne) { if (is_real(input_type)) { cmp = builder->CreateFCmpONE(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } else { cmp = builder->CreateICmpNE(llvm_val[stmt->lhs], llvm_val[stmt->rhs]); } } else { TI_NOT_IMPLEMENTED } llvm_val[stmt] = builder->CreateSExt(cmp, llvm_type(PrimitiveType::i32)); } else { TI_P(binary_op_type_name(op)); TI_NOT_IMPLEMENTED } } llvm::Type *CodeGenLLVM::llvm_type(DataType dt) { if (dt->is_primitive(PrimitiveTypeID::i8) || dt->is_primitive(PrimitiveTypeID::u8)) { return llvm::Type::getInt8Ty(*llvm_context); } else if (dt->is_primitive(PrimitiveTypeID::i16) || dt->is_primitive(PrimitiveTypeID::u16)) { return llvm::Type::getInt16Ty(*llvm_context); } else if (dt->is_primitive(PrimitiveTypeID::i32) || dt->is_primitive(PrimitiveTypeID::u32)) { return llvm::Type::getInt32Ty(*llvm_context); } else if (dt->is_primitive(PrimitiveTypeID::i64) || dt->is_primitive(PrimitiveTypeID::u64)) { return llvm::Type::getInt64Ty(*llvm_context); } else if (dt->is_primitive(PrimitiveTypeID::u1)) { return llvm::Type::getInt1Ty(*llvm_context); } else if (dt->is_primitive(PrimitiveTypeID::f32)) { return llvm::Type::getFloatTy(*llvm_context); } else if (dt->is_primitive(PrimitiveTypeID::f64)) { return llvm::Type::getDoubleTy(*llvm_context); } else { TI_NOT_IMPLEMENTED; } return nullptr; } llvm::Type *CodeGenLLVM::llvm_ptr_type(DataType dt) { return llvm::PointerType::get(llvm_type(dt), 0); } void CodeGenLLVM::visit(TernaryOpStmt *stmt) { TI_ASSERT(stmt->op_type == TernaryOpType::select); llvm_val[stmt] = builder->CreateSelect( builder->CreateTrunc(llvm_val[stmt->op1], llvm_type(PrimitiveType::u1)), llvm_val[stmt->op2], llvm_val[stmt->op3]); } void CodeGenLLVM::visit(IfStmt *if_stmt) { // TODO: take care of vectorized cases llvm::BasicBlock *true_block = llvm::BasicBlock::Create(*llvm_context, "true_block", func); llvm::BasicBlock *false_block = llvm::BasicBlock::Create(*llvm_context, "false_block", func); llvm::BasicBlock *after_if = llvm::BasicBlock::Create(*llvm_context, "after_if", func); builder->CreateCondBr( builder->CreateICmpNE(llvm_val[if_stmt->cond], tlctx->get_constant(0)), true_block, false_block); builder->SetInsertPoint(true_block); if (if_stmt->true_statements) { if_stmt->true_statements->accept(this); } builder->CreateBr(after_if); builder->SetInsertPoint(false_block); if (if_stmt->false_statements) { if_stmt->false_statements->accept(this); } builder->CreateBr(after_if); builder->SetInsertPoint(after_if); } llvm::Value *CodeGenLLVM::create_print(std::string tag, DataType dt, llvm::Value *value) { if (!arch_is_cpu(kernel->arch)) { TI_WARN("print not supported on arch {}", arch_name(kernel->arch)); return nullptr; } std::vector<llvm::Value *> args; std::string format = data_type_format(dt); auto runtime_printf = call("LLVMRuntime_get_host_printf", get_runtime()); args.push_back(builder->CreateGlobalStringPtr( ("[llvm codegen debug] " + tag + " = " + format + "\n").c_str(), "format_string")); if (dt->is_primitive(PrimitiveTypeID::f32)) value = builder->CreateFPExt(value, tlctx->get_data_type(PrimitiveType::f64)); args.push_back(value); return builder->CreateCall(runtime_printf, args); } llvm::Value *CodeGenLLVM::create_print(std::string tag, llvm::Value *value) { if (value->getType() == llvm::Type::getFloatTy(*llvm_context)) return create_print( tag, TypeFactory::get_instance().get_primitive_type(PrimitiveTypeID::f32), value); else if (value->getType() == llvm::Type::getInt32Ty(*llvm_context)) return create_print( tag, TypeFactory::get_instance().get_primitive_type(PrimitiveTypeID::i32), value); else TI_NOT_IMPLEMENTED } void CodeGenLLVM::visit(PrintStmt *stmt) { TI_ASSERT(stmt->width() == 1); std::vector<llvm::Value *> args; std::string formats; for (auto const &content : stmt->contents) { if (std::holds_alternative<Stmt *>(content)) { auto arg_stmt = std::get<Stmt *>(content); auto value = llvm_val[arg_stmt]; if (arg_stmt->ret_type->is_primitive(PrimitiveTypeID::f32)) value = builder->CreateFPExt(value, tlctx->get_data_type(PrimitiveType::f64)); args.push_back(value); formats += data_type_format(arg_stmt->ret_type); } else { auto arg_str = std::get<std::string>(content); auto value = builder->CreateGlobalStringPtr(arg_str, "content_string"); args.push_back(value); formats += "%s"; } } auto runtime_printf = call("LLVMRuntime_get_host_printf", get_runtime()); args.insert(args.begin(), builder->CreateGlobalStringPtr(formats.c_str(), "format_string")); llvm_val[stmt] = builder->CreateCall(runtime_printf, args); } void CodeGenLLVM::visit(ConstStmt *stmt) { TI_ASSERT(stmt->width() == 1); auto val = stmt->val[0]; if (val.dt->is_primitive(PrimitiveTypeID::f32)) { llvm_val[stmt] = llvm::ConstantFP::get(*llvm_context, llvm::APFloat(val.val_float32())); } else if (val.dt->is_primitive(PrimitiveTypeID::f64)) { llvm_val[stmt] = llvm::ConstantFP::get(*llvm_context, llvm::APFloat(val.val_float64())); } else if (val.dt->is_primitive(PrimitiveTypeID::i32)) { llvm_val[stmt] = llvm::ConstantInt::get( *llvm_context, llvm::APInt(32, (uint64)val.val_int32(), true)); } else if (val.dt->is_primitive(PrimitiveTypeID::u32)) { llvm_val[stmt] = llvm::ConstantInt::get( *llvm_context, llvm::APInt(32, (uint64)val.val_uint32(), false)); } else if (val.dt->is_primitive(PrimitiveTypeID::i64)) { llvm_val[stmt] = llvm::ConstantInt::get( *llvm_context, llvm::APInt(64, (uint64)val.val_int64(), true)); } else if (val.dt->is_primitive(PrimitiveTypeID::u64)) { llvm_val[stmt] = llvm::ConstantInt::get( *llvm_context, llvm::APInt(64, val.val_uint64(), false)); } else { TI_P(data_type_name(val.dt)); TI_NOT_IMPLEMENTED; } } void CodeGenLLVM::visit(WhileControlStmt *stmt) { using namespace llvm; BasicBlock *after_break = BasicBlock::Create(*llvm_context, "after_break", func); TI_ASSERT(current_while_after_loop); auto cond = builder->CreateICmpEQ(llvm_val[stmt->cond], tlctx->get_constant(0)); builder->CreateCondBr(cond, current_while_after_loop, after_break); builder->SetInsertPoint(after_break); } void CodeGenLLVM::visit(ContinueStmt *stmt) { using namespace llvm; if (stmt->as_return()) { builder->CreateRetVoid(); } else { TI_ASSERT(current_loop_reentry != nullptr); builder->CreateBr(current_loop_reentry); } // Stmts after continue are useless, so we switch the insertion point to // /dev/null. In LLVM IR, the "after_continue" label shows "No predecessors!". BasicBlock *after_continue = BasicBlock::Create(*llvm_context, "after_continue", func); builder->SetInsertPoint(after_continue); } void CodeGenLLVM::visit(WhileStmt *stmt) { using namespace llvm; BasicBlock *body = BasicBlock::Create(*llvm_context, "while_loop_body", func); builder->CreateBr(body); builder->SetInsertPoint(body); auto lrg = make_loop_reentry_guard(this); current_loop_reentry = body; BasicBlock *after_loop = BasicBlock::Create(*llvm_context, "after_while", func); auto walg = make_while_after_loop_guard(this); current_while_after_loop = after_loop; stmt->body->accept(this); builder->CreateBr(body); // jump to head builder->SetInsertPoint(after_loop); } llvm::Value *CodeGenLLVM::cast_pointer(llvm::Value *val, std::string dest_ty_name, int addr_space) { return builder->CreateBitCast( val, llvm::PointerType::get(get_runtime_type(dest_ty_name), addr_space)); } void CodeGenLLVM::emit_list_gen(OffloadedStmt *listgen) { auto snode_child = listgen->snode; auto snode_parent = listgen->snode->parent; auto meta_child = cast_pointer(emit_struct_meta(snode_child), "StructMeta"); auto meta_parent = cast_pointer(emit_struct_meta(snode_parent), "StructMeta"); if (snode_parent->type == SNodeType::root) { // Since there's only one container to expand, we need a special kernel for // more parallelism. call("element_listgen_root", get_runtime(), meta_parent, meta_child); } else { call("element_listgen_nonroot", get_runtime(), meta_parent, meta_child); } } void CodeGenLLVM::emit_gc(OffloadedStmt *stmt) { auto snode = stmt->snode->id; call("node_gc", get_runtime(), tlctx->get_constant(snode)); } llvm::Value *CodeGenLLVM::create_call(llvm::Value *func, std::vector<llvm::Value *> args) { check_func_call_signature(func, args); return builder->CreateCall(func, args); } llvm::Value *CodeGenLLVM::create_call(std::string func_name, std::vector<llvm::Value *> args) { auto func = get_runtime_function(func_name); return create_call(func, args); } void CodeGenLLVM::create_increment(llvm::Value *ptr, llvm::Value *value) { builder->CreateStore(builder->CreateAdd(builder->CreateLoad(ptr), value), ptr); } void CodeGenLLVM::create_naive_range_for(RangeForStmt *for_stmt) { using namespace llvm; BasicBlock *body = BasicBlock::Create(*llvm_context, "for_loop_body", func); BasicBlock *loop_inc = BasicBlock::Create(*llvm_context, "for_loop_inc", func); BasicBlock *after_loop = BasicBlock::Create(*llvm_context, "after_for", func); BasicBlock *loop_test = BasicBlock::Create(*llvm_context, "for_loop_test", func); auto loop_var = create_entry_block_alloca(PrimitiveType::i32); loop_vars_llvm[for_stmt].push_back(loop_var); if (!for_stmt->reversed) { builder->CreateStore(llvm_val[for_stmt->begin], loop_var); } else { builder->CreateStore( builder->CreateSub(llvm_val[for_stmt->end], tlctx->get_constant(1)), loop_var); } builder->CreateBr(loop_test); { // test block builder->SetInsertPoint(loop_test); llvm::Value *cond; if (!for_stmt->reversed) { cond = builder->CreateICmp(llvm::CmpInst::Predicate::ICMP_SLT, builder->CreateLoad(loop_var), llvm_val[for_stmt->end]); } else { cond = builder->CreateICmp(llvm::CmpInst::Predicate::ICMP_SGE, builder->CreateLoad(loop_var), llvm_val[for_stmt->begin]); } builder->CreateCondBr(cond, body, after_loop); } { { auto lrg = make_loop_reentry_guard(this); // The continue stmt should jump to the loop-increment block! current_loop_reentry = loop_inc; // body cfg builder->SetInsertPoint(body); for_stmt->body->accept(this); } builder->CreateBr(loop_inc); builder->SetInsertPoint(loop_inc); if (!for_stmt->reversed) { create_increment(loop_var, tlctx->get_constant(1)); } else { create_increment(loop_var, tlctx->get_constant(-1)); } builder->CreateBr(loop_test); } // next cfg builder->SetInsertPoint(after_loop); } void CodeGenLLVM::visit(RangeForStmt *for_stmt) { create_naive_range_for(for_stmt); } void CodeGenLLVM::visit(ArgLoadStmt *stmt) { auto raw_arg = call(builder.get(), "Context_get_args", get_context(), tlctx->get_constant(stmt->arg_id)); llvm::Type *dest_ty = nullptr; if (stmt->is_ptr) { dest_ty = llvm::PointerType::get(tlctx->get_data_type(PrimitiveType::i32), 0); llvm_val[stmt] = builder->CreateIntToPtr(raw_arg, dest_ty); } else { TI_ASSERT(!stmt->ret_type->is<PointerType>()); if (auto cit = stmt->ret_type->cast<CustomIntType>()) { if (cit->get_is_signed()) dest_ty = tlctx->get_data_type(PrimitiveType::i32); else dest_ty = tlctx->get_data_type(PrimitiveType::u32); } else { dest_ty = tlctx->get_data_type(stmt->ret_type); } auto dest_bits = dest_ty->getPrimitiveSizeInBits(); auto truncated = builder->CreateTrunc( raw_arg, llvm::Type::getIntNTy(*llvm_context, dest_bits)); llvm_val[stmt] = builder->CreateBitCast(truncated, dest_ty); } } void CodeGenLLVM::visit(ReturnStmt *stmt) { if (stmt->ret_type.is_pointer()) { TI_NOT_IMPLEMENTED } else { auto intermediate_bits = 0; if (auto cit = stmt->value->ret_type->cast<CustomIntType>()) { intermediate_bits = data_type_bits(cit->get_compute_type()); } else { intermediate_bits = tlctx->get_data_type(stmt->value->ret_type)->getPrimitiveSizeInBits(); } llvm::Type *intermediate_type = llvm::Type::getIntNTy(*llvm_context, intermediate_bits); llvm::Type *dest_ty = tlctx->get_data_type<int64>(); auto extended = builder->CreateZExt( builder->CreateBitCast(llvm_val[stmt->value], intermediate_type), dest_ty); builder->CreateCall(get_runtime_function("LLVMRuntime_store_result"), {get_runtime(), extended}); } } void CodeGenLLVM::visit(LocalLoadStmt *stmt) { TI_ASSERT(stmt->width() == 1); llvm_val[stmt] = builder->CreateLoad(llvm_val[stmt->src[0].var]); } void CodeGenLLVM::visit(LocalStoreStmt *stmt) { auto mask = stmt->parent->mask(); if (mask && stmt->width() != 1) { TI_NOT_IMPLEMENTED } else { builder->CreateStore(llvm_val[stmt->val], llvm_val[stmt->dest]); } } void CodeGenLLVM::visit(AssertStmt *stmt) { TI_ASSERT((int)stmt->args.size() <= taichi_error_message_max_num_arguments); auto argument_buffer_size = llvm::ArrayType::get( llvm::Type::getInt64Ty(*llvm_context), stmt->args.size()); // TODO: maybe let all asserts in a single offload share a single buffer? auto arguments = create_entry_block_alloca(argument_buffer_size); std::vector<llvm::Value *> args; args.emplace_back(get_runtime()); args.emplace_back(llvm_val[stmt->cond]); args.emplace_back(builder->CreateGlobalStringPtr(stmt->text)); for (int i = 0; i < stmt->args.size(); i++) { auto arg = stmt->args[i]; TI_ASSERT(llvm_val[arg]); // First convert the argument to an integral type with the same number of // bits: auto cast_type = llvm::Type::getIntNTy( *llvm_context, 8 * (std::size_t)data_type_size(arg->ret_type)); auto cast_int = builder->CreateBitCast(llvm_val[arg], cast_type); // Then zero-extend the conversion result into int64: auto cast_int64 = builder->CreateZExt(cast_int, llvm::Type::getInt64Ty(*llvm_context)); // Finally store the int64 value to the argument buffer: builder->CreateStore( cast_int64, builder->CreateGEP(arguments, {tlctx->get_constant(0), tlctx->get_constant(i)})); } args.emplace_back(tlctx->get_constant((int)stmt->args.size())); args.emplace_back(builder->CreateGEP( arguments, {tlctx->get_constant(0), tlctx->get_constant(0)})); llvm_val[stmt] = create_call("taichi_assert_format", args); } void CodeGenLLVM::visit(SNodeOpStmt *stmt) { auto snode = stmt->snode; if (stmt->op_type == SNodeOpType::append) { TI_ASSERT(snode->type == SNodeType::dynamic); TI_ASSERT(stmt->ret_type->is_primitive(PrimitiveTypeID::i32)); llvm_val[stmt] = call(snode, llvm_val[stmt->ptr], "append", {llvm_val[stmt->val]}); } else if (stmt->op_type == SNodeOpType::length) { TI_ASSERT(snode->type == SNodeType::dynamic); llvm_val[stmt] = call(snode, llvm_val[stmt->ptr], "get_num_elements", {}); } else if (stmt->op_type == SNodeOpType::is_active) { llvm_val[stmt] = call(snode, llvm_val[stmt->ptr], "is_active", {llvm_val[stmt->val]}); } else if (stmt->op_type == SNodeOpType::activate) { llvm_val[stmt] = call(snode, llvm_val[stmt->ptr], "activate", {llvm_val[stmt->val]}); } else if (stmt->op_type == SNodeOpType::deactivate) { if (snode->type == SNodeType::pointer || snode->type == SNodeType::hash || snode->type == SNodeType::bitmasked) { llvm_val[stmt] = call(snode, llvm_val[stmt->ptr], "deactivate", {llvm_val[stmt->val]}); } else if (snode->type == SNodeType::dynamic) { llvm_val[stmt] = call(snode, llvm_val[stmt->ptr], "deactivate", {}); } } else { TI_NOT_IMPLEMENTED } } void CodeGenLLVM::visit(AtomicOpStmt *stmt) { // auto mask = stmt->parent->mask(); // TODO: deal with mask when vectorized // TODO(type): support all AtomicOpTypes on custom types TI_ASSERT(stmt->width() == 1); for (int l = 0; l < stmt->width(); l++) { llvm::Value *old_value; if (stmt->op_type == AtomicOpType::add) { auto dst_type = stmt->dest->ret_type->as<PointerType>()->get_pointee_type(); if (dst_type->is<PrimitiveType>() && is_integral(stmt->val->ret_type)) { old_value = builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::Add, llvm_val[stmt->dest], llvm_val[stmt->val], llvm::AtomicOrdering::SequentiallyConsistent); } else if (!dst_type->is<CustomFloatType>() && is_real(stmt->val->ret_type)) { old_value = builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::FAdd, llvm_val[stmt->dest], llvm_val[stmt->val], llvm::AtomicOrdering::SequentiallyConsistent); } else if (auto cit = dst_type->cast<CustomIntType>()) { old_value = atomic_add_custom_int(stmt, cit); } else if (auto cft = dst_type->cast<CustomFloatType>()) { old_value = atomic_add_custom_float(stmt, cft); } else { TI_NOT_IMPLEMENTED } } else if (stmt->op_type == AtomicOpType::min) { if (is_integral(stmt->val->ret_type)) { old_value = builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::Min, llvm_val[stmt->dest], llvm_val[stmt->val], llvm::AtomicOrdering::SequentiallyConsistent); } else if (stmt->val->ret_type->is_primitive(PrimitiveTypeID::f32)) { old_value = builder->CreateCall(get_runtime_function("atomic_min_f32"), {llvm_val[stmt->dest], llvm_val[stmt->val]}); } else if (stmt->val->ret_type->is_primitive(PrimitiveTypeID::f64)) { old_value = builder->CreateCall(get_runtime_function("atomic_min_f64"), {llvm_val[stmt->dest], llvm_val[stmt->val]}); } else { TI_NOT_IMPLEMENTED } } else if (stmt->op_type == AtomicOpType::max) { if (is_integral(stmt->val->ret_type)) { old_value = builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::Max, llvm_val[stmt->dest], llvm_val[stmt->val], llvm::AtomicOrdering::SequentiallyConsistent); } else if (stmt->val->ret_type->is_primitive(PrimitiveTypeID::f32)) { old_value = builder->CreateCall(get_runtime_function("atomic_max_f32"), {llvm_val[stmt->dest], llvm_val[stmt->val]}); } else if (stmt->val->ret_type->is_primitive(PrimitiveTypeID::f64)) { old_value = builder->CreateCall(get_runtime_function("atomic_max_f64"), {llvm_val[stmt->dest], llvm_val[stmt->val]}); } else { TI_NOT_IMPLEMENTED } } else if (stmt->op_type == AtomicOpType::bit_and) { if (is_integral(stmt->val->ret_type)) { old_value = builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::And, llvm_val[stmt->dest], llvm_val[stmt->val], llvm::AtomicOrdering::SequentiallyConsistent); } else { TI_NOT_IMPLEMENTED } } else if (stmt->op_type == AtomicOpType::bit_or) { if (is_integral(stmt->val->ret_type)) { old_value = builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::Or, llvm_val[stmt->dest], llvm_val[stmt->val], llvm::AtomicOrdering::SequentiallyConsistent); } else { TI_NOT_IMPLEMENTED } } else if (stmt->op_type == AtomicOpType::bit_xor) { if (is_integral(stmt->val->ret_type)) { old_value = builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::Xor, llvm_val[stmt->dest], llvm_val[stmt->val], llvm::AtomicOrdering::SequentiallyConsistent); } else { TI_NOT_IMPLEMENTED } } else { TI_NOT_IMPLEMENTED } llvm_val[stmt] = old_value; } } void CodeGenLLVM::visit(GlobalPtrStmt *stmt) { TI_ERROR("Global Ptrs should have been lowered."); } void CodeGenLLVM::visit(GlobalStoreStmt *stmt) { TI_ASSERT(!stmt->parent->mask() || stmt->width() == 1); TI_ASSERT(llvm_val[stmt->val]); TI_ASSERT(llvm_val[stmt->dest]); auto ptr_type = stmt->dest->ret_type->as<PointerType>(); if (ptr_type->is_bit_pointer()) { auto pointee_type = ptr_type->get_pointee_type(); if (!pointee_type->is<CustomIntType>()) { if (stmt->dest->as<GetChStmt>()->input_snode->type == SNodeType::bit_struct) { TI_ERROR( "Bit struct stores with type {} should have been " "handled by BitStructStoreStmt.", pointee_type->to_string()); } else { TI_ERROR("Bit array only supports custom int type."); } } llvm::Value *store_value = nullptr; auto *cit = pointee_type->as<CustomIntType>(); store_value = llvm_val[stmt->val]; store_custom_int(llvm_val[stmt->dest], cit, store_value, /*atomic=*/true); } else { builder->CreateStore(llvm_val[stmt->val], llvm_val[stmt->dest]); } } void CodeGenLLVM::visit(GlobalLoadStmt *stmt) { int width = stmt->width(); TI_ASSERT(width == 1); auto ptr_type = stmt->src->ret_type->as<PointerType>(); if (ptr_type->is_bit_pointer()) { auto val_type = ptr_type->get_pointee_type(); if (val_type->is<CustomIntType>()) { llvm_val[stmt] = load_as_custom_int(llvm_val[stmt->src], val_type); } else if (auto cft = val_type->cast<CustomFloatType>()) { TI_ASSERT(stmt->src->is<GetChStmt>()); llvm_val[stmt] = load_custom_float(stmt->src); } else { TI_NOT_IMPLEMENTED } } else { llvm_val[stmt] = builder->CreateLoad(tlctx->get_data_type(stmt->ret_type), llvm_val[stmt->src]); } } void CodeGenLLVM::visit(ElementShuffleStmt *stmt){ TI_NOT_IMPLEMENTED /* auto init = stmt->elements.serialize( [](const VectorElement &elem) { return fmt::format("{}[{}]", elem.stmt->raw_name(), elem.index); }, "{"); if (stmt->pointer) { emit("{} * const {} [{}] {};", data_type_name(stmt->ret_type), stmt->raw_name(), stmt->width(), init); } else { emit("const {} {} ({});", stmt->ret_data_type_name(), stmt->raw_name(), init); } */ } std::string CodeGenLLVM::get_runtime_snode_name(SNode *snode) { if (snode->type == SNodeType::root) { return "Root"; } else if (snode->type == SNodeType::dense) { return "Dense"; } else if (snode->type == SNodeType::dynamic) { return "Dynamic"; } else if (snode->type == SNodeType::pointer) { return "Pointer"; } else if (snode->type == SNodeType::hash) { return "Hash"; } else if (snode->type == SNodeType::bitmasked) { return "Bitmasked"; } else if (snode->type == SNodeType::bit_struct) { return "BitStruct"; } else if (snode->type == SNodeType::bit_array) { return "BitArray"; } else { TI_P(snode_type_name(snode->type)); TI_NOT_IMPLEMENTED } } llvm::Value *CodeGenLLVM::call(SNode *snode, llvm::Value *node_ptr, const std::string &method, const std::vector<llvm::Value *> &arguments) { auto prefix = get_runtime_snode_name(snode); auto s = emit_struct_meta(snode); auto s_ptr = builder->CreateBitCast(s, llvm::Type::getInt8PtrTy(*llvm_context)); node_ptr = builder->CreateBitCast(node_ptr, llvm::Type::getInt8PtrTy(*llvm_context)); std::vector<llvm::Value *> func_arguments{s_ptr, node_ptr}; func_arguments.insert(func_arguments.end(), arguments.begin(), arguments.end()); return call(builder.get(), prefix + "_" + method, func_arguments); } void CodeGenLLVM::visit(GetRootStmt *stmt) { if (stmt->root() == nullptr) llvm_val[stmt] = builder->CreateBitCast( get_root(SNodeTree::kFirstID), llvm::PointerType::get( StructCompilerLLVM::get_llvm_node_type( module.get(), prog->get_snode_root(SNodeTree::kFirstID)), 0)); else llvm_val[stmt] = builder->CreateBitCast( get_root(stmt->root()->get_snode_tree_id()), llvm::PointerType::get( StructCompilerLLVM::get_llvm_node_type(module.get(), stmt->root()), 0)); } void CodeGenLLVM::visit(BitExtractStmt *stmt) { int mask = (1u << (stmt->bit_end - stmt->bit_begin)) - 1; llvm_val[stmt] = builder->CreateAnd( builder->CreateLShr(llvm_val[stmt->input], stmt->bit_begin), tlctx->get_constant(mask)); } void CodeGenLLVM::visit(LinearizeStmt *stmt) { llvm::Value *val = tlctx->get_constant(0); for (int i = 0; i < (int)stmt->inputs.size(); i++) { val = builder->CreateAdd( builder->CreateMul(val, tlctx->get_constant(stmt->strides[i])), llvm_val[stmt->inputs[i]]); } llvm_val[stmt] = val; } void CodeGenLLVM::visit(IntegerOffsetStmt *stmt){TI_NOT_IMPLEMENTED} llvm::Value *CodeGenLLVM::create_bit_ptr_struct(llvm::Value *byte_ptr_base, llvm::Value *bit_offset) { // 1. get the bit pointer LLVM struct // struct bit_pointer { // i8* byte_ptr; // i32 offset; // }; auto struct_type = llvm::StructType::get( *llvm_context, {llvm::Type::getInt8PtrTy(*llvm_context), llvm::Type::getInt32Ty(*llvm_context)}); // 2. allocate the bit pointer struct auto bit_ptr_struct = create_entry_block_alloca(struct_type); // 3. store `byte_ptr_base` into `bit_ptr_struct` (if provided) if (byte_ptr_base) { auto byte_ptr = builder->CreateBitCast( byte_ptr_base, llvm::PointerType::getInt8PtrTy(*llvm_context)); builder->CreateStore( byte_ptr, builder->CreateGEP(bit_ptr_struct, {tlctx->get_constant(0), tlctx->get_constant(0)})); } // 4. store `offset` in `bit_ptr_struct` (if provided) if (bit_offset) { builder->CreateStore( bit_offset, builder->CreateGEP(bit_ptr_struct, {tlctx->get_constant(0), tlctx->get_constant(1)})); } return bit_ptr_struct; } llvm::Value *CodeGenLLVM::offset_bit_ptr(llvm::Value *input_bit_ptr, int bit_offset_delta) { auto byte_ptr_base = builder->CreateLoad(builder->CreateGEP( input_bit_ptr, {tlctx->get_constant(0), tlctx->get_constant(0)})); auto input_offset = builder->CreateLoad(builder->CreateGEP( input_bit_ptr, {tlctx->get_constant(0), tlctx->get_constant(1)})); auto new_bit_offset = builder->CreateAdd(input_offset, tlctx->get_constant(bit_offset_delta)); return create_bit_ptr_struct(byte_ptr_base, new_bit_offset); } void CodeGenLLVM::visit(SNodeLookupStmt *stmt) { llvm::Value *parent = nullptr; parent = llvm_val[stmt->input_snode]; TI_ASSERT(parent); auto snode = stmt->snode; if (snode->type == SNodeType::root) { llvm_val[stmt] = builder->CreateGEP(parent, llvm_val[stmt->input_index]); } else if (snode->type == SNodeType::dense || snode->type == SNodeType::pointer || snode->type == SNodeType::dynamic || snode->type == SNodeType::bitmasked) { if (stmt->activate) { call(snode, llvm_val[stmt->input_snode], "activate", {llvm_val[stmt->input_index]}); } llvm_val[stmt] = call(snode, llvm_val[stmt->input_snode], "lookup_element", {llvm_val[stmt->input_index]}); } else if (snode->type == SNodeType::bit_struct) { llvm_val[stmt] = parent; } else if (snode->type == SNodeType::bit_array) { auto element_num_bits = snode->dt->as<BitArrayType>()->get_element_num_bits(); auto offset = tlctx->get_constant(element_num_bits); offset = builder->CreateMul(offset, llvm_val[stmt->input_index]); llvm_val[stmt] = create_bit_ptr_struct(llvm_val[stmt->input_snode], offset); } else { TI_INFO(snode_type_name(snode->type)); TI_NOT_IMPLEMENTED } } void CodeGenLLVM::visit(GetChStmt *stmt) { if (stmt->input_snode->type == SNodeType::bit_array) { llvm_val[stmt] = llvm_val[stmt->input_ptr]; } else if (stmt->ret_type->as<PointerType>()->is_bit_pointer()) { auto bit_struct = stmt->input_snode->dt->cast<BitStructType>(); auto bit_offset = bit_struct->get_member_bit_offset( stmt->input_snode->child_id(stmt->output_snode)); auto offset = tlctx->get_constant(bit_offset); llvm_val[stmt] = create_bit_ptr_struct(llvm_val[stmt->input_ptr], offset); } else { auto ch = create_call(stmt->output_snode->get_ch_from_parent_func_name(), {builder->CreateBitCast( llvm_val[stmt->input_ptr], llvm::PointerType::getInt8PtrTy(*llvm_context))}); llvm_val[stmt] = builder->CreateBitCast( ch, llvm::PointerType::get(StructCompilerLLVM::get_llvm_node_type( module.get(), stmt->output_snode), 0)); } } void CodeGenLLVM::visit(PtrOffsetStmt *stmt) { auto origin_address = builder->CreatePtrToInt( llvm_val[stmt->origin], llvm::Type::getInt64Ty(*llvm_context)); auto address_offset = builder->CreateSExt( llvm_val[stmt->offset], llvm::Type::getInt64Ty(*llvm_context)); auto target_address = builder->CreateAdd(origin_address, address_offset); auto dt = stmt->ret_type.ptr_removed(); llvm_val[stmt] = builder->CreateIntToPtr( target_address, llvm::PointerType::get(tlctx->get_data_type(dt), 0)); } void CodeGenLLVM::visit(ExternalPtrStmt *stmt) { TI_ASSERT(stmt->width() == 1); auto argload = stmt->base_ptrs[0]->as<ArgLoadStmt>(); auto arg_id = argload->arg_id; int num_indices = stmt->indices.size(); std::vector<llvm::Value *> sizes(num_indices); for (int i = 0; i < num_indices; i++) { auto raw_arg = builder->CreateCall( get_runtime_function("Context_get_extra_args"), {get_context(), tlctx->get_constant(arg_id), tlctx->get_constant(i)}); sizes[i] = raw_arg; } auto dt = stmt->ret_type.ptr_removed(); auto base = builder->CreateBitCast( llvm_val[stmt->base_ptrs[0]], llvm::PointerType::get(tlctx->get_data_type(dt), 0)); auto linear_index = tlctx->get_constant(0); for (int i = 0; i < num_indices; i++) { linear_index = builder->CreateMul(linear_index, sizes[i]); linear_index = builder->CreateAdd(linear_index, llvm_val[stmt->indices[i]]); } llvm_val[stmt] = builder->CreateGEP(base, linear_index); } void CodeGenLLVM::visit(ExternalTensorShapeAlongAxisStmt *stmt) { const auto arg_id = stmt->arg_id; const auto axis = stmt->axis; llvm_val[stmt] = builder->CreateCall( get_runtime_function("Context_get_extra_args"), {get_context(), tlctx->get_constant(arg_id), tlctx->get_constant(axis)}); } std::string CodeGenLLVM::init_offloaded_task_function(OffloadedStmt *stmt, std::string suffix) { current_loop_reentry = nullptr; current_while_after_loop = nullptr; task_function_type = llvm::FunctionType::get(llvm::Type::getVoidTy(*llvm_context), {llvm::PointerType::get(context_ty, 0)}, false); auto task_kernel_name = fmt::format("{}_{}_{}{}", kernel_name, task_counter, stmt->task_name(), suffix); task_counter += 1; func = llvm::Function::Create(task_function_type, llvm::Function::ExternalLinkage, task_kernel_name, module.get()); current_task = std::make_unique<OffloadedTask>(this); current_task->begin(task_kernel_name); for (auto &arg : func->args()) { kernel_args.push_back(&arg); } kernel_args[0]->setName("context"); if (kernel_argument_by_val()) func->addParamAttr(0, llvm::Attribute::ByVal); // entry_block has all the allocas this->entry_block = llvm::BasicBlock::Create(*llvm_context, "entry", func); // The real function body func_body_bb = llvm::BasicBlock::Create(*llvm_context, "body", func); builder->SetInsertPoint(func_body_bb); return task_kernel_name; } void CodeGenLLVM::finalize_offloaded_task_function() { builder->CreateRetVoid(); // entry_block should jump to the body after all allocas are inserted builder->SetInsertPoint(entry_block); builder->CreateBr(func_body_bb); if (prog->config.print_kernel_llvm_ir) { static FileSequenceWriter writer("taichi_kernel_generic_llvm_ir_{:04d}.ll", "unoptimized LLVM IR (generic)"); writer.write(module.get()); } TI_ASSERT(!llvm::verifyFunction(*func, &llvm::errs())); // TI_INFO("Kernel function verified."); } std::tuple<llvm::Value *, llvm::Value *> CodeGenLLVM::get_range_for_bounds( OffloadedStmt *stmt) { llvm::Value *begin, *end; if (stmt->const_begin) { begin = tlctx->get_constant(stmt->begin_value); } else { auto begin_stmt = Stmt::make<GlobalTemporaryStmt>( stmt->begin_offset, TypeFactory::create_vector_or_scalar_type(1, PrimitiveType::i32)); begin_stmt->accept(this); begin = builder->CreateLoad(llvm_val[begin_stmt.get()]); } if (stmt->const_end) { end = tlctx->get_constant(stmt->end_value); } else { auto end_stmt = Stmt::make<GlobalTemporaryStmt>( stmt->end_offset, TypeFactory::create_vector_or_scalar_type(1, PrimitiveType::i32)); end_stmt->accept(this); end = builder->CreateLoad(llvm_val[end_stmt.get()]); } return std::tuple(begin, end); } void CodeGenLLVM::create_offload_struct_for(OffloadedStmt *stmt, bool spmd) { using namespace llvm; // TODO: instead of constructing tons of LLVM IR, writing the logic in // runtime.cpp may be a cleaner solution. See // CodeGenLLVMCPU::create_offload_range_for as an example. llvm::Function *body = nullptr; auto leaf_block = stmt->snode; // When looping over bit_arrays, we always vectorize and generate struct for // on their parent node (usually "dense") instead of itself for higher // performance. Also, note that the loop must be bit_vectorized for // bit_arrays, and their parent must be "dense". if (leaf_block->type == SNodeType::bit_array) { if (leaf_block->parent->type == SNodeType::dense) { leaf_block = leaf_block->parent; } else { TI_ERROR( "Struct-for looping through bit array but its parent is not dense") } } { // Create the loop body function auto guard = get_function_creation_guard({ llvm::PointerType::get(get_runtime_type("Context"), 0), get_tls_buffer_type(), llvm::PointerType::get(get_runtime_type("Element"), 0), tlctx->get_data_type<int>(), tlctx->get_data_type<int>(), }); body = guard.body; /* Function structure: * * function_body (entry): * loop_index = lower_bound; * tls_prologue() * bls_prologue() * goto loop_test * * loop_test: * if (loop_index < upper_bound) * goto loop_body * else * goto func_exit * * loop_body: * initialize_coordinates() * if (bitmasked voxel is active) * goto struct_for_body * else * goto loop_body_tail * * struct_for_body: * ... (Run codegen on the StructForStmt::body Taichi Block) * goto loop_body_tail * * loop_body_tail: * loop_index += block_dim * goto loop_test * * func_exit: * bls_epilogue() * tls_epilogue() * return */ auto loop_index = create_entry_block_alloca(llvm::Type::getInt32Ty(*llvm_context)); RuntimeObject element("Element", this, builder.get(), get_arg(2)); // Loop ranges auto lower_bound = get_arg(3); auto upper_bound = get_arg(4); parent_coordinates = element.get_ptr("pcoord"); block_corner_coordinates = create_entry_block_alloca(physical_coordinate_ty); auto refine = get_runtime_function(leaf_block->refine_coordinates_func_name()); // A block corner is the global coordinate/index of the lower-left corner // cell within that block, and is the same for all the cells within that // block. create_call(refine, {parent_coordinates, block_corner_coordinates, tlctx->get_constant(0)}); if (stmt->tls_prologue) { stmt->tls_prologue->accept(this); } if (stmt->bls_prologue) { call("block_barrier"); // "__syncthreads()" stmt->bls_prologue->accept(this); call("block_barrier"); // "__syncthreads()" } llvm::Value *thread_idx = nullptr, *block_dim = nullptr; if (spmd) { thread_idx = builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_tid_x, {}, {}); block_dim = builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ntid_x, {}, {}); builder->CreateStore(builder->CreateAdd(thread_idx, lower_bound), loop_index); } else { builder->CreateStore(lower_bound, loop_index); } auto loop_test_bb = BasicBlock::Create(*llvm_context, "loop_test", func); auto loop_body_bb = BasicBlock::Create(*llvm_context, "loop_body", func); auto body_tail_bb = BasicBlock::Create(*llvm_context, "loop_body_tail", func); auto func_exit = BasicBlock::Create(*llvm_context, "func_exit", func); auto struct_for_body_bb = BasicBlock::Create(*llvm_context, "struct_for_body_body", func); builder->CreateBr(loop_test_bb); { // loop_test: // if (loop_index < upper_bound) // goto loop_body; // else // goto func_exit builder->SetInsertPoint(loop_test_bb); auto cond = builder->CreateICmp(llvm::CmpInst::Predicate::ICMP_SLT, builder->CreateLoad(loop_index), upper_bound); builder->CreateCondBr(cond, loop_body_bb, func_exit); } // *********************** // Begin loop_body_bb: builder->SetInsertPoint(loop_body_bb); // initialize the coordinates auto new_coordinates = create_entry_block_alloca(physical_coordinate_ty); create_call(refine, {parent_coordinates, new_coordinates, builder->CreateLoad(loop_index)}); // One more refine step is needed for bit_arrays to make final coordinates // non-consecutive, since each thread will process multiple // coordinates via vectorization if (stmt->snode->type == SNodeType::bit_array && stmt->snode->parent) { if (stmt->snode->parent->type == SNodeType::dense) { refine = get_runtime_function(stmt->snode->refine_coordinates_func_name()); create_call(refine, {new_coordinates, new_coordinates, tlctx->get_constant(0)}); } else { TI_ERROR( "Struct-for looping through bit array but its parent is not dense"); } } current_coordinates = new_coordinates; // exec_cond: safe-guard the execution of loop body: // - if non-POT field dim exists, make sure we don't go out of bounds // - if leaf block is bitmasked, make sure we only loop over active // voxels auto exec_cond = tlctx->get_constant(true); auto snode = stmt->snode; if (snode->type == SNodeType::bit_array && snode->parent) { if (snode->parent->type == SNodeType::dense) { snode = snode->parent; } else { TI_ERROR( "Struct-for looping through bit array but its parent is not dense"); } } auto coord_object = RuntimeObject(kLLVMPhysicalCoordinatesName, this, builder.get(), new_coordinates); if (!prog->config.packed) { for (int i = 0; i < snode->num_active_indices; i++) { auto j = snode->physical_index_position[i]; if (!bit::is_power_of_two( snode->extractors[j].num_elements_from_root)) { auto coord = coord_object.get("val", tlctx->get_constant(j)); exec_cond = builder->CreateAnd( exec_cond, builder->CreateICmp( llvm::CmpInst::ICMP_SLT, coord, tlctx->get_constant( snode->extractors[j].num_elements_from_root))); } } } if (snode->type == SNodeType::bitmasked || snode->type == SNodeType::pointer) { // test whether the current voxel is active or not auto is_active = call(snode, element.get("element"), "is_active", {builder->CreateLoad(loop_index)}); is_active = builder->CreateTrunc(is_active, llvm::Type::getInt1Ty(*llvm_context)); exec_cond = builder->CreateAnd(exec_cond, is_active); } builder->CreateCondBr(exec_cond, struct_for_body_bb, body_tail_bb); { builder->SetInsertPoint(struct_for_body_bb); // The real loop body of the StructForStmt stmt->body->accept(this); builder->CreateBr(body_tail_bb); } { // body tail: increment loop_index and jump to loop_test builder->SetInsertPoint(body_tail_bb); if (spmd) { create_increment(loop_index, block_dim); } else { create_increment(loop_index, tlctx->get_constant(1)); } builder->CreateBr(loop_test_bb); builder->SetInsertPoint(func_exit); } if (stmt->bls_epilogue) { call("block_barrier"); // "__syncthreads()" stmt->bls_epilogue->accept(this); call("block_barrier"); // "__syncthreads()" } if (stmt->tls_epilogue) { stmt->tls_epilogue->accept(this); } } int list_element_size = std::min(leaf_block->max_num_elements(), (int64)taichi_listgen_max_element_size); int num_splits = std::max(1, list_element_size / stmt->block_dim); auto struct_for_func = get_runtime_function("parallel_struct_for"); if (arch_is_gpu(current_arch())) { // Note that on CUDA local array allocation must have a compile-time // constant size. Therefore, instead of passing in the tls_buffer_size // argument, we directly clone the "parallel_struct_for" function and // replace the "alignas(8) char tls_buffer[1]" statement with "alignas(8) // char tls_buffer[tls_buffer_size]" at compile time. auto value_map = llvm::ValueToValueMapTy(); auto patched_struct_for_func = llvm::CloneFunction(struct_for_func, value_map); int replaced_alloca_types = 0; // Find the "1" in "char tls_buffer[1]" and replace it with // "tls_buffer_size" for (auto &bb : *patched_struct_for_func) { for (llvm::Instruction &inst : bb) { auto alloca = llvm::dyn_cast<AllocaInst>(&inst); if (!alloca || alloca->getAlignment() != 8) continue; auto alloca_type = alloca->getAllocatedType(); auto char_type = llvm::Type::getInt8Ty(*llvm_context); // Allocated type should be array [1 x i8] if (alloca_type->isArrayTy() && alloca_type->getArrayNumElements() == 1 && alloca_type->getArrayElementType() == char_type) { auto new_type = llvm::ArrayType::get(char_type, stmt->tls_size); alloca->setAllocatedType(new_type); replaced_alloca_types += 1; } } } // There should be **exactly** one replacement. TI_ASSERT(replaced_alloca_types == 1); struct_for_func = patched_struct_for_func; } // Loop over nodes in the element list, in parallel create_call( struct_for_func, {get_context(), tlctx->get_constant(leaf_block->id), tlctx->get_constant(list_element_size), tlctx->get_constant(num_splits), body, tlctx->get_constant(stmt->tls_size), tlctx->get_constant(stmt->num_cpu_threads)}); // TODO: why do we need num_cpu_threads on GPUs? current_coordinates = nullptr; parent_coordinates = nullptr; block_corner_coordinates = nullptr; } void CodeGenLLVM::visit(LoopIndexStmt *stmt) { if (stmt->loop->is<OffloadedStmt>() && stmt->loop->as<OffloadedStmt>()->task_type == OffloadedStmt::TaskType::struct_for) { llvm_val[stmt] = builder->CreateLoad(builder->CreateGEP( current_coordinates, {tlctx->get_constant(0), tlctx->get_constant(0), tlctx->get_constant(stmt->index)})); } else { llvm_val[stmt] = builder->CreateLoad(loop_vars_llvm[stmt->loop][stmt->index]); } } void CodeGenLLVM::visit(LoopLinearIndexStmt *stmt) { if (stmt->loop->is<OffloadedStmt>() && stmt->loop->as<OffloadedStmt>()->task_type == OffloadedStmt::TaskType::struct_for) { llvm_val[stmt] = create_call("thread_idx"); } else { TI_NOT_IMPLEMENTED; } } void CodeGenLLVM::visit(BlockCornerIndexStmt *stmt) { if (stmt->loop->is<OffloadedStmt>() && stmt->loop->as<OffloadedStmt>()->task_type == OffloadedStmt::TaskType::struct_for) { TI_ASSERT(block_corner_coordinates); llvm_val[stmt] = builder->CreateLoad( builder->CreateGEP(block_corner_coordinates, {tlctx->get_constant(0), tlctx->get_constant(0), tlctx->get_constant(stmt->index)})); } else { TI_NOT_IMPLEMENTED; } } void CodeGenLLVM::visit(BlockDimStmt *stmt) { TI_NOT_IMPLEMENTED // No need for this statement for now. Untested so mark // it as a loud failure. llvm_val[stmt] = create_call("block_dim", {}); } void CodeGenLLVM::visit(GlobalTemporaryStmt *stmt) { auto runtime = get_runtime(); auto buffer = call("get_temporary_pointer", runtime, tlctx->get_constant((int64)stmt->offset)); TI_ASSERT(stmt->width() == 1 || stmt->ret_type->is<TensorType>()); if (stmt->ret_type->is<TensorType>()) { auto ptr_type = llvm::PointerType::get( tlctx->get_data_type( stmt->ret_type->cast<TensorType>()->get_element_type()), 0); llvm_val[stmt] = builder->CreatePointerCast(buffer, ptr_type); } else { auto ptr_type = llvm::PointerType::get( tlctx->get_data_type(stmt->ret_type.ptr_removed()), 0); llvm_val[stmt] = builder->CreatePointerCast(buffer, ptr_type); } } void CodeGenLLVM::visit(ThreadLocalPtrStmt *stmt) { auto base = get_tls_base_ptr(); TI_ASSERT(stmt->width() == 1); auto ptr = builder->CreateGEP(base, tlctx->get_constant(stmt->offset)); auto ptr_type = llvm::PointerType::get( tlctx->get_data_type(stmt->ret_type.ptr_removed()), 0); llvm_val[stmt] = builder->CreatePointerCast(ptr, ptr_type); } void CodeGenLLVM::visit(BlockLocalPtrStmt *stmt) { TI_ASSERT(bls_buffer); auto base = bls_buffer; TI_ASSERT(stmt->width() == 1); auto ptr = builder->CreateGEP( base, {tlctx->get_constant(0), llvm_val[stmt->offset]}); auto ptr_type = llvm::PointerType::get( tlctx->get_data_type(stmt->ret_type.ptr_removed()), 0); llvm_val[stmt] = builder->CreatePointerCast(ptr, ptr_type); } void CodeGenLLVM::visit(ClearListStmt *stmt) { auto snode_child = stmt->snode; auto snode_parent = stmt->snode->parent; auto meta_child = cast_pointer(emit_struct_meta(snode_child), "StructMeta"); auto meta_parent = cast_pointer(emit_struct_meta(snode_parent), "StructMeta"); call("clear_list", get_runtime(), meta_parent, meta_child); } void CodeGenLLVM::visit(InternalFuncStmt *stmt) { std::vector<llvm::Value *> args{get_context()}; for (auto s : stmt->args) { args.push_back(llvm_val[s]); } llvm_val[stmt] = create_call(stmt->func_name, args); } void CodeGenLLVM::visit(AdStackAllocaStmt *stmt) { TI_ASSERT(stmt->width() == 1); TI_ASSERT_INFO(stmt->max_size > 0, "Adaptive autodiff stack's size should have been determined."); auto type = llvm::ArrayType::get(llvm::Type::getInt8Ty(*llvm_context), stmt->size_in_bytes()); auto alloca = create_entry_block_alloca(type, sizeof(int64)); llvm_val[stmt] = builder->CreateBitCast( alloca, llvm::PointerType::getInt8PtrTy(*llvm_context)); call("stack_init", llvm_val[stmt]); } void CodeGenLLVM::visit(AdStackPopStmt *stmt) { call("stack_pop", llvm_val[stmt->stack]); } void CodeGenLLVM::visit(AdStackPushStmt *stmt) { auto stack = stmt->stack->as<AdStackAllocaStmt>(); call("stack_push", llvm_val[stack], tlctx->get_constant(stack->max_size), tlctx->get_constant(stack->element_size_in_bytes())); auto primal_ptr = call("stack_top_primal", llvm_val[stack], tlctx->get_constant(stack->element_size_in_bytes())); primal_ptr = builder->CreateBitCast( primal_ptr, llvm::PointerType::get(tlctx->get_data_type(stmt->ret_type), 0)); builder->CreateStore(llvm_val[stmt->v], primal_ptr); } void CodeGenLLVM::visit(AdStackLoadTopStmt *stmt) { auto stack = stmt->stack->as<AdStackAllocaStmt>(); auto primal_ptr = call("stack_top_primal", llvm_val[stack], tlctx->get_constant(stack->element_size_in_bytes())); primal_ptr = builder->CreateBitCast( primal_ptr, llvm::PointerType::get(tlctx->get_data_type(stmt->ret_type), 0)); llvm_val[stmt] = builder->CreateLoad(primal_ptr); } void CodeGenLLVM::visit(AdStackLoadTopAdjStmt *stmt) { auto stack = stmt->stack->as<AdStackAllocaStmt>(); auto adjoint = call("stack_top_adjoint", llvm_val[stack], tlctx->get_constant(stack->element_size_in_bytes())); adjoint = builder->CreateBitCast( adjoint, llvm::PointerType::get(tlctx->get_data_type(stmt->ret_type), 0)); llvm_val[stmt] = builder->CreateLoad(adjoint); } void CodeGenLLVM::visit(AdStackAccAdjointStmt *stmt) { auto stack = stmt->stack->as<AdStackAllocaStmt>(); auto adjoint_ptr = call("stack_top_adjoint", llvm_val[stack], tlctx->get_constant(stack->element_size_in_bytes())); adjoint_ptr = builder->CreateBitCast( adjoint_ptr, llvm::PointerType::get(tlctx->get_data_type(stack->ret_type), 0)); auto old_val = builder->CreateLoad(adjoint_ptr); TI_ASSERT(is_real(stmt->v->ret_type)); auto new_val = builder->CreateFAdd(old_val, llvm_val[stmt->v]); builder->CreateStore(new_val, adjoint_ptr); } void CodeGenLLVM::visit(RangeAssumptionStmt *stmt) { llvm_val[stmt] = llvm_val[stmt->input]; } void CodeGenLLVM::visit(LoopUniqueStmt *stmt) { llvm_val[stmt] = llvm_val[stmt->input]; } void CodeGenLLVM::eliminate_unused_functions() { TaichiLLVMContext::eliminate_unused_functions( module.get(), [&](std::string func_name) { for (auto &task : offloaded_tasks) { if (task.name == func_name) return true; } return false; }); } FunctionType CodeGenLLVM::compile_module_to_executable() { TI_AUTO_PROF eliminate_unused_functions(); tlctx->add_module(std::move(module)); for (auto &task : offloaded_tasks) { task.compile(); } auto offloaded_tasks_local = offloaded_tasks; auto kernel_name_ = kernel_name; return [=](Context &context) { TI_TRACE("Launching kernel {}", kernel_name_); for (auto task : offloaded_tasks_local) { task(&context); } }; } FunctionCreationGuard CodeGenLLVM::get_function_creation_guard( std::vector<llvm::Type *> argument_types) { return FunctionCreationGuard(this, argument_types); } void CodeGenLLVM::initialize_context() { tlctx = prog->get_llvm_program_impl()->get_llvm_context(kernel->arch); llvm_context = tlctx->get_this_thread_context(); builder = std::make_unique<llvm::IRBuilder<>>(*llvm_context); } llvm::Value *CodeGenLLVM::get_arg(int i) { std::vector<llvm::Value *> args; for (auto &arg : func->args()) { args.push_back(&arg); } return args[i]; } llvm::Value *CodeGenLLVM::get_context() { return get_arg(0); } llvm::Value *CodeGenLLVM::get_tls_base_ptr() { return get_arg(1); } llvm::Type *CodeGenLLVM::get_tls_buffer_type() { return llvm::Type::getInt8PtrTy(*llvm_context); } std::vector<llvm::Type *> CodeGenLLVM::get_xlogue_argument_types() { return {llvm::PointerType::get(get_runtime_type("Context"), 0), get_tls_buffer_type()}; } llvm::Type *CodeGenLLVM::get_xlogue_function_type() { return llvm::FunctionType::get(llvm::Type::getVoidTy(*llvm_context), get_xlogue_argument_types(), false); } llvm::Value *CodeGenLLVM::get_root(int snode_tree_id) { return create_call("LLVMRuntime_get_roots", {get_runtime(), tlctx->get_constant(snode_tree_id)}); } llvm::Value *CodeGenLLVM::get_runtime() { auto runtime_ptr = create_call("Context_get_runtime", {get_context()}); return builder->CreateBitCast( runtime_ptr, llvm::PointerType::get(get_runtime_type("LLVMRuntime"), 0)); } llvm::Value *CodeGenLLVM::emit_struct_meta(SNode *snode) { auto obj = emit_struct_meta_object(snode); TI_ASSERT(obj != nullptr); return obj->ptr; } void CodeGenLLVM::emit_to_module() { TI_AUTO_PROF ir->accept(this); } FunctionType CodeGenLLVM::gen() { emit_to_module(); return compile_module_to_executable(); } llvm::Value *CodeGenLLVM::create_xlogue(std::unique_ptr<Block> &block) { llvm::Value *xlogue; auto xlogue_type = get_xlogue_function_type(); auto xlogue_ptr_type = llvm::PointerType::get(xlogue_type, 0); if (block) { auto guard = get_function_creation_guard(get_xlogue_argument_types()); block->accept(this); xlogue = guard.body; } else { xlogue = llvm::ConstantPointerNull::get(xlogue_ptr_type); } return xlogue; } TLANG_NAMESPACE_END
36.847393
80
0.638807
[ "vector" ]
a3741a3d13e8a2058592972e82d3fa4c6553a2be
9,702
hpp
C++
bflib/PF.hpp
olggc/bflib
15a43a6ca1db2a4c061b4a90b804518c75e9b514
[ "MIT" ]
1
2021-05-21T12:31:03.000Z
2021-05-21T12:31:03.000Z
bflib/PF.hpp
viniciusreis21/bflib
15a43a6ca1db2a4c061b4a90b804518c75e9b514
[ "MIT" ]
null
null
null
bflib/PF.hpp
viniciusreis21/bflib
15a43a6ca1db2a4c061b4a90b804518c75e9b514
[ "MIT" ]
null
null
null
// Copyright(c) 2019-present, Alexander Silva Barbosa & bflib contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) /** * @author Alexander Silva Barbosa <alexander.ti.ufv@gmail.com> * @date 2019 * Particle Filter (Monte Carlo) */ #pragma once #include <Eigen/Dense> #include <random> #include <chrono> #include <thread> #include <iostream> #include <vector> using namespace Eigen; using namespace std; template <typename dataType, int states, int inputs, int outputs, int outputSize> class PF { private: typedef Matrix<dataType, states, 1> MatNx1; typedef Matrix<dataType, inputs, 1> MatMx1; typedef Matrix<dataType, outputs, 1> MatPx1; typedef Matrix<dataType, states, states> MatNxN; public: typedef MatNx1 State; typedef MatMx1 Input; typedef MatPx1 Output; typedef Input Control; typedef Output Sensor; typedef MatPx1 SensorStd; typedef MatNx1 ResampleStd; double eps; private: typedef void (*ModelFunction)(State &x, Input &u, double dt); typedef void (*SensorFunction)(std::vector<Output> &y, State &x, double dt); std::default_random_engine gen; std::normal_distribution<double> distr{0.0, 1.0}; std::chrono::time_point<std::chrono::high_resolution_clock> start; int N, NMax; std::vector<State> W; std::vector< std::vector<Output> > Y; std::vector<double> w; double wMax; State minState, maxState, meanState; State x; ResampleStd Q; SensorStd R; MatNxN resampleMatrix; MatNx1 randX; ModelFunction modelFn; SensorFunction sensorFn; void init() { modelFn = NULL; sensorFn = NULL; resampleMatrix = Q.asDiagonal(); N = NMax; W.resize(N); Y.resize(N); w.resize(N); meanState = (maxState - minState) / 2; initW(); eps = 1e-10; start = std::chrono::high_resolution_clock::now(); } public: PF(int N, State minState, State maxState) : NMax(N), minState(minState), maxState(maxState) { Q.setIdentity(); R.setIdentity(); x.setZero(); init(); } PF(int N, State X, State minState, State maxState) : x(X), NMax(N), minState(minState), maxState(maxState) { Q.setIdentity(); R.setIdentity(); init(); } PF(int N, State minState, State maxState, ResampleStd Q, SensorStd R) : Q(Q), R(R), NMax(N), minState(minState), maxState(maxState) { x.setZero(); init(); } PF(int N, State X, State minState, State maxState, ResampleStd Q, SensorStd R) : x(X), Q(Q), R(R), NMax(N), minState(minState), maxState(maxState) { init(); } virtual ~PF() { } void seed() { unsigned int s = std::chrono::system_clock::now().time_since_epoch().count(); seed(s); } void seed(unsigned int s) { gen = std::default_random_engine(s); srand (s); std::srand(s); initW(); } State state() { MatNx1 x; x.setZero(); return x; } Input input() { MatMx1 u; u.setZero(); return u; } Output output() { MatPx1 y; y.setZero(); return y; } SensorStd createR() { SensorStd R; R.setZero(); return R; } void setR(SensorStd R) { this->R = R; } ResampleStd createQ() { ResampleStd Q; Q.setZero(); return Q; } void setQ(ResampleStd Q) { this->Q = Q; resampleMatrix = Q.asDiagonal(); } double time() { auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = end - start; start = std::chrono::high_resolution_clock::now(); return diff.count(); } double delay(double s) { double ellapsed = time(); double remain = s - ellapsed; if(remain < 0) return ellapsed; std::this_thread::sleep_for(std::chrono::nanoseconds((long long)(remain * 1e9))); ellapsed += time(); return ellapsed; } std::vector<State>& particles() { return W; } void setModel(ModelFunction fn) { modelFn = fn; } void setSensor(SensorFunction fn) { sensorFn = fn; } virtual void model(State &x, Input &u, double dt) { } virtual void sensor(std::vector<Output> &z, State &x, double dt) { } void simulate(State &x, std::vector<Output> &y, Input &u, double dt) { doModel(x, u, dt); y.resize(outputSize); doSensor(y, x, dt); } void run(State &xK, std::vector<Output> &y, Input &u, double dt) { y.resize(outputSize); applyControl(u, dt); sense(dt); compare(y); resample(); measure(); xK = x; } void VaryN(float error, int Nmin, int Ni, float error_lim, int Nmax) { int Np=0; if(error>error_lim) { float l; l = round(error/error_lim); int k = (int)l; Np = Nmin + Ni*k; if(Np > Nmax) { this->N = Nmax; } else { this->N = Np; } } else { Np = Nmin; this->N = Np; } cout << this-> N << endl; } private: void initW() { for(int n = 0; n < N; n++) { W[n] = State::Random(); for (size_t i = 0; i < states; i++) { W[n](i) = meanState(i) + W[n](i) * meanState(i); } } } void applyControl( Input &u, double dt) { for(int i = 0; i < N; i++) { doModel(W[i], u, dt); } } void sense(double dt) { for(int i = 0; i < N; i++) { Y[i].resize(outputSize); doSensor(Y[i], W[i], dt); } } void compare(std::vector<Output> &y) { double sum = 0; double lh = 0; for(int i = 0; i < N; i++) { w[i] = 1.0; for(int j = 0; j < outputSize; j++) { lh = likelihood(y[j], Y[i][j]); w[i] *= lh; } sum += w[i]; } wMax = 0; for(int i = 0; i < N; i++) { w[i] /= sum; if(w[i] > wMax) wMax = w[i]; } } double likelihood(Output y, Output z) { double lh = 0; double df, sq, ex, pi2, m; pi2 = sqrt(2 * 3.14159265358979); for (size_t i = 0; i < outputs; i++) { if(R(i) == 0) continue; m = 1.0 / ( R(i) * pi2 ); df = (z(i) - y(i)) / R(i); sq = df*df; ex = exp( -0.5 * sq ); lh += m * ex; } lh += eps; } void resample() { int index = rand() % N; double F; std::vector<State> nW(N); for(int i = 0; i < N; i++) { F = 10 * wMax * ( ( rand() % 100 ) / 100.0); while(F > w[index]) { F -= w[index]; index = ( index + 1 ) % N; } randn(randX); nW[i] = W[index] + resampleMatrix * randX; for (size_t j = 0; j < outputs; j++) { if(nW[i](j) < minState(j)) nW[i](j) = maxState(j) - ( minState(j) - nW[i](j) ); else if(nW[i](j) > maxState(j)) nW[i](j) = minState(j) + ( nW[i](j) - maxState(j) ); } } W = nW; } void measure() { x.setZero(); for(int i = 0; i < N; i++) { x += W[i]; } x /= N; } void doModel(State &x, Input &u, double dt) { if(modelFn != NULL) modelFn(x, u, dt); else model(x, u, dt); } void doSensor(std::vector<Output> &z, State &x, double dt) { if(sensorFn != NULL) sensorFn(z, x, dt); else sensor(z, x, dt); } template<class T> void randn(T &mat) { for (size_t i = 0; i < mat.rows(); i++) { for (size_t j = 0; j < mat.cols(); j++) { mat(i, j) = distr(gen); } } } };
23.210526
154
0.412801
[ "vector", "model" ]
a37718f5560bf33b5b904f04a594adba70b37a63
71,560
cpp
C++
src/capstone2llvmir/x86/x86_init.cpp
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
1
2019-01-25T13:31:44.000Z
2019-01-25T13:31:44.000Z
src/capstone2llvmir/x86/x86_init.cpp
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/capstone2llvmir/x86/x86_init.cpp
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
1
2019-03-24T03:45:30.000Z
2019-03-24T03:45:30.000Z
/** * @file src/capstone2llvmir/x86/x86_init.cpp * @brief Initializations for X86 implementation of @c Capstone2LlvmIrTranslator. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include "capstone2llvmir/x86/x86_impl.h" namespace retdec { namespace capstone2llvmir { // //============================================================================== // Pure virtual methods from Capstone2LlvmIrTranslator_impl //============================================================================== // void Capstone2LlvmIrTranslatorX86_impl::initializeArchSpecific() { initializeRegistersParentMap(); } void Capstone2LlvmIrTranslatorX86_impl::initializeRegNameMap() { std::map<uint32_t, std::string> r2n = { // x86_reg_rflags // {X86_REG_CF, "cf"}, {X86_REG_PF, "pf"}, {X86_REG_AF, "az"}, {X86_REG_ZF, "zf"}, {X86_REG_SF, "sf"}, {X86_REG_TF, "tf"}, {X86_REG_IF, "if"}, {X86_REG_DF, "df"}, {X86_REG_OF, "of"}, {X86_REG_IOPL, "iopl"}, {X86_REG_NT, "nt"}, {X86_REG_RF, "rf"}, {X86_REG_VM, "vm"}, {X86_REG_AC, "ac"}, {X86_REG_VIF, "vif"}, {X86_REG_VIP, "vip"}, {X86_REG_ID, "id"}, // x87_reg_status // {X87_REG_IE, "fpu_stat_IE"}, {X87_REG_DE, "fpu_stat_DE"}, {X87_REG_ZE, "fpu_stat_ZE"}, {X87_REG_OE, "fpu_stat_OE"}, {X87_REG_UE, "fpu_stat_UE"}, {X87_REG_PE, "fpu_stat_PE"}, {X87_REG_SF, "fpu_stat_SF"}, {X87_REG_ES, "fpu_stat_ES"}, {X87_REG_C0, "fpu_stat_C0"}, {X87_REG_C1, "fpu_stat_C1"}, {X87_REG_C2, "fpu_stat_C2"}, {X87_REG_C3, "fpu_stat_C3"}, {X87_REG_TOP, "fpu_stat_TOP"}, {X87_REG_B, "fpu_stat_B"}, // x87_reg_control // {X87_REG_IM, "fpu_control_IM"}, {X87_REG_DM, "fpu_control_DM"}, {X87_REG_ZM, "fpu_control_ZM"}, {X87_REG_OM, "fpu_control_OM"}, {X87_REG_UM, "fpu_control_UM"}, {X87_REG_PM, "fpu_control_PM"}, {X87_REG_PC, "fpu_control_PC"}, {X87_REG_RC, "fpu_control_RC"}, {X87_REG_X, "fpu_control_X"}, // x87_reg_tag // {X87_REG_TAG0, "fpu_tag_0"}, {X87_REG_TAG1, "fpu_tag_1"}, {X87_REG_TAG2, "fpu_tag_2"}, {X87_REG_TAG3, "fpu_tag_3"}, {X87_REG_TAG4, "fpu_tag_4"}, {X87_REG_TAG5, "fpu_tag_5"}, {X87_REG_TAG6, "fpu_tag_6"}, {X87_REG_TAG7, "fpu_tag_7"}, // FPU data registers // They are named as ST(X) in Capstone, which is not good for us. // {X86_REG_ST0, "st0"}, {X86_REG_ST1, "st1"}, {X86_REG_ST2, "st2"}, {X86_REG_ST3, "st3"}, {X86_REG_ST4, "st4"}, {X86_REG_ST5, "st5"}, {X86_REG_ST6, "st6"}, {X86_REG_ST7, "st7"}, }; _reg2name = std::move(r2n); } void Capstone2LlvmIrTranslatorX86_impl::initializeRegTypeMap() { auto* i1 = llvm::IntegerType::getInt1Ty(_module->getContext()); auto* i2 = llvm::IntegerType::getIntNTy(_module->getContext(), 2); auto* i3 = llvm::IntegerType::getIntNTy(_module->getContext(), 3); auto* i8 = llvm::IntegerType::getInt8Ty(_module->getContext()); auto* i16 = llvm::IntegerType::getInt16Ty(_module->getContext()); auto* i32 = llvm::IntegerType::getInt32Ty(_module->getContext()); auto* i64 = llvm::IntegerType::getInt64Ty(_module->getContext()); auto* i128 = llvm::IntegerType::getInt128Ty(_module->getContext()); auto* i256 = llvm::IntegerType::getIntNTy(_module->getContext(), 256); auto* i512 = llvm::IntegerType::getIntNTy(_module->getContext(), 512); auto* fp64 = llvm::IntegerType::getDoubleTy(_module->getContext()); auto* fp80 = llvm::IntegerType::getX86_FP80Ty(_module->getContext()); auto* defTy = _origBasicMode == CS_MODE_64 ? i64 : i32; std::map<uint32_t, llvm::Type*> r2t = { // x86_reg // {X86_REG_AH, i8}, {X86_REG_AL, i8}, {X86_REG_CH, i8}, {X86_REG_CL, i8}, {X86_REG_DH, i8}, {X86_REG_DL, i8}, {X86_REG_BH, i8}, {X86_REG_BL, i8}, {X86_REG_SPL, i8}, {X86_REG_BPL, i8}, {X86_REG_DIL, i8}, {X86_REG_SIL, i8}, {X86_REG_R8B, i8}, {X86_REG_R9B, i8}, {X86_REG_R10B, i8}, {X86_REG_R11B, i8}, {X86_REG_R12B, i8}, {X86_REG_R13B, i8}, {X86_REG_R14B, i8}, {X86_REG_R15B, i8}, {X86_REG_AX, i16}, {X86_REG_CX, i16}, {X86_REG_DX, i16}, {X86_REG_BP, i16}, {X86_REG_BX, i16}, {X86_REG_DI, i16}, {X86_REG_SP, i16}, {X86_REG_SI, i16}, {X86_REG_SS, i16}, {X86_REG_CS, i16}, {X86_REG_DS, i16}, {X86_REG_ES, i16}, {X86_REG_FS, i16}, {X86_REG_GS, i16}, {X86_REG_R8W, i16}, {X86_REG_R9W, i16}, {X86_REG_R10W, i16}, {X86_REG_R11W, i16}, {X86_REG_R12W, i16}, {X86_REG_R13W, i16}, {X86_REG_R14W, i16}, {X86_REG_R15W, i16}, {X86_REG_IP, i16}, {X86_REG_EAX, i32}, {X86_REG_EBP, i32}, {X86_REG_EBX, i32}, {X86_REG_ECX, i32}, {X86_REG_EDI, i32}, {X86_REG_EDX, i32}, {X86_REG_ESI, i32}, {X86_REG_ESP, i32}, {X86_REG_R8D, i32}, {X86_REG_R9D, i32}, {X86_REG_R10D, i32}, {X86_REG_R11D, i32}, {X86_REG_R12D, i32}, {X86_REG_R13D, i32}, {X86_REG_R14D, i32}, {X86_REG_R15D, i32}, {X86_REG_EIP, i32}, {X86_REG_EIZ, i32}, {X86_REG_RAX, i64}, {X86_REG_RBP, i64}, {X86_REG_RBX, i64}, {X86_REG_RCX, i64}, {X86_REG_RDI, i64}, {X86_REG_RDX, i64}, {X86_REG_RIP, i64}, {X86_REG_RIZ, i64}, {X86_REG_RSI, i64}, {X86_REG_RSP, i64}, {X86_REG_R8, i64}, {X86_REG_R9, i64}, {X86_REG_R10, i64}, {X86_REG_R11, i64}, {X86_REG_R12, i64}, {X86_REG_R13, i64}, {X86_REG_R14, i64}, {X86_REG_R15, i64}, {X86_REG_ST0, fp80}, {X86_REG_ST1, fp80}, {X86_REG_ST2, fp80}, {X86_REG_ST3, fp80}, {X86_REG_ST4, fp80}, {X86_REG_ST5, fp80}, {X86_REG_ST6, fp80}, {X86_REG_ST7, fp80}, {X86_REG_FP0, fp64}, {X86_REG_FP1, fp64}, {X86_REG_FP2, fp64}, {X86_REG_FP3, fp64}, {X86_REG_FP4, fp64}, {X86_REG_FP5, fp64}, {X86_REG_FP6, fp64}, {X86_REG_FP7, fp64}, {X86_REG_EFLAGS, defTy}, {X86_REG_DR0, defTy}, {X86_REG_DR1, defTy}, {X86_REG_DR2, defTy}, {X86_REG_DR3, defTy}, {X86_REG_DR4, defTy}, {X86_REG_DR5, defTy}, {X86_REG_DR6, defTy}, {X86_REG_DR7, defTy}, {X86_REG_DR8, defTy}, {X86_REG_DR9, defTy}, {X86_REG_DR10, defTy}, {X86_REG_DR11, defTy}, {X86_REG_DR12, defTy}, {X86_REG_DR13, defTy}, {X86_REG_DR14, defTy}, {X86_REG_DR15, defTy}, {X86_REG_CR0, defTy}, {X86_REG_CR1, defTy}, {X86_REG_CR2, defTy}, {X86_REG_CR3, defTy}, {X86_REG_CR4, defTy}, {X86_REG_CR5, defTy}, {X86_REG_CR6, defTy}, {X86_REG_CR7, defTy}, {X86_REG_CR8, defTy}, {X86_REG_CR9, defTy}, {X86_REG_CR10, defTy}, {X86_REG_CR11, defTy}, {X86_REG_CR12, defTy}, {X86_REG_CR13, defTy}, {X86_REG_CR14, defTy}, {X86_REG_CR15, defTy}, {X86_REG_FPSW, defTy}, // opmask registers (AVX-512) {X86_REG_K0, i64}, {X86_REG_K1, i64}, {X86_REG_K2, i64}, {X86_REG_K3, i64}, {X86_REG_K4, i64}, {X86_REG_K5, i64}, {X86_REG_K6, i64}, {X86_REG_K7, i64}, // MMX {X86_REG_MM0, i64}, {X86_REG_MM1, i64}, {X86_REG_MM2, i64}, {X86_REG_MM3, i64}, {X86_REG_MM4, i64}, {X86_REG_MM5, i64}, {X86_REG_MM6, i64}, {X86_REG_MM7, i64}, // XMM {X86_REG_XMM0, i128}, {X86_REG_XMM1, i128}, {X86_REG_XMM2, i128}, {X86_REG_XMM3, i128}, {X86_REG_XMM4, i128}, {X86_REG_XMM5, i128}, {X86_REG_XMM6, i128}, {X86_REG_XMM7, i128}, {X86_REG_XMM8, i128}, {X86_REG_XMM9, i128}, {X86_REG_XMM10, i128}, {X86_REG_XMM11, i128}, {X86_REG_XMM12, i128}, {X86_REG_XMM13, i128}, {X86_REG_XMM14, i128}, {X86_REG_XMM15, i128}, {X86_REG_XMM16, i128}, {X86_REG_XMM17, i128}, {X86_REG_XMM18, i128}, {X86_REG_XMM19, i128}, {X86_REG_XMM20, i128}, {X86_REG_XMM21, i128}, {X86_REG_XMM22, i128}, {X86_REG_XMM23, i128}, {X86_REG_XMM24, i128}, {X86_REG_XMM25, i128}, {X86_REG_XMM26, i128}, {X86_REG_XMM27, i128}, {X86_REG_XMM28, i128}, {X86_REG_XMM29, i128}, {X86_REG_XMM30, i128}, {X86_REG_XMM31, i128}, // YMM {X86_REG_YMM0, i256}, {X86_REG_YMM1, i256}, {X86_REG_YMM2, i256}, {X86_REG_YMM3, i256}, {X86_REG_YMM4, i256}, {X86_REG_YMM5, i256}, {X86_REG_YMM6, i256}, {X86_REG_YMM7, i256}, {X86_REG_YMM8, i256}, {X86_REG_YMM9, i256}, {X86_REG_YMM10, i256}, {X86_REG_YMM11, i256}, {X86_REG_YMM12, i256}, {X86_REG_YMM13, i256}, {X86_REG_YMM14, i256}, {X86_REG_YMM15, i256}, {X86_REG_YMM16, i256}, {X86_REG_YMM17, i256}, {X86_REG_YMM18, i256}, {X86_REG_YMM19, i256}, {X86_REG_YMM20, i256}, {X86_REG_YMM21, i256}, {X86_REG_YMM22, i256}, {X86_REG_YMM23, i256}, {X86_REG_YMM24, i256}, {X86_REG_YMM25, i256}, {X86_REG_YMM26, i256}, {X86_REG_YMM27, i256}, {X86_REG_YMM28, i256}, {X86_REG_YMM29, i256}, {X86_REG_YMM30, i256}, {X86_REG_YMM31, i256}, // ZMM {X86_REG_ZMM0, i512}, {X86_REG_ZMM1, i512}, {X86_REG_ZMM2, i512}, {X86_REG_ZMM3, i512}, {X86_REG_ZMM4, i512}, {X86_REG_ZMM5, i512}, {X86_REG_ZMM6, i512}, {X86_REG_ZMM7, i512}, {X86_REG_ZMM8, i512}, {X86_REG_ZMM9, i512}, {X86_REG_ZMM10, i512}, {X86_REG_ZMM11, i512}, {X86_REG_ZMM12, i512}, {X86_REG_ZMM13, i512}, {X86_REG_ZMM14, i512}, {X86_REG_ZMM15, i512}, {X86_REG_ZMM16, i512}, {X86_REG_ZMM17, i512}, {X86_REG_ZMM18, i512}, {X86_REG_ZMM19, i512}, {X86_REG_ZMM20, i512}, {X86_REG_ZMM21, i512}, {X86_REG_ZMM22, i512}, {X86_REG_ZMM23, i512}, {X86_REG_ZMM24, i512}, {X86_REG_ZMM25, i512}, {X86_REG_ZMM26, i512}, {X86_REG_ZMM27, i512}, {X86_REG_ZMM28, i512}, {X86_REG_ZMM29, i512}, {X86_REG_ZMM30, i512}, {X86_REG_ZMM31, i512}, // x86_reg_rflags // {X86_REG_CF, i1}, {X86_REG_PF, i1}, {X86_REG_AF, i1}, {X86_REG_ZF, i1}, {X86_REG_SF, i1}, {X86_REG_TF, i1}, {X86_REG_IF, i1}, {X86_REG_DF, i1}, {X86_REG_OF, i1}, {X86_REG_IOPL, i2}, {X86_REG_NT, i1}, {X86_REG_RF, i1}, {X86_REG_VM, i1}, {X86_REG_AC, i1}, {X86_REG_VIF, i1}, {X86_REG_VIP, i1}, {X86_REG_ID, i1}, // x87_reg_status // {X87_REG_IE, i1}, {X87_REG_DE, i1}, {X87_REG_ZE, i1}, {X87_REG_OE, i1}, {X87_REG_UE, i1}, {X87_REG_PE, i1}, {X87_REG_SF, i1}, {X87_REG_ES, i1}, {X87_REG_C0, i1}, {X87_REG_C1, i1}, {X87_REG_C2, i1}, {X87_REG_C3, i1}, {X87_REG_TOP, i3}, {X87_REG_B, i1}, // x87_reg_control // {X87_REG_IM, i1}, {X87_REG_DM, i1}, {X87_REG_ZM, i1}, {X87_REG_OM, i1}, {X87_REG_UM, i1}, {X87_REG_PM, i1}, {X87_REG_PC, i2}, {X87_REG_RC, i2}, {X87_REG_X, i1}, // x87_reg_tag // {X87_REG_TAG0, i2}, {X87_REG_TAG1, i2}, {X87_REG_TAG2, i2}, {X87_REG_TAG3, i2}, {X87_REG_TAG4, i2}, {X87_REG_TAG5, i2}, {X87_REG_TAG6, i2}, {X87_REG_TAG7, i2}, }; _reg2type = std::move(r2t); } void Capstone2LlvmIrTranslatorX86_impl::initializePseudoCallInstructionIDs() { _callInsnIds = { X86_INS_CALL, X86_INS_LCALL, }; _returnInsnIds = { X86_INS_RET, X86_INS_RETF, X86_INS_RETFQ }; _branchInsnIds = { X86_INS_JMP, X86_INS_LJMP, }; _condBranchInsnIds = { X86_INS_JCXZ, X86_INS_JECXZ, X86_INS_JRCXZ, // X86_INS_LOOP, X86_INS_LOOPE, X86_INS_LOOPNE, // X86_INS_JAE, X86_INS_JA, X86_INS_JBE, X86_INS_JB, X86_INS_JE, X86_INS_JGE, X86_INS_JG, X86_INS_JLE, X86_INS_JL, X86_INS_JNE, X86_INS_JNO, X86_INS_JNP, X86_INS_JNS, X86_INS_JO, X86_INS_JP, X86_INS_JS, }; _controlFlowInsnIds = { // Currently, all instructions can be categorized based on their // IDs alone. }; } // //============================================================================== // x86-specific methods. //============================================================================== // void Capstone2LlvmIrTranslatorX86_impl::initializeRegistersParentMapToOther( const std::vector<x86_reg>& rs, x86_reg other) { for (auto r : rs) { if (r >= _reg2parentMap.size()) { throw GenericError("Register out of range."); } _reg2parentMap[r] = other; } } void Capstone2LlvmIrTranslatorX86_impl::initializeRegistersParentMap() { switch (_origBasicMode) { case CS_MODE_16: initializeRegistersParentMap16(); break; case CS_MODE_32: initializeRegistersParentMap32(); break; case CS_MODE_64: initializeRegistersParentMap64(); break; default: { throw GenericError("Unhandled mode in " "initializeRegistersParentMap()."); break; } } } void Capstone2LlvmIrTranslatorX86_impl::initializeRegistersParentMap16() { // Last element in vector is its own parent. std::vector<std::vector<x86_reg>> rss = { {X86_REG_AH, X86_REG_AL, X86_REG_AX}, {X86_REG_CH, X86_REG_CL, X86_REG_CX}, {X86_REG_DH, X86_REG_DL, X86_REG_DX}, {X86_REG_BH, X86_REG_BL, X86_REG_BX}, {X86_REG_SPL, X86_REG_SP}, {X86_REG_BPL, X86_REG_BP}, {X86_REG_SIL, X86_REG_SI}, {X86_REG_DIL, X86_REG_DI}, {X86_REG_IP}, }; for (std::vector<x86_reg>& rs : rss) { initializeRegistersParentMapToOther(rs, rs.back()); } } void Capstone2LlvmIrTranslatorX86_impl::initializeRegistersParentMap32() { // Last element in vector is its own parent. std::vector<std::vector<x86_reg>> rss = { {X86_REG_AH, X86_REG_AL, X86_REG_AX, X86_REG_EAX}, {X86_REG_CH, X86_REG_CL, X86_REG_CX, X86_REG_ECX}, {X86_REG_DH, X86_REG_DL, X86_REG_DX, X86_REG_EDX}, {X86_REG_BH, X86_REG_BL, X86_REG_BX, X86_REG_EBX}, {X86_REG_SPL, X86_REG_SP, X86_REG_ESP}, {X86_REG_BPL, X86_REG_BP, X86_REG_EBP}, {X86_REG_SIL, X86_REG_SI, X86_REG_ESI}, {X86_REG_DIL, X86_REG_DI, X86_REG_EDI}, {X86_REG_IP, X86_REG_EIP}, {X86_REG_EIZ}, }; for (std::vector<x86_reg>& rs : rss) { initializeRegistersParentMapToOther(rs, rs.back()); } } void Capstone2LlvmIrTranslatorX86_impl::initializeRegistersParentMap64() { // Last element in vector is its own parent. std::vector<std::vector<x86_reg>> rss = { {X86_REG_AH, X86_REG_AL, X86_REG_AX, X86_REG_EAX, X86_REG_RAX}, {X86_REG_CH, X86_REG_CL, X86_REG_CX, X86_REG_ECX, X86_REG_RCX}, {X86_REG_DH, X86_REG_DL, X86_REG_DX, X86_REG_EDX, X86_REG_RDX}, {X86_REG_BH, X86_REG_BL, X86_REG_BX, X86_REG_EBX, X86_REG_RBX}, {X86_REG_SPL, X86_REG_SP, X86_REG_ESP, X86_REG_RSP}, {X86_REG_BPL, X86_REG_BP, X86_REG_EBP, X86_REG_RBP}, {X86_REG_SIL, X86_REG_SI, X86_REG_ESI, X86_REG_RSI}, {X86_REG_DIL, X86_REG_DI, X86_REG_EDI, X86_REG_RDI}, {X86_REG_IP, X86_REG_EIP, X86_REG_RIP}, {X86_REG_EIZ, X86_REG_RIZ}, {X86_REG_R8B, X86_REG_R8W, X86_REG_R8D, X86_REG_R8}, {X86_REG_R9B, X86_REG_R9W, X86_REG_R9D, X86_REG_R9}, {X86_REG_R10B, X86_REG_R10W, X86_REG_R10D, X86_REG_R10}, {X86_REG_R11B, X86_REG_R11W, X86_REG_R11D, X86_REG_R11}, {X86_REG_R12B, X86_REG_R12W, X86_REG_R12D, X86_REG_R12}, {X86_REG_R13B, X86_REG_R13W, X86_REG_R13D, X86_REG_R13}, {X86_REG_R14B, X86_REG_R14W, X86_REG_R14D, X86_REG_R14}, {X86_REG_R15B, X86_REG_R15W, X86_REG_R15D, X86_REG_R15} }; for (std::vector<x86_reg>& rs : rss) { initializeRegistersParentMapToOther(rs, rs.back()); } } // //============================================================================== // Instruction translation map initialization. //============================================================================== // std::map< std::size_t, void (Capstone2LlvmIrTranslatorX86_impl::*)( cs_insn* i, cs_x86*, llvm::IRBuilder<>&)> Capstone2LlvmIrTranslatorX86_impl::_i2fm = { {X86_INS_INVALID, nullptr}, {X86_INS_AAA, &Capstone2LlvmIrTranslatorX86_impl::translateAaa}, {X86_INS_AAD, &Capstone2LlvmIrTranslatorX86_impl::translateAad}, {X86_INS_AAM, &Capstone2LlvmIrTranslatorX86_impl::translateAam}, {X86_INS_AAS, &Capstone2LlvmIrTranslatorX86_impl::translateAaa}, {X86_INS_FABS, &Capstone2LlvmIrTranslatorX86_impl::translateFabs}, {X86_INS_ADC, &Capstone2LlvmIrTranslatorX86_impl::translateAdc}, {X86_INS_ADCX, &Capstone2LlvmIrTranslatorX86_impl::translateAdc}, {X86_INS_ADD, &Capstone2LlvmIrTranslatorX86_impl::translateAdd}, {X86_INS_ADDPD, nullptr}, {X86_INS_ADDPS, nullptr}, {X86_INS_ADDSD, nullptr}, {X86_INS_ADDSS, nullptr}, {X86_INS_ADDSUBPD, nullptr}, {X86_INS_ADDSUBPS, nullptr}, {X86_INS_FADD, &Capstone2LlvmIrTranslatorX86_impl::translateFadd}, {X86_INS_FIADD, &Capstone2LlvmIrTranslatorX86_impl::translateFadd}, {X86_INS_FADDP, &Capstone2LlvmIrTranslatorX86_impl::translateFadd}, {X86_INS_ADOX, &Capstone2LlvmIrTranslatorX86_impl::translateAdc}, {X86_INS_AESDECLAST, nullptr}, {X86_INS_AESDEC, nullptr}, {X86_INS_AESENCLAST, nullptr}, {X86_INS_AESENC, nullptr}, {X86_INS_AESIMC, nullptr}, {X86_INS_AESKEYGENASSIST, nullptr}, {X86_INS_AND, &Capstone2LlvmIrTranslatorX86_impl::translateAnd}, {X86_INS_ANDN, nullptr}, {X86_INS_ANDNPD, nullptr}, {X86_INS_ANDNPS, nullptr}, {X86_INS_ANDPD, nullptr}, {X86_INS_ANDPS, nullptr}, {X86_INS_ARPL, nullptr}, {X86_INS_BEXTR, nullptr}, {X86_INS_BLCFILL, nullptr}, {X86_INS_BLCI, nullptr}, {X86_INS_BLCIC, nullptr}, {X86_INS_BLCMSK, nullptr}, {X86_INS_BLCS, nullptr}, {X86_INS_BLENDPD, nullptr}, {X86_INS_BLENDPS, nullptr}, {X86_INS_BLENDVPD, nullptr}, {X86_INS_BLENDVPS, nullptr}, {X86_INS_BLSFILL, nullptr}, {X86_INS_BLSI, nullptr}, {X86_INS_BLSIC, nullptr}, {X86_INS_BLSMSK, nullptr}, {X86_INS_BLSR, nullptr}, {X86_INS_BOUND, nullptr}, {X86_INS_BSF, &Capstone2LlvmIrTranslatorX86_impl::translateBsf}, {X86_INS_BSR, &Capstone2LlvmIrTranslatorX86_impl::translateBsf}, {X86_INS_BSWAP, &Capstone2LlvmIrTranslatorX86_impl::translateBswap}, {X86_INS_BT, &Capstone2LlvmIrTranslatorX86_impl::translateBt}, {X86_INS_BTC, &Capstone2LlvmIrTranslatorX86_impl::translateBtc}, {X86_INS_BTR, &Capstone2LlvmIrTranslatorX86_impl::translateBtr}, {X86_INS_BTS, &Capstone2LlvmIrTranslatorX86_impl::translateBts}, {X86_INS_BZHI, nullptr}, {X86_INS_CALL, &Capstone2LlvmIrTranslatorX86_impl::translateCall}, {X86_INS_CBW, &Capstone2LlvmIrTranslatorX86_impl::translateCbw}, {X86_INS_CDQ, &Capstone2LlvmIrTranslatorX86_impl::translateCdq}, {X86_INS_CDQE, &Capstone2LlvmIrTranslatorX86_impl::translateCdqe}, {X86_INS_FCHS, &Capstone2LlvmIrTranslatorX86_impl::translateFchs}, {X86_INS_CLAC, nullptr}, {X86_INS_CLC, &Capstone2LlvmIrTranslatorX86_impl::translateClc}, {X86_INS_CLD, &Capstone2LlvmIrTranslatorX86_impl::translateCld}, {X86_INS_CLFLUSH, nullptr}, {X86_INS_CLFLUSHOPT, nullptr}, {X86_INS_CLGI, nullptr}, {X86_INS_CLI, &Capstone2LlvmIrTranslatorX86_impl::translateCli}, {X86_INS_CLTS, nullptr}, {X86_INS_CLWB, nullptr}, {X86_INS_CMC, &Capstone2LlvmIrTranslatorX86_impl::translateCmc}, {X86_INS_CMOVA, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVAE, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVB, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVBE, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_FCMOVBE, nullptr}, {X86_INS_FCMOVB, nullptr}, {X86_INS_CMOVE, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_FCMOVE, nullptr}, {X86_INS_CMOVG, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVGE, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVL, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVLE, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_FCMOVNBE, nullptr}, {X86_INS_FCMOVNB, nullptr}, {X86_INS_CMOVNE, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_FCMOVNE, nullptr}, {X86_INS_CMOVNO, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVNP, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_FCMOVNU, nullptr}, {X86_INS_CMOVNS, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVO, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMOVP, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_FCMOVU, nullptr}, {X86_INS_CMOVS, &Capstone2LlvmIrTranslatorX86_impl::translateCMovCc}, {X86_INS_CMP, &Capstone2LlvmIrTranslatorX86_impl::translateSub}, {X86_INS_CMPSB, &Capstone2LlvmIrTranslatorX86_impl::translateCompareString}, {X86_INS_CMPSQ, &Capstone2LlvmIrTranslatorX86_impl::translateCompareString}, {X86_INS_CMPSW, &Capstone2LlvmIrTranslatorX86_impl::translateCompareString}, {X86_INS_CMPXCHG16B, &Capstone2LlvmIrTranslatorX86_impl::translateCmpxchg16b}, {X86_INS_CMPXCHG, &Capstone2LlvmIrTranslatorX86_impl::translateCmpxchg}, {X86_INS_CMPXCHG8B, &Capstone2LlvmIrTranslatorX86_impl::translateCmpxchg8b}, {X86_INS_COMISD, nullptr}, {X86_INS_COMISS, nullptr}, {X86_INS_FCOMP, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FCOMIP, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FCOMI, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FCOM, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FCOS, &Capstone2LlvmIrTranslatorX86_impl::translateFcos}, {X86_INS_CPUID, &Capstone2LlvmIrTranslatorX86_impl::translateCpuid}, {X86_INS_CQO, &Capstone2LlvmIrTranslatorX86_impl::translateCqo}, {X86_INS_CRC32, nullptr}, {X86_INS_CVTDQ2PD, nullptr}, {X86_INS_CVTDQ2PS, nullptr}, {X86_INS_CVTPD2DQ, nullptr}, {X86_INS_CVTPD2PS, nullptr}, {X86_INS_CVTPS2DQ, nullptr}, {X86_INS_CVTPS2PD, nullptr}, {X86_INS_CVTSD2SI, nullptr}, {X86_INS_CVTSD2SS, nullptr}, {X86_INS_CVTSI2SD, nullptr}, {X86_INS_CVTSI2SS, nullptr}, {X86_INS_CVTSS2SD, nullptr}, {X86_INS_CVTSS2SI, nullptr}, {X86_INS_CVTTPD2DQ, nullptr}, {X86_INS_CVTTPS2DQ, nullptr}, {X86_INS_CVTTSD2SI, nullptr}, {X86_INS_CVTTSS2SI, nullptr}, {X86_INS_CWD, &Capstone2LlvmIrTranslatorX86_impl::translateCwd}, {X86_INS_CWDE, &Capstone2LlvmIrTranslatorX86_impl::translateCwde}, {X86_INS_DAA, &Capstone2LlvmIrTranslatorX86_impl::translateDaaDas}, {X86_INS_DAS, &Capstone2LlvmIrTranslatorX86_impl::translateDaaDas}, {X86_INS_DATA16, nullptr}, {X86_INS_DEC, &Capstone2LlvmIrTranslatorX86_impl::translateDec}, {X86_INS_DIV, &Capstone2LlvmIrTranslatorX86_impl::translateDiv}, {X86_INS_DIVPD, nullptr}, {X86_INS_DIVPS, nullptr}, {X86_INS_FDIVR, &Capstone2LlvmIrTranslatorX86_impl::translateFdivr}, {X86_INS_FIDIVR, &Capstone2LlvmIrTranslatorX86_impl::translateFdivr}, {X86_INS_FDIVRP, &Capstone2LlvmIrTranslatorX86_impl::translateFdivr}, {X86_INS_DIVSD, nullptr}, {X86_INS_DIVSS, nullptr}, {X86_INS_FDIV, &Capstone2LlvmIrTranslatorX86_impl::translateFdiv}, {X86_INS_FIDIV, &Capstone2LlvmIrTranslatorX86_impl::translateFdiv}, {X86_INS_FDIVP, &Capstone2LlvmIrTranslatorX86_impl::translateFdiv}, {X86_INS_DPPD, nullptr}, {X86_INS_DPPS, nullptr}, {X86_INS_RET, &Capstone2LlvmIrTranslatorX86_impl::translateRet}, {X86_INS_ENCLS, nullptr}, {X86_INS_ENCLU, nullptr}, {X86_INS_ENTER, &Capstone2LlvmIrTranslatorX86_impl::translateEnter}, {X86_INS_EXTRACTPS, nullptr}, {X86_INS_EXTRQ, nullptr}, {X86_INS_F2XM1, nullptr}, {X86_INS_LCALL, &Capstone2LlvmIrTranslatorX86_impl::translateLcall}, {X86_INS_LJMP, &Capstone2LlvmIrTranslatorX86_impl::translateLjmp}, {X86_INS_FBLD, nullptr}, {X86_INS_FBSTP, nullptr}, {X86_INS_FCOMPP, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FDECSTP, &Capstone2LlvmIrTranslatorX86_impl::translateFdecstp}, {X86_INS_FEMMS, nullptr}, {X86_INS_FFREE, nullptr}, {X86_INS_FICOM, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FICOMP, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FINCSTP, &Capstone2LlvmIrTranslatorX86_impl::translateFincstp}, {X86_INS_FLDCW, &Capstone2LlvmIrTranslatorX86_impl::translateNop}, {X86_INS_FLDENV, nullptr}, {X86_INS_FLDL2E, &Capstone2LlvmIrTranslatorX86_impl::translateFloadConstant}, {X86_INS_FLDL2T, &Capstone2LlvmIrTranslatorX86_impl::translateFloadConstant}, {X86_INS_FLDLG2, &Capstone2LlvmIrTranslatorX86_impl::translateFloadConstant}, {X86_INS_FLDLN2, &Capstone2LlvmIrTranslatorX86_impl::translateFloadConstant}, {X86_INS_FLDPI, &Capstone2LlvmIrTranslatorX86_impl::translateFloadConstant}, {X86_INS_FNCLEX, nullptr}, {X86_INS_FNINIT, &Capstone2LlvmIrTranslatorX86_impl::translateFninit}, {X86_INS_FNOP, &Capstone2LlvmIrTranslatorX86_impl::translateNop}, {X86_INS_FNSTCW, &Capstone2LlvmIrTranslatorX86_impl::translateNop}, {X86_INS_FNSTSW, nullptr}, {X86_INS_FPATAN, nullptr}, {X86_INS_FPREM, nullptr}, {X86_INS_FPREM1, nullptr}, {X86_INS_FPTAN, nullptr}, {X86_INS_FFREEP, nullptr}, {X86_INS_FRNDINT, &Capstone2LlvmIrTranslatorX86_impl::translateFrndint}, {X86_INS_FRSTOR, nullptr}, {X86_INS_FNSAVE, nullptr}, {X86_INS_FSCALE, nullptr}, {X86_INS_FSETPM, nullptr}, {X86_INS_FSINCOS, &Capstone2LlvmIrTranslatorX86_impl::translateFsincos}, {X86_INS_FNSTENV, nullptr}, {X86_INS_FXAM, nullptr}, {X86_INS_FXRSTOR, nullptr}, {X86_INS_FXRSTOR64, nullptr}, {X86_INS_FXSAVE, nullptr}, {X86_INS_FXSAVE64, nullptr}, {X86_INS_FXTRACT, nullptr}, {X86_INS_FYL2X, nullptr}, {X86_INS_FYL2XP1, nullptr}, {X86_INS_MOVAPD, nullptr}, {X86_INS_MOVAPS, nullptr}, {X86_INS_ORPD, nullptr}, {X86_INS_ORPS, nullptr}, {X86_INS_VMOVAPD, nullptr}, {X86_INS_VMOVAPS, nullptr}, {X86_INS_XORPD, nullptr}, {X86_INS_XORPS, nullptr}, {X86_INS_GETSEC, nullptr}, {X86_INS_HADDPD, nullptr}, {X86_INS_HADDPS, nullptr}, {X86_INS_HLT, nullptr}, {X86_INS_HSUBPD, nullptr}, {X86_INS_HSUBPS, nullptr}, {X86_INS_IDIV, &Capstone2LlvmIrTranslatorX86_impl::translateDiv}, {X86_INS_FILD, &Capstone2LlvmIrTranslatorX86_impl::translateFld}, {X86_INS_IMUL, &Capstone2LlvmIrTranslatorX86_impl::translateImul}, {X86_INS_IN, nullptr}, {X86_INS_INC, &Capstone2LlvmIrTranslatorX86_impl::translateInc}, {X86_INS_INSB, &Capstone2LlvmIrTranslatorX86_impl::translateIns}, {X86_INS_INSERTPS, nullptr}, {X86_INS_INSERTQ, nullptr}, {X86_INS_INSD, &Capstone2LlvmIrTranslatorX86_impl::translateIns}, {X86_INS_INSW, &Capstone2LlvmIrTranslatorX86_impl::translateIns}, {X86_INS_INT, nullptr}, {X86_INS_INT1, nullptr}, {X86_INS_INT3, nullptr}, {X86_INS_INTO, nullptr}, {X86_INS_INVD, nullptr}, {X86_INS_INVEPT, nullptr}, {X86_INS_INVLPG, nullptr}, {X86_INS_INVLPGA, nullptr}, {X86_INS_INVPCID, nullptr}, {X86_INS_INVVPID, nullptr}, {X86_INS_IRET, nullptr}, {X86_INS_IRETD, nullptr}, {X86_INS_IRETQ, nullptr}, {X86_INS_FISTTP, nullptr}, {X86_INS_FIST, &Capstone2LlvmIrTranslatorX86_impl::translateFist}, {X86_INS_FISTP, &Capstone2LlvmIrTranslatorX86_impl::translateFist}, {X86_INS_UCOMISD, nullptr}, {X86_INS_UCOMISS, nullptr}, {X86_INS_VCOMISD, nullptr}, {X86_INS_VCOMISS, nullptr}, {X86_INS_VCVTSD2SS, nullptr}, {X86_INS_VCVTSI2SD, nullptr}, {X86_INS_VCVTSI2SS, nullptr}, {X86_INS_VCVTSS2SD, nullptr}, {X86_INS_VCVTTSD2SI, nullptr}, {X86_INS_VCVTTSD2USI, nullptr}, {X86_INS_VCVTTSS2SI, nullptr}, {X86_INS_VCVTTSS2USI, nullptr}, {X86_INS_VCVTUSI2SD, nullptr}, {X86_INS_VCVTUSI2SS, nullptr}, {X86_INS_VUCOMISD, nullptr}, {X86_INS_VUCOMISS, nullptr}, {X86_INS_JAE, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JA, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JBE, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JB, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JCXZ, &Capstone2LlvmIrTranslatorX86_impl::translateJecxz}, {X86_INS_JECXZ, &Capstone2LlvmIrTranslatorX86_impl::translateJecxz}, {X86_INS_JE, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JGE, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JG, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JLE, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JL, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JMP, &Capstone2LlvmIrTranslatorX86_impl::translateJmp}, {X86_INS_JNE, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JNO, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JNP, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JNS, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JO, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JP, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_JRCXZ, &Capstone2LlvmIrTranslatorX86_impl::translateJecxz}, {X86_INS_JS, &Capstone2LlvmIrTranslatorX86_impl::translateJCc}, {X86_INS_KANDB, nullptr}, {X86_INS_KANDD, nullptr}, {X86_INS_KANDNB, nullptr}, {X86_INS_KANDND, nullptr}, {X86_INS_KANDNQ, nullptr}, {X86_INS_KANDNW, nullptr}, {X86_INS_KANDQ, nullptr}, {X86_INS_KANDW, nullptr}, {X86_INS_KMOVB, nullptr}, {X86_INS_KMOVD, nullptr}, {X86_INS_KMOVQ, nullptr}, {X86_INS_KMOVW, nullptr}, {X86_INS_KNOTB, nullptr}, {X86_INS_KNOTD, nullptr}, {X86_INS_KNOTQ, nullptr}, {X86_INS_KNOTW, nullptr}, {X86_INS_KORB, nullptr}, {X86_INS_KORD, nullptr}, {X86_INS_KORQ, nullptr}, {X86_INS_KORTESTB, nullptr}, {X86_INS_KORTESTD, nullptr}, {X86_INS_KORTESTQ, nullptr}, {X86_INS_KORTESTW, nullptr}, {X86_INS_KORW, nullptr}, {X86_INS_KSHIFTLB, nullptr}, {X86_INS_KSHIFTLD, nullptr}, {X86_INS_KSHIFTLQ, nullptr}, {X86_INS_KSHIFTLW, nullptr}, {X86_INS_KSHIFTRB, nullptr}, {X86_INS_KSHIFTRD, nullptr}, {X86_INS_KSHIFTRQ, nullptr}, {X86_INS_KSHIFTRW, nullptr}, {X86_INS_KUNPCKBW, nullptr}, {X86_INS_KXNORB, nullptr}, {X86_INS_KXNORD, nullptr}, {X86_INS_KXNORQ, nullptr}, {X86_INS_KXNORW, nullptr}, {X86_INS_KXORB, nullptr}, {X86_INS_KXORD, nullptr}, {X86_INS_KXORQ, nullptr}, {X86_INS_KXORW, nullptr}, {X86_INS_LAHF, &Capstone2LlvmIrTranslatorX86_impl::translateLahf}, {X86_INS_LAR, nullptr}, {X86_INS_LDDQU, nullptr}, {X86_INS_LDMXCSR, nullptr}, {X86_INS_LDS, &Capstone2LlvmIrTranslatorX86_impl::translateLoadFarPtr}, {X86_INS_FLDZ, &Capstone2LlvmIrTranslatorX86_impl::translateFloadConstant}, {X86_INS_FLD1, &Capstone2LlvmIrTranslatorX86_impl::translateFloadConstant}, {X86_INS_FLD, &Capstone2LlvmIrTranslatorX86_impl::translateFld}, {X86_INS_LEA, &Capstone2LlvmIrTranslatorX86_impl::translateLea}, {X86_INS_LEAVE, &Capstone2LlvmIrTranslatorX86_impl::translateLeave}, {X86_INS_LES, &Capstone2LlvmIrTranslatorX86_impl::translateLoadFarPtr}, {X86_INS_LFENCE, nullptr}, {X86_INS_LFS, &Capstone2LlvmIrTranslatorX86_impl::translateLoadFarPtr}, {X86_INS_LGDT, nullptr}, {X86_INS_LGS, &Capstone2LlvmIrTranslatorX86_impl::translateLoadFarPtr}, {X86_INS_LIDT, nullptr}, {X86_INS_LLDT, nullptr}, {X86_INS_LMSW, nullptr}, {X86_INS_OR, &Capstone2LlvmIrTranslatorX86_impl::translateOr}, {X86_INS_SUB, &Capstone2LlvmIrTranslatorX86_impl::translateSub}, {X86_INS_XOR, &Capstone2LlvmIrTranslatorX86_impl::translateXor}, {X86_INS_LODSB, &Capstone2LlvmIrTranslatorX86_impl::translateLoadString}, {X86_INS_LODSD, &Capstone2LlvmIrTranslatorX86_impl::translateLoadString}, {X86_INS_LODSQ, &Capstone2LlvmIrTranslatorX86_impl::translateLoadString}, {X86_INS_LODSW, &Capstone2LlvmIrTranslatorX86_impl::translateLoadString}, {X86_INS_LOOP, &Capstone2LlvmIrTranslatorX86_impl::translateLoop}, {X86_INS_LOOPE, &Capstone2LlvmIrTranslatorX86_impl::translateLoop}, {X86_INS_LOOPNE, &Capstone2LlvmIrTranslatorX86_impl::translateLoop}, {X86_INS_RETF, &Capstone2LlvmIrTranslatorX86_impl::translateRet}, {X86_INS_RETFQ, &Capstone2LlvmIrTranslatorX86_impl::translateRet}, {X86_INS_LSL, nullptr}, {X86_INS_LSS, &Capstone2LlvmIrTranslatorX86_impl::translateLoadFarPtr}, {X86_INS_LTR, nullptr}, {X86_INS_XADD, &Capstone2LlvmIrTranslatorX86_impl::translateAdd}, {X86_INS_LZCNT, nullptr}, {X86_INS_MASKMOVDQU, nullptr}, {X86_INS_MAXPD, nullptr}, {X86_INS_MAXPS, nullptr}, {X86_INS_MAXSD, nullptr}, {X86_INS_MAXSS, nullptr}, {X86_INS_MFENCE, nullptr}, {X86_INS_MINPD, nullptr}, {X86_INS_MINPS, nullptr}, {X86_INS_MINSD, nullptr}, {X86_INS_MINSS, nullptr}, {X86_INS_CVTPD2PI, nullptr}, {X86_INS_CVTPI2PD, nullptr}, {X86_INS_CVTPI2PS, nullptr}, {X86_INS_CVTPS2PI, nullptr}, {X86_INS_CVTTPD2PI, nullptr}, {X86_INS_CVTTPS2PI, nullptr}, {X86_INS_EMMS, nullptr}, {X86_INS_MASKMOVQ, nullptr}, {X86_INS_MOVD, nullptr}, {X86_INS_MOVDQ2Q, nullptr}, {X86_INS_MOVNTQ, nullptr}, {X86_INS_MOVQ2DQ, nullptr}, {X86_INS_MOVQ, nullptr}, {X86_INS_PABSB, nullptr}, {X86_INS_PABSD, nullptr}, {X86_INS_PABSW, nullptr}, {X86_INS_PACKSSDW, nullptr}, {X86_INS_PACKSSWB, nullptr}, {X86_INS_PACKUSWB, nullptr}, {X86_INS_PADDB, nullptr}, {X86_INS_PADDD, nullptr}, {X86_INS_PADDQ, nullptr}, {X86_INS_PADDSB, nullptr}, {X86_INS_PADDSW, nullptr}, {X86_INS_PADDUSB, nullptr}, {X86_INS_PADDUSW, nullptr}, {X86_INS_PADDW, nullptr}, {X86_INS_PALIGNR, nullptr}, {X86_INS_PANDN, nullptr}, {X86_INS_PAND, nullptr}, {X86_INS_PAVGB, nullptr}, {X86_INS_PAVGW, nullptr}, {X86_INS_PCMPEQB, nullptr}, {X86_INS_PCMPEQD, nullptr}, {X86_INS_PCMPEQW, nullptr}, {X86_INS_PCMPGTB, nullptr}, {X86_INS_PCMPGTD, nullptr}, {X86_INS_PCMPGTW, nullptr}, {X86_INS_PEXTRW, nullptr}, {X86_INS_PHADDSW, nullptr}, {X86_INS_PHADDW, nullptr}, {X86_INS_PHADDD, nullptr}, {X86_INS_PHSUBD, nullptr}, {X86_INS_PHSUBSW, nullptr}, {X86_INS_PHSUBW, nullptr}, {X86_INS_PINSRW, nullptr}, {X86_INS_PMADDUBSW, nullptr}, {X86_INS_PMADDWD, nullptr}, {X86_INS_PMAXSW, nullptr}, {X86_INS_PMAXUB, nullptr}, {X86_INS_PMINSW, nullptr}, {X86_INS_PMINUB, nullptr}, {X86_INS_PMOVMSKB, nullptr}, {X86_INS_PMULHRSW, nullptr}, {X86_INS_PMULHUW, nullptr}, {X86_INS_PMULHW, nullptr}, {X86_INS_PMULLW, nullptr}, {X86_INS_PMULUDQ, nullptr}, {X86_INS_POR, nullptr}, {X86_INS_PSADBW, nullptr}, {X86_INS_PSHUFB, nullptr}, {X86_INS_PSHUFW, nullptr}, {X86_INS_PSIGNB, nullptr}, {X86_INS_PSIGND, nullptr}, {X86_INS_PSIGNW, nullptr}, {X86_INS_PSLLD, nullptr}, {X86_INS_PSLLQ, nullptr}, {X86_INS_PSLLW, nullptr}, {X86_INS_PSRAD, nullptr}, {X86_INS_PSRAW, nullptr}, {X86_INS_PSRLD, nullptr}, {X86_INS_PSRLQ, nullptr}, {X86_INS_PSRLW, nullptr}, {X86_INS_PSUBB, nullptr}, {X86_INS_PSUBD, nullptr}, {X86_INS_PSUBQ, nullptr}, {X86_INS_PSUBSB, nullptr}, {X86_INS_PSUBSW, nullptr}, {X86_INS_PSUBUSB, nullptr}, {X86_INS_PSUBUSW, nullptr}, {X86_INS_PSUBW, nullptr}, {X86_INS_PUNPCKHBW, nullptr}, {X86_INS_PUNPCKHDQ, nullptr}, {X86_INS_PUNPCKHWD, nullptr}, {X86_INS_PUNPCKLBW, nullptr}, {X86_INS_PUNPCKLDQ, nullptr}, {X86_INS_PUNPCKLWD, nullptr}, {X86_INS_PXOR, nullptr}, {X86_INS_MONITOR, nullptr}, {X86_INS_MONTMUL, nullptr}, {X86_INS_MOV, &Capstone2LlvmIrTranslatorX86_impl::translateMov}, {X86_INS_MOVABS, &Capstone2LlvmIrTranslatorX86_impl::translateMov}, {X86_INS_MOVBE, nullptr}, {X86_INS_MOVDDUP, nullptr}, {X86_INS_MOVDQA, nullptr}, {X86_INS_MOVDQU, nullptr}, {X86_INS_MOVHLPS, nullptr}, {X86_INS_MOVHPD, nullptr}, {X86_INS_MOVHPS, nullptr}, {X86_INS_MOVLHPS, nullptr}, {X86_INS_MOVLPD, nullptr}, {X86_INS_MOVLPS, nullptr}, {X86_INS_MOVMSKPD, nullptr}, {X86_INS_MOVMSKPS, nullptr}, {X86_INS_MOVNTDQA, nullptr}, {X86_INS_MOVNTDQ, nullptr}, {X86_INS_MOVNTI, nullptr}, {X86_INS_MOVNTPD, nullptr}, {X86_INS_MOVNTPS, nullptr}, {X86_INS_MOVNTSD, nullptr}, {X86_INS_MOVNTSS, nullptr}, {X86_INS_MOVSB, &Capstone2LlvmIrTranslatorX86_impl::translateMoveString}, {X86_INS_MOVSD, &Capstone2LlvmIrTranslatorX86_impl::translateMoveString}, {X86_INS_MOVSHDUP, nullptr}, {X86_INS_MOVSLDUP, nullptr}, {X86_INS_MOVSQ, &Capstone2LlvmIrTranslatorX86_impl::translateMoveString}, {X86_INS_MOVSS, nullptr}, {X86_INS_MOVSW, &Capstone2LlvmIrTranslatorX86_impl::translateMoveString}, {X86_INS_MOVSX, &Capstone2LlvmIrTranslatorX86_impl::translateMov}, {X86_INS_MOVSXD, &Capstone2LlvmIrTranslatorX86_impl::translateMov}, {X86_INS_MOVUPD, nullptr}, {X86_INS_MOVUPS, nullptr}, {X86_INS_MOVZX, &Capstone2LlvmIrTranslatorX86_impl::translateMov}, {X86_INS_MPSADBW, nullptr}, {X86_INS_MUL, &Capstone2LlvmIrTranslatorX86_impl::translateMul}, {X86_INS_MULPD, nullptr}, {X86_INS_MULPS, nullptr}, {X86_INS_MULSD, nullptr}, {X86_INS_MULSS, nullptr}, {X86_INS_MULX, nullptr}, {X86_INS_FMUL, &Capstone2LlvmIrTranslatorX86_impl::translateFmul}, {X86_INS_FIMUL, &Capstone2LlvmIrTranslatorX86_impl::translateFmul}, {X86_INS_FMULP, &Capstone2LlvmIrTranslatorX86_impl::translateFmul}, {X86_INS_MWAIT, nullptr}, {X86_INS_NEG, &Capstone2LlvmIrTranslatorX86_impl::translateNeg}, {X86_INS_NOP, &Capstone2LlvmIrTranslatorX86_impl::translateNop}, {X86_INS_NOT, &Capstone2LlvmIrTranslatorX86_impl::translateNot}, {X86_INS_OUT, nullptr}, {X86_INS_OUTSB, &Capstone2LlvmIrTranslatorX86_impl::translateOuts}, {X86_INS_OUTSD, &Capstone2LlvmIrTranslatorX86_impl::translateOuts}, {X86_INS_OUTSW, &Capstone2LlvmIrTranslatorX86_impl::translateOuts}, {X86_INS_PACKUSDW, nullptr}, {X86_INS_PAUSE, nullptr}, {X86_INS_PAVGUSB, nullptr}, {X86_INS_PBLENDVB, nullptr}, {X86_INS_PBLENDW, nullptr}, {X86_INS_PCLMULQDQ, nullptr}, {X86_INS_PCMPEQQ, nullptr}, {X86_INS_PCMPESTRI, nullptr}, {X86_INS_PCMPESTRM, nullptr}, {X86_INS_PCMPGTQ, nullptr}, {X86_INS_PCMPISTRI, nullptr}, {X86_INS_PCMPISTRM, nullptr}, {X86_INS_PCOMMIT, nullptr}, {X86_INS_PDEP, nullptr}, {X86_INS_PEXT, nullptr}, {X86_INS_PEXTRB, nullptr}, {X86_INS_PEXTRD, nullptr}, {X86_INS_PEXTRQ, nullptr}, {X86_INS_PF2ID, nullptr}, {X86_INS_PF2IW, nullptr}, {X86_INS_PFACC, nullptr}, {X86_INS_PFADD, nullptr}, {X86_INS_PFCMPEQ, nullptr}, {X86_INS_PFCMPGE, nullptr}, {X86_INS_PFCMPGT, nullptr}, {X86_INS_PFMAX, nullptr}, {X86_INS_PFMIN, nullptr}, {X86_INS_PFMUL, nullptr}, {X86_INS_PFNACC, nullptr}, {X86_INS_PFPNACC, nullptr}, {X86_INS_PFRCPIT1, nullptr}, {X86_INS_PFRCPIT2, nullptr}, {X86_INS_PFRCP, nullptr}, {X86_INS_PFRSQIT1, nullptr}, {X86_INS_PFRSQRT, nullptr}, {X86_INS_PFSUBR, nullptr}, {X86_INS_PFSUB, nullptr}, {X86_INS_PHMINPOSUW, nullptr}, {X86_INS_PI2FD, nullptr}, {X86_INS_PI2FW, nullptr}, {X86_INS_PINSRB, nullptr}, {X86_INS_PINSRD, nullptr}, {X86_INS_PINSRQ, nullptr}, {X86_INS_PMAXSB, nullptr}, {X86_INS_PMAXSD, nullptr}, {X86_INS_PMAXUD, nullptr}, {X86_INS_PMAXUW, nullptr}, {X86_INS_PMINSB, nullptr}, {X86_INS_PMINSD, nullptr}, {X86_INS_PMINUD, nullptr}, {X86_INS_PMINUW, nullptr}, {X86_INS_PMOVSXBD, nullptr}, {X86_INS_PMOVSXBQ, nullptr}, {X86_INS_PMOVSXBW, nullptr}, {X86_INS_PMOVSXDQ, nullptr}, {X86_INS_PMOVSXWD, nullptr}, {X86_INS_PMOVSXWQ, nullptr}, {X86_INS_PMOVZXBD, nullptr}, {X86_INS_PMOVZXBQ, nullptr}, {X86_INS_PMOVZXBW, nullptr}, {X86_INS_PMOVZXDQ, nullptr}, {X86_INS_PMOVZXWD, nullptr}, {X86_INS_PMOVZXWQ, nullptr}, {X86_INS_PMULDQ, nullptr}, {X86_INS_PMULHRW, nullptr}, {X86_INS_PMULLD, nullptr}, {X86_INS_POP, &Capstone2LlvmIrTranslatorX86_impl::translatePop}, {X86_INS_POPAW, &Capstone2LlvmIrTranslatorX86_impl::translatePopa}, // X86_INS_POPAW == POPA {X86_INS_POPAL, &Capstone2LlvmIrTranslatorX86_impl::translatePopa}, // X86_INS_POPAL == POPAD {X86_INS_POPCNT, nullptr}, {X86_INS_POPF, &Capstone2LlvmIrTranslatorX86_impl::translatePopEflags}, {X86_INS_POPFD, &Capstone2LlvmIrTranslatorX86_impl::translatePopEflags}, {X86_INS_POPFQ, &Capstone2LlvmIrTranslatorX86_impl::translatePopEflags}, {X86_INS_PREFETCH, nullptr}, {X86_INS_PREFETCHNTA, nullptr}, {X86_INS_PREFETCHT0, nullptr}, {X86_INS_PREFETCHT1, nullptr}, {X86_INS_PREFETCHT2, nullptr}, {X86_INS_PREFETCHW, nullptr}, {X86_INS_PSHUFD, nullptr}, {X86_INS_PSHUFHW, nullptr}, {X86_INS_PSHUFLW, nullptr}, {X86_INS_PSLLDQ, nullptr}, {X86_INS_PSRLDQ, nullptr}, {X86_INS_PSWAPD, nullptr}, {X86_INS_PTEST, nullptr}, {X86_INS_PUNPCKHQDQ, nullptr}, {X86_INS_PUNPCKLQDQ, nullptr}, {X86_INS_PUSH, &Capstone2LlvmIrTranslatorX86_impl::translatePush}, {X86_INS_PUSHAW, &Capstone2LlvmIrTranslatorX86_impl::translatePusha}, // X86_INS_PUSHAW = PUSHA {X86_INS_PUSHAL, &Capstone2LlvmIrTranslatorX86_impl::translatePusha}, // X86_INS_PUSHAL = PUSHAD {X86_INS_PUSHF, &Capstone2LlvmIrTranslatorX86_impl::translatePushEflags}, {X86_INS_PUSHFD, &Capstone2LlvmIrTranslatorX86_impl::translatePushEflags}, {X86_INS_PUSHFQ, &Capstone2LlvmIrTranslatorX86_impl::translatePushEflags}, {X86_INS_RCL, &Capstone2LlvmIrTranslatorX86_impl::translateRcl}, {X86_INS_RCPPS, nullptr}, {X86_INS_RCPSS, nullptr}, {X86_INS_RCR, &Capstone2LlvmIrTranslatorX86_impl::translateRcr}, {X86_INS_RDFSBASE, nullptr}, {X86_INS_RDGSBASE, nullptr}, {X86_INS_RDMSR, nullptr}, {X86_INS_RDPMC, nullptr}, {X86_INS_RDRAND, nullptr}, {X86_INS_RDSEED, nullptr}, {X86_INS_RDTSC, &Capstone2LlvmIrTranslatorX86_impl::translateRdtsc}, {X86_INS_RDTSCP, &Capstone2LlvmIrTranslatorX86_impl::translateRdtscp}, {X86_INS_ROL, &Capstone2LlvmIrTranslatorX86_impl::translateRol}, {X86_INS_ROR, &Capstone2LlvmIrTranslatorX86_impl::translateRor}, {X86_INS_RORX, nullptr}, {X86_INS_ROUNDPD, nullptr}, {X86_INS_ROUNDPS, nullptr}, {X86_INS_ROUNDSD, nullptr}, {X86_INS_ROUNDSS, nullptr}, {X86_INS_RSM, nullptr}, {X86_INS_RSQRTPS, nullptr}, {X86_INS_RSQRTSS, nullptr}, {X86_INS_SAHF, &Capstone2LlvmIrTranslatorX86_impl::translateSahf}, {X86_INS_SAL, &Capstone2LlvmIrTranslatorX86_impl::translateShiftLeft}, {X86_INS_SALC, &Capstone2LlvmIrTranslatorX86_impl::translateSalc}, {X86_INS_SAR, &Capstone2LlvmIrTranslatorX86_impl::translateShiftRight}, {X86_INS_SARX, nullptr}, {X86_INS_SBB, &Capstone2LlvmIrTranslatorX86_impl::translateSbb}, {X86_INS_SCASB, &Capstone2LlvmIrTranslatorX86_impl::translateScanString}, {X86_INS_SCASD, &Capstone2LlvmIrTranslatorX86_impl::translateScanString}, {X86_INS_SCASQ, &Capstone2LlvmIrTranslatorX86_impl::translateScanString}, {X86_INS_SCASW, &Capstone2LlvmIrTranslatorX86_impl::translateScanString}, {X86_INS_SETAE, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETA, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETBE, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETB, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETE, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETGE, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETG, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETLE, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETL, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETNE, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETNO, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETNP, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETNS, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETO, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETP, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SETS, &Capstone2LlvmIrTranslatorX86_impl::translateSetCc}, {X86_INS_SFENCE, nullptr}, {X86_INS_SGDT, nullptr}, {X86_INS_SHA1MSG1, nullptr}, {X86_INS_SHA1MSG2, nullptr}, {X86_INS_SHA1NEXTE, nullptr}, {X86_INS_SHA1RNDS4, nullptr}, {X86_INS_SHA256MSG1, nullptr}, {X86_INS_SHA256MSG2, nullptr}, {X86_INS_SHA256RNDS2, nullptr}, {X86_INS_SHL, &Capstone2LlvmIrTranslatorX86_impl::translateShiftLeft}, {X86_INS_SHLD, &Capstone2LlvmIrTranslatorX86_impl::translateShld}, {X86_INS_SHLX, nullptr}, {X86_INS_SHR, &Capstone2LlvmIrTranslatorX86_impl::translateShiftRight}, {X86_INS_SHRD, &Capstone2LlvmIrTranslatorX86_impl::translateShrd}, {X86_INS_SHRX, nullptr}, {X86_INS_SHUFPD, nullptr}, {X86_INS_SHUFPS, nullptr}, {X86_INS_SIDT, nullptr}, {X86_INS_FSIN, &Capstone2LlvmIrTranslatorX86_impl::translateFsin}, {X86_INS_SKINIT, nullptr}, {X86_INS_SLDT, nullptr}, {X86_INS_SMSW, nullptr}, {X86_INS_SQRTPD, nullptr}, {X86_INS_SQRTPS, nullptr}, {X86_INS_SQRTSD, nullptr}, {X86_INS_SQRTSS, nullptr}, {X86_INS_FSQRT, &Capstone2LlvmIrTranslatorX86_impl::translateFsqrt}, {X86_INS_STAC, nullptr}, {X86_INS_STC, &Capstone2LlvmIrTranslatorX86_impl::translateStc}, {X86_INS_STD, &Capstone2LlvmIrTranslatorX86_impl::translateStd}, {X86_INS_STGI, nullptr}, {X86_INS_STI, nullptr}, {X86_INS_STMXCSR, nullptr}, {X86_INS_STOSB, &Capstone2LlvmIrTranslatorX86_impl::translateStoreString}, {X86_INS_STOSD, &Capstone2LlvmIrTranslatorX86_impl::translateStoreString}, {X86_INS_STOSQ, &Capstone2LlvmIrTranslatorX86_impl::translateStoreString}, {X86_INS_STOSW, &Capstone2LlvmIrTranslatorX86_impl::translateStoreString}, {X86_INS_STR, nullptr}, {X86_INS_FST, &Capstone2LlvmIrTranslatorX86_impl::translateFst}, {X86_INS_FSTP, &Capstone2LlvmIrTranslatorX86_impl::translateFst}, {X86_INS_FSTPNCE, nullptr}, {X86_INS_FXCH, &Capstone2LlvmIrTranslatorX86_impl::translateFxch}, {X86_INS_SUBPD, nullptr}, {X86_INS_SUBPS, nullptr}, {X86_INS_FSUBR, &Capstone2LlvmIrTranslatorX86_impl::translateFsubr}, {X86_INS_FISUBR, &Capstone2LlvmIrTranslatorX86_impl::translateFsubr}, {X86_INS_FSUBRP, &Capstone2LlvmIrTranslatorX86_impl::translateFsubr}, {X86_INS_SUBSD, nullptr}, {X86_INS_SUBSS, nullptr}, {X86_INS_FSUB, &Capstone2LlvmIrTranslatorX86_impl::translateFsub}, {X86_INS_FISUB, &Capstone2LlvmIrTranslatorX86_impl::translateFsub}, {X86_INS_FSUBP, &Capstone2LlvmIrTranslatorX86_impl::translateFsub}, {X86_INS_SWAPGS, nullptr}, {X86_INS_SYSCALL, nullptr}, {X86_INS_SYSENTER, nullptr}, {X86_INS_SYSEXIT, nullptr}, {X86_INS_SYSRET, nullptr}, {X86_INS_T1MSKC, nullptr}, {X86_INS_TEST, &Capstone2LlvmIrTranslatorX86_impl::translateAnd}, {X86_INS_UD2, &Capstone2LlvmIrTranslatorX86_impl::translateNop}, {X86_INS_FTST, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_TZCNT, nullptr}, {X86_INS_TZMSK, nullptr}, {X86_INS_FUCOMIP, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FUCOMI, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FUCOMPP, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FUCOMP, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_FUCOM, &Capstone2LlvmIrTranslatorX86_impl::translateFucomPop}, {X86_INS_UD2B, &Capstone2LlvmIrTranslatorX86_impl::translateNop}, {X86_INS_UNPCKHPD, nullptr}, {X86_INS_UNPCKHPS, nullptr}, {X86_INS_UNPCKLPD, nullptr}, {X86_INS_UNPCKLPS, nullptr}, {X86_INS_VADDPD, nullptr}, {X86_INS_VADDPS, nullptr}, {X86_INS_VADDSD, nullptr}, {X86_INS_VADDSS, nullptr}, {X86_INS_VADDSUBPD, nullptr}, {X86_INS_VADDSUBPS, nullptr}, {X86_INS_VAESDECLAST, nullptr}, {X86_INS_VAESDEC, nullptr}, {X86_INS_VAESENCLAST, nullptr}, {X86_INS_VAESENC, nullptr}, {X86_INS_VAESIMC, nullptr}, {X86_INS_VAESKEYGENASSIST, nullptr}, {X86_INS_VALIGND, nullptr}, {X86_INS_VALIGNQ, nullptr}, {X86_INS_VANDNPD, nullptr}, {X86_INS_VANDNPS, nullptr}, {X86_INS_VANDPD, nullptr}, {X86_INS_VANDPS, nullptr}, {X86_INS_VBLENDMPD, nullptr}, {X86_INS_VBLENDMPS, nullptr}, {X86_INS_VBLENDPD, nullptr}, {X86_INS_VBLENDPS, nullptr}, {X86_INS_VBLENDVPD, nullptr}, {X86_INS_VBLENDVPS, nullptr}, {X86_INS_VBROADCASTF128, nullptr}, {X86_INS_VBROADCASTI32X4, nullptr}, {X86_INS_VBROADCASTI64X4, nullptr}, {X86_INS_VBROADCASTSD, nullptr}, {X86_INS_VBROADCASTSS, nullptr}, {X86_INS_VCOMPRESSPD, nullptr}, {X86_INS_VCOMPRESSPS, nullptr}, {X86_INS_VCVTDQ2PD, nullptr}, {X86_INS_VCVTDQ2PS, nullptr}, {X86_INS_VCVTPD2DQX, nullptr}, {X86_INS_VCVTPD2DQ, nullptr}, {X86_INS_VCVTPD2PSX, nullptr}, {X86_INS_VCVTPD2PS, nullptr}, {X86_INS_VCVTPD2UDQ, nullptr}, {X86_INS_VCVTPH2PS, nullptr}, {X86_INS_VCVTPS2DQ, nullptr}, {X86_INS_VCVTPS2PD, nullptr}, {X86_INS_VCVTPS2PH, nullptr}, {X86_INS_VCVTPS2UDQ, nullptr}, {X86_INS_VCVTSD2SI, nullptr}, {X86_INS_VCVTSD2USI, nullptr}, {X86_INS_VCVTSS2SI, nullptr}, {X86_INS_VCVTSS2USI, nullptr}, {X86_INS_VCVTTPD2DQX, nullptr}, {X86_INS_VCVTTPD2DQ, nullptr}, {X86_INS_VCVTTPD2UDQ, nullptr}, {X86_INS_VCVTTPS2DQ, nullptr}, {X86_INS_VCVTTPS2UDQ, nullptr}, {X86_INS_VCVTUDQ2PD, nullptr}, {X86_INS_VCVTUDQ2PS, nullptr}, {X86_INS_VDIVPD, nullptr}, {X86_INS_VDIVPS, nullptr}, {X86_INS_VDIVSD, nullptr}, {X86_INS_VDIVSS, nullptr}, {X86_INS_VDPPD, nullptr}, {X86_INS_VDPPS, nullptr}, {X86_INS_VERR, nullptr}, {X86_INS_VERW, nullptr}, {X86_INS_VEXP2PD, nullptr}, {X86_INS_VEXP2PS, nullptr}, {X86_INS_VEXPANDPD, nullptr}, {X86_INS_VEXPANDPS, nullptr}, {X86_INS_VEXTRACTF128, nullptr}, {X86_INS_VEXTRACTF32X4, nullptr}, {X86_INS_VEXTRACTF64X4, nullptr}, {X86_INS_VEXTRACTI128, nullptr}, {X86_INS_VEXTRACTI32X4, nullptr}, {X86_INS_VEXTRACTI64X4, nullptr}, {X86_INS_VEXTRACTPS, nullptr}, {X86_INS_VFMADD132PD, nullptr}, {X86_INS_VFMADD132PS, nullptr}, {X86_INS_VFMADDPD, nullptr}, {X86_INS_VFMADD213PD, nullptr}, {X86_INS_VFMADD231PD, nullptr}, {X86_INS_VFMADDPS, nullptr}, {X86_INS_VFMADD213PS, nullptr}, {X86_INS_VFMADD231PS, nullptr}, {X86_INS_VFMADDSD, nullptr}, {X86_INS_VFMADD213SD, nullptr}, {X86_INS_VFMADD132SD, nullptr}, {X86_INS_VFMADD231SD, nullptr}, {X86_INS_VFMADDSS, nullptr}, {X86_INS_VFMADD213SS, nullptr}, {X86_INS_VFMADD132SS, nullptr}, {X86_INS_VFMADD231SS, nullptr}, {X86_INS_VFMADDSUB132PD, nullptr}, {X86_INS_VFMADDSUB132PS, nullptr}, {X86_INS_VFMADDSUBPD, nullptr}, {X86_INS_VFMADDSUB213PD, nullptr}, {X86_INS_VFMADDSUB231PD, nullptr}, {X86_INS_VFMADDSUBPS, nullptr}, {X86_INS_VFMADDSUB213PS, nullptr}, {X86_INS_VFMADDSUB231PS, nullptr}, {X86_INS_VFMSUB132PD, nullptr}, {X86_INS_VFMSUB132PS, nullptr}, {X86_INS_VFMSUBADD132PD, nullptr}, {X86_INS_VFMSUBADD132PS, nullptr}, {X86_INS_VFMSUBADDPD, nullptr}, {X86_INS_VFMSUBADD213PD, nullptr}, {X86_INS_VFMSUBADD231PD, nullptr}, {X86_INS_VFMSUBADDPS, nullptr}, {X86_INS_VFMSUBADD213PS, nullptr}, {X86_INS_VFMSUBADD231PS, nullptr}, {X86_INS_VFMSUBPD, nullptr}, {X86_INS_VFMSUB213PD, nullptr}, {X86_INS_VFMSUB231PD, nullptr}, {X86_INS_VFMSUBPS, nullptr}, {X86_INS_VFMSUB213PS, nullptr}, {X86_INS_VFMSUB231PS, nullptr}, {X86_INS_VFMSUBSD, nullptr}, {X86_INS_VFMSUB213SD, nullptr}, {X86_INS_VFMSUB132SD, nullptr}, {X86_INS_VFMSUB231SD, nullptr}, {X86_INS_VFMSUBSS, nullptr}, {X86_INS_VFMSUB213SS, nullptr}, {X86_INS_VFMSUB132SS, nullptr}, {X86_INS_VFMSUB231SS, nullptr}, {X86_INS_VFNMADD132PD, nullptr}, {X86_INS_VFNMADD132PS, nullptr}, {X86_INS_VFNMADDPD, nullptr}, {X86_INS_VFNMADD213PD, nullptr}, {X86_INS_VFNMADD231PD, nullptr}, {X86_INS_VFNMADDPS, nullptr}, {X86_INS_VFNMADD213PS, nullptr}, {X86_INS_VFNMADD231PS, nullptr}, {X86_INS_VFNMADDSD, nullptr}, {X86_INS_VFNMADD213SD, nullptr}, {X86_INS_VFNMADD132SD, nullptr}, {X86_INS_VFNMADD231SD, nullptr}, {X86_INS_VFNMADDSS, nullptr}, {X86_INS_VFNMADD213SS, nullptr}, {X86_INS_VFNMADD132SS, nullptr}, {X86_INS_VFNMADD231SS, nullptr}, {X86_INS_VFNMSUB132PD, nullptr}, {X86_INS_VFNMSUB132PS, nullptr}, {X86_INS_VFNMSUBPD, nullptr}, {X86_INS_VFNMSUB213PD, nullptr}, {X86_INS_VFNMSUB231PD, nullptr}, {X86_INS_VFNMSUBPS, nullptr}, {X86_INS_VFNMSUB213PS, nullptr}, {X86_INS_VFNMSUB231PS, nullptr}, {X86_INS_VFNMSUBSD, nullptr}, {X86_INS_VFNMSUB213SD, nullptr}, {X86_INS_VFNMSUB132SD, nullptr}, {X86_INS_VFNMSUB231SD, nullptr}, {X86_INS_VFNMSUBSS, nullptr}, {X86_INS_VFNMSUB213SS, nullptr}, {X86_INS_VFNMSUB132SS, nullptr}, {X86_INS_VFNMSUB231SS, nullptr}, {X86_INS_VFRCZPD, nullptr}, {X86_INS_VFRCZPS, nullptr}, {X86_INS_VFRCZSD, nullptr}, {X86_INS_VFRCZSS, nullptr}, {X86_INS_VORPD, nullptr}, {X86_INS_VORPS, nullptr}, {X86_INS_VXORPD, nullptr}, {X86_INS_VXORPS, nullptr}, {X86_INS_VGATHERDPD, nullptr}, {X86_INS_VGATHERDPS, nullptr}, {X86_INS_VGATHERPF0DPD, nullptr}, {X86_INS_VGATHERPF0DPS, nullptr}, {X86_INS_VGATHERPF0QPD, nullptr}, {X86_INS_VGATHERPF0QPS, nullptr}, {X86_INS_VGATHERPF1DPD, nullptr}, {X86_INS_VGATHERPF1DPS, nullptr}, {X86_INS_VGATHERPF1QPD, nullptr}, {X86_INS_VGATHERPF1QPS, nullptr}, {X86_INS_VGATHERQPD, nullptr}, {X86_INS_VGATHERQPS, nullptr}, {X86_INS_VHADDPD, nullptr}, {X86_INS_VHADDPS, nullptr}, {X86_INS_VHSUBPD, nullptr}, {X86_INS_VHSUBPS, nullptr}, {X86_INS_VINSERTF128, nullptr}, {X86_INS_VINSERTF32X4, nullptr}, {X86_INS_VINSERTF32X8, nullptr}, {X86_INS_VINSERTF64X2, nullptr}, {X86_INS_VINSERTF64X4, nullptr}, {X86_INS_VINSERTI128, nullptr}, {X86_INS_VINSERTI32X4, nullptr}, {X86_INS_VINSERTI32X8, nullptr}, {X86_INS_VINSERTI64X2, nullptr}, {X86_INS_VINSERTI64X4, nullptr}, {X86_INS_VINSERTPS, nullptr}, {X86_INS_VLDDQU, nullptr}, {X86_INS_VLDMXCSR, nullptr}, {X86_INS_VMASKMOVDQU, nullptr}, {X86_INS_VMASKMOVPD, nullptr}, {X86_INS_VMASKMOVPS, nullptr}, {X86_INS_VMAXPD, nullptr}, {X86_INS_VMAXPS, nullptr}, {X86_INS_VMAXSD, nullptr}, {X86_INS_VMAXSS, nullptr}, {X86_INS_VMCALL, nullptr}, {X86_INS_VMCLEAR, nullptr}, {X86_INS_VMFUNC, nullptr}, {X86_INS_VMINPD, nullptr}, {X86_INS_VMINPS, nullptr}, {X86_INS_VMINSD, nullptr}, {X86_INS_VMINSS, nullptr}, {X86_INS_VMLAUNCH, nullptr}, {X86_INS_VMLOAD, nullptr}, {X86_INS_VMMCALL, nullptr}, {X86_INS_VMOVQ, nullptr}, {X86_INS_VMOVDDUP, nullptr}, {X86_INS_VMOVD, nullptr}, {X86_INS_VMOVDQA32, nullptr}, {X86_INS_VMOVDQA64, nullptr}, {X86_INS_VMOVDQA, nullptr}, {X86_INS_VMOVDQU16, nullptr}, {X86_INS_VMOVDQU32, nullptr}, {X86_INS_VMOVDQU64, nullptr}, {X86_INS_VMOVDQU8, nullptr}, {X86_INS_VMOVDQU, nullptr}, {X86_INS_VMOVHLPS, nullptr}, {X86_INS_VMOVHPD, nullptr}, {X86_INS_VMOVHPS, nullptr}, {X86_INS_VMOVLHPS, nullptr}, {X86_INS_VMOVLPD, nullptr}, {X86_INS_VMOVLPS, nullptr}, {X86_INS_VMOVMSKPD, nullptr}, {X86_INS_VMOVMSKPS, nullptr}, {X86_INS_VMOVNTDQA, nullptr}, {X86_INS_VMOVNTDQ, nullptr}, {X86_INS_VMOVNTPD, nullptr}, {X86_INS_VMOVNTPS, nullptr}, {X86_INS_VMOVSD, nullptr}, {X86_INS_VMOVSHDUP, nullptr}, {X86_INS_VMOVSLDUP, nullptr}, {X86_INS_VMOVSS, nullptr}, {X86_INS_VMOVUPD, nullptr}, {X86_INS_VMOVUPS, nullptr}, {X86_INS_VMPSADBW, nullptr}, {X86_INS_VMPTRLD, nullptr}, {X86_INS_VMPTRST, nullptr}, {X86_INS_VMREAD, nullptr}, {X86_INS_VMRESUME, nullptr}, {X86_INS_VMRUN, nullptr}, {X86_INS_VMSAVE, nullptr}, {X86_INS_VMULPD, nullptr}, {X86_INS_VMULPS, nullptr}, {X86_INS_VMULSD, nullptr}, {X86_INS_VMULSS, nullptr}, {X86_INS_VMWRITE, nullptr}, {X86_INS_VMXOFF, nullptr}, {X86_INS_VMXON, nullptr}, {X86_INS_VPABSB, nullptr}, {X86_INS_VPABSD, nullptr}, {X86_INS_VPABSQ, nullptr}, {X86_INS_VPABSW, nullptr}, {X86_INS_VPACKSSDW, nullptr}, {X86_INS_VPACKSSWB, nullptr}, {X86_INS_VPACKUSDW, nullptr}, {X86_INS_VPACKUSWB, nullptr}, {X86_INS_VPADDB, nullptr}, {X86_INS_VPADDD, nullptr}, {X86_INS_VPADDQ, nullptr}, {X86_INS_VPADDSB, nullptr}, {X86_INS_VPADDSW, nullptr}, {X86_INS_VPADDUSB, nullptr}, {X86_INS_VPADDUSW, nullptr}, {X86_INS_VPADDW, nullptr}, {X86_INS_VPALIGNR, nullptr}, {X86_INS_VPANDD, nullptr}, {X86_INS_VPANDND, nullptr}, {X86_INS_VPANDNQ, nullptr}, {X86_INS_VPANDN, nullptr}, {X86_INS_VPANDQ, nullptr}, {X86_INS_VPAND, nullptr}, {X86_INS_VPAVGB, nullptr}, {X86_INS_VPAVGW, nullptr}, {X86_INS_VPBLENDD, nullptr}, {X86_INS_VPBLENDMB, nullptr}, {X86_INS_VPBLENDMD, nullptr}, {X86_INS_VPBLENDMQ, nullptr}, {X86_INS_VPBLENDMW, nullptr}, {X86_INS_VPBLENDVB, nullptr}, {X86_INS_VPBLENDW, nullptr}, {X86_INS_VPBROADCASTB, nullptr}, {X86_INS_VPBROADCASTD, nullptr}, {X86_INS_VPBROADCASTMB2Q, nullptr}, {X86_INS_VPBROADCASTMW2D, nullptr}, {X86_INS_VPBROADCASTQ, nullptr}, {X86_INS_VPBROADCASTW, nullptr}, {X86_INS_VPCLMULQDQ, nullptr}, {X86_INS_VPCMOV, nullptr}, {X86_INS_VPCMPB, nullptr}, {X86_INS_VPCMPD, nullptr}, {X86_INS_VPCMPEQB, nullptr}, {X86_INS_VPCMPEQD, nullptr}, {X86_INS_VPCMPEQQ, nullptr}, {X86_INS_VPCMPEQW, nullptr}, {X86_INS_VPCMPESTRI, nullptr}, {X86_INS_VPCMPESTRM, nullptr}, {X86_INS_VPCMPGTB, nullptr}, {X86_INS_VPCMPGTD, nullptr}, {X86_INS_VPCMPGTQ, nullptr}, {X86_INS_VPCMPGTW, nullptr}, {X86_INS_VPCMPISTRI, nullptr}, {X86_INS_VPCMPISTRM, nullptr}, {X86_INS_VPCMPQ, nullptr}, {X86_INS_VPCMPUB, nullptr}, {X86_INS_VPCMPUD, nullptr}, {X86_INS_VPCMPUQ, nullptr}, {X86_INS_VPCMPUW, nullptr}, {X86_INS_VPCMPW, nullptr}, {X86_INS_VPCOMB, nullptr}, {X86_INS_VPCOMD, nullptr}, {X86_INS_VPCOMPRESSD, nullptr}, {X86_INS_VPCOMPRESSQ, nullptr}, {X86_INS_VPCOMQ, nullptr}, {X86_INS_VPCOMUB, nullptr}, {X86_INS_VPCOMUD, nullptr}, {X86_INS_VPCOMUQ, nullptr}, {X86_INS_VPCOMUW, nullptr}, {X86_INS_VPCOMW, nullptr}, {X86_INS_VPCONFLICTD, nullptr}, {X86_INS_VPCONFLICTQ, nullptr}, {X86_INS_VPERM2F128, nullptr}, {X86_INS_VPERM2I128, nullptr}, {X86_INS_VPERMD, nullptr}, {X86_INS_VPERMI2D, nullptr}, {X86_INS_VPERMI2PD, nullptr}, {X86_INS_VPERMI2PS, nullptr}, {X86_INS_VPERMI2Q, nullptr}, {X86_INS_VPERMIL2PD, nullptr}, {X86_INS_VPERMIL2PS, nullptr}, {X86_INS_VPERMILPD, nullptr}, {X86_INS_VPERMILPS, nullptr}, {X86_INS_VPERMPD, nullptr}, {X86_INS_VPERMPS, nullptr}, {X86_INS_VPERMQ, nullptr}, {X86_INS_VPERMT2D, nullptr}, {X86_INS_VPERMT2PD, nullptr}, {X86_INS_VPERMT2PS, nullptr}, {X86_INS_VPERMT2Q, nullptr}, {X86_INS_VPEXPANDD, nullptr}, {X86_INS_VPEXPANDQ, nullptr}, {X86_INS_VPEXTRB, nullptr}, {X86_INS_VPEXTRD, nullptr}, {X86_INS_VPEXTRQ, nullptr}, {X86_INS_VPEXTRW, nullptr}, {X86_INS_VPGATHERDD, nullptr}, {X86_INS_VPGATHERDQ, nullptr}, {X86_INS_VPGATHERQD, nullptr}, {X86_INS_VPGATHERQQ, nullptr}, {X86_INS_VPHADDBD, nullptr}, {X86_INS_VPHADDBQ, nullptr}, {X86_INS_VPHADDBW, nullptr}, {X86_INS_VPHADDDQ, nullptr}, {X86_INS_VPHADDD, nullptr}, {X86_INS_VPHADDSW, nullptr}, {X86_INS_VPHADDUBD, nullptr}, {X86_INS_VPHADDUBQ, nullptr}, {X86_INS_VPHADDUBW, nullptr}, {X86_INS_VPHADDUDQ, nullptr}, {X86_INS_VPHADDUWD, nullptr}, {X86_INS_VPHADDUWQ, nullptr}, {X86_INS_VPHADDWD, nullptr}, {X86_INS_VPHADDWQ, nullptr}, {X86_INS_VPHADDW, nullptr}, {X86_INS_VPHMINPOSUW, nullptr}, {X86_INS_VPHSUBBW, nullptr}, {X86_INS_VPHSUBDQ, nullptr}, {X86_INS_VPHSUBD, nullptr}, {X86_INS_VPHSUBSW, nullptr}, {X86_INS_VPHSUBWD, nullptr}, {X86_INS_VPHSUBW, nullptr}, {X86_INS_VPINSRB, nullptr}, {X86_INS_VPINSRD, nullptr}, {X86_INS_VPINSRQ, nullptr}, {X86_INS_VPINSRW, nullptr}, {X86_INS_VPLZCNTD, nullptr}, {X86_INS_VPLZCNTQ, nullptr}, {X86_INS_VPMACSDD, nullptr}, {X86_INS_VPMACSDQH, nullptr}, {X86_INS_VPMACSDQL, nullptr}, {X86_INS_VPMACSSDD, nullptr}, {X86_INS_VPMACSSDQH, nullptr}, {X86_INS_VPMACSSDQL, nullptr}, {X86_INS_VPMACSSWD, nullptr}, {X86_INS_VPMACSSWW, nullptr}, {X86_INS_VPMACSWD, nullptr}, {X86_INS_VPMACSWW, nullptr}, {X86_INS_VPMADCSSWD, nullptr}, {X86_INS_VPMADCSWD, nullptr}, {X86_INS_VPMADDUBSW, nullptr}, {X86_INS_VPMADDWD, nullptr}, {X86_INS_VPMASKMOVD, nullptr}, {X86_INS_VPMASKMOVQ, nullptr}, {X86_INS_VPMAXSB, nullptr}, {X86_INS_VPMAXSD, nullptr}, {X86_INS_VPMAXSQ, nullptr}, {X86_INS_VPMAXSW, nullptr}, {X86_INS_VPMAXUB, nullptr}, {X86_INS_VPMAXUD, nullptr}, {X86_INS_VPMAXUQ, nullptr}, {X86_INS_VPMAXUW, nullptr}, {X86_INS_VPMINSB, nullptr}, {X86_INS_VPMINSD, nullptr}, {X86_INS_VPMINSQ, nullptr}, {X86_INS_VPMINSW, nullptr}, {X86_INS_VPMINUB, nullptr}, {X86_INS_VPMINUD, nullptr}, {X86_INS_VPMINUQ, nullptr}, {X86_INS_VPMINUW, nullptr}, {X86_INS_VPMOVDB, nullptr}, {X86_INS_VPMOVDW, nullptr}, {X86_INS_VPMOVM2B, nullptr}, {X86_INS_VPMOVM2D, nullptr}, {X86_INS_VPMOVM2Q, nullptr}, {X86_INS_VPMOVM2W, nullptr}, {X86_INS_VPMOVMSKB, nullptr}, {X86_INS_VPMOVQB, nullptr}, {X86_INS_VPMOVQD, nullptr}, {X86_INS_VPMOVQW, nullptr}, {X86_INS_VPMOVSDB, nullptr}, {X86_INS_VPMOVSDW, nullptr}, {X86_INS_VPMOVSQB, nullptr}, {X86_INS_VPMOVSQD, nullptr}, {X86_INS_VPMOVSQW, nullptr}, {X86_INS_VPMOVSXBD, nullptr}, {X86_INS_VPMOVSXBQ, nullptr}, {X86_INS_VPMOVSXBW, nullptr}, {X86_INS_VPMOVSXDQ, nullptr}, {X86_INS_VPMOVSXWD, nullptr}, {X86_INS_VPMOVSXWQ, nullptr}, {X86_INS_VPMOVUSDB, nullptr}, {X86_INS_VPMOVUSDW, nullptr}, {X86_INS_VPMOVUSQB, nullptr}, {X86_INS_VPMOVUSQD, nullptr}, {X86_INS_VPMOVUSQW, nullptr}, {X86_INS_VPMOVZXBD, nullptr}, {X86_INS_VPMOVZXBQ, nullptr}, {X86_INS_VPMOVZXBW, nullptr}, {X86_INS_VPMOVZXDQ, nullptr}, {X86_INS_VPMOVZXWD, nullptr}, {X86_INS_VPMOVZXWQ, nullptr}, {X86_INS_VPMULDQ, nullptr}, {X86_INS_VPMULHRSW, nullptr}, {X86_INS_VPMULHUW, nullptr}, {X86_INS_VPMULHW, nullptr}, {X86_INS_VPMULLD, nullptr}, {X86_INS_VPMULLQ, nullptr}, {X86_INS_VPMULLW, nullptr}, {X86_INS_VPMULUDQ, nullptr}, {X86_INS_VPORD, nullptr}, {X86_INS_VPORQ, nullptr}, {X86_INS_VPOR, nullptr}, {X86_INS_VPPERM, nullptr}, {X86_INS_VPROTB, nullptr}, {X86_INS_VPROTD, nullptr}, {X86_INS_VPROTQ, nullptr}, {X86_INS_VPROTW, nullptr}, {X86_INS_VPSADBW, nullptr}, {X86_INS_VPSCATTERDD, nullptr}, {X86_INS_VPSCATTERDQ, nullptr}, {X86_INS_VPSCATTERQD, nullptr}, {X86_INS_VPSCATTERQQ, nullptr}, {X86_INS_VPSHAB, nullptr}, {X86_INS_VPSHAD, nullptr}, {X86_INS_VPSHAQ, nullptr}, {X86_INS_VPSHAW, nullptr}, {X86_INS_VPSHLB, nullptr}, {X86_INS_VPSHLD, nullptr}, {X86_INS_VPSHLQ, nullptr}, {X86_INS_VPSHLW, nullptr}, {X86_INS_VPSHUFB, nullptr}, {X86_INS_VPSHUFD, nullptr}, {X86_INS_VPSHUFHW, nullptr}, {X86_INS_VPSHUFLW, nullptr}, {X86_INS_VPSIGNB, nullptr}, {X86_INS_VPSIGND, nullptr}, {X86_INS_VPSIGNW, nullptr}, {X86_INS_VPSLLDQ, nullptr}, {X86_INS_VPSLLD, nullptr}, {X86_INS_VPSLLQ, nullptr}, {X86_INS_VPSLLVD, nullptr}, {X86_INS_VPSLLVQ, nullptr}, {X86_INS_VPSLLW, nullptr}, {X86_INS_VPSRAD, nullptr}, {X86_INS_VPSRAQ, nullptr}, {X86_INS_VPSRAVD, nullptr}, {X86_INS_VPSRAVQ, nullptr}, {X86_INS_VPSRAW, nullptr}, {X86_INS_VPSRLDQ, nullptr}, {X86_INS_VPSRLD, nullptr}, {X86_INS_VPSRLQ, nullptr}, {X86_INS_VPSRLVD, nullptr}, {X86_INS_VPSRLVQ, nullptr}, {X86_INS_VPSRLW, nullptr}, {X86_INS_VPSUBB, nullptr}, {X86_INS_VPSUBD, nullptr}, {X86_INS_VPSUBQ, nullptr}, {X86_INS_VPSUBSB, nullptr}, {X86_INS_VPSUBSW, nullptr}, {X86_INS_VPSUBUSB, nullptr}, {X86_INS_VPSUBUSW, nullptr}, {X86_INS_VPSUBW, nullptr}, {X86_INS_VPTESTMD, nullptr}, {X86_INS_VPTESTMQ, nullptr}, {X86_INS_VPTESTNMD, nullptr}, {X86_INS_VPTESTNMQ, nullptr}, {X86_INS_VPTEST, nullptr}, {X86_INS_VPUNPCKHBW, nullptr}, {X86_INS_VPUNPCKHDQ, nullptr}, {X86_INS_VPUNPCKHQDQ, nullptr}, {X86_INS_VPUNPCKHWD, nullptr}, {X86_INS_VPUNPCKLBW, nullptr}, {X86_INS_VPUNPCKLDQ, nullptr}, {X86_INS_VPUNPCKLQDQ, nullptr}, {X86_INS_VPUNPCKLWD, nullptr}, {X86_INS_VPXORD, nullptr}, {X86_INS_VPXORQ, nullptr}, {X86_INS_VPXOR, nullptr}, {X86_INS_VRCP14PD, nullptr}, {X86_INS_VRCP14PS, nullptr}, {X86_INS_VRCP14SD, nullptr}, {X86_INS_VRCP14SS, nullptr}, {X86_INS_VRCP28PD, nullptr}, {X86_INS_VRCP28PS, nullptr}, {X86_INS_VRCP28SD, nullptr}, {X86_INS_VRCP28SS, nullptr}, {X86_INS_VRCPPS, nullptr}, {X86_INS_VRCPSS, nullptr}, {X86_INS_VRNDSCALEPD, nullptr}, {X86_INS_VRNDSCALEPS, nullptr}, {X86_INS_VRNDSCALESD, nullptr}, {X86_INS_VRNDSCALESS, nullptr}, {X86_INS_VROUNDPD, nullptr}, {X86_INS_VROUNDPS, nullptr}, {X86_INS_VROUNDSD, nullptr}, {X86_INS_VROUNDSS, nullptr}, {X86_INS_VRSQRT14PD, nullptr}, {X86_INS_VRSQRT14PS, nullptr}, {X86_INS_VRSQRT14SD, nullptr}, {X86_INS_VRSQRT14SS, nullptr}, {X86_INS_VRSQRT28PD, nullptr}, {X86_INS_VRSQRT28PS, nullptr}, {X86_INS_VRSQRT28SD, nullptr}, {X86_INS_VRSQRT28SS, nullptr}, {X86_INS_VRSQRTPS, nullptr}, {X86_INS_VRSQRTSS, nullptr}, {X86_INS_VSCATTERDPD, nullptr}, {X86_INS_VSCATTERDPS, nullptr}, {X86_INS_VSCATTERPF0DPD, nullptr}, {X86_INS_VSCATTERPF0DPS, nullptr}, {X86_INS_VSCATTERPF0QPD, nullptr}, {X86_INS_VSCATTERPF0QPS, nullptr}, {X86_INS_VSCATTERPF1DPD, nullptr}, {X86_INS_VSCATTERPF1DPS, nullptr}, {X86_INS_VSCATTERPF1QPD, nullptr}, {X86_INS_VSCATTERPF1QPS, nullptr}, {X86_INS_VSCATTERQPD, nullptr}, {X86_INS_VSCATTERQPS, nullptr}, {X86_INS_VSHUFPD, nullptr}, {X86_INS_VSHUFPS, nullptr}, {X86_INS_VSQRTPD, nullptr}, {X86_INS_VSQRTPS, nullptr}, {X86_INS_VSQRTSD, nullptr}, {X86_INS_VSQRTSS, nullptr}, {X86_INS_VSTMXCSR, nullptr}, {X86_INS_VSUBPD, nullptr}, {X86_INS_VSUBPS, nullptr}, {X86_INS_VSUBSD, nullptr}, {X86_INS_VSUBSS, nullptr}, {X86_INS_VTESTPD, nullptr}, {X86_INS_VTESTPS, nullptr}, {X86_INS_VUNPCKHPD, nullptr}, {X86_INS_VUNPCKHPS, nullptr}, {X86_INS_VUNPCKLPD, nullptr}, {X86_INS_VUNPCKLPS, nullptr}, {X86_INS_VZEROALL, nullptr}, {X86_INS_VZEROUPPER, nullptr}, {X86_INS_WAIT, nullptr}, {X86_INS_WBINVD, nullptr}, {X86_INS_WRFSBASE, nullptr}, {X86_INS_WRGSBASE, nullptr}, {X86_INS_WRMSR, nullptr}, {X86_INS_XABORT, nullptr}, {X86_INS_XACQUIRE, nullptr}, {X86_INS_XBEGIN, nullptr}, {X86_INS_XCHG, &Capstone2LlvmIrTranslatorX86_impl::translateXchg}, {X86_INS_XCRYPTCBC, nullptr}, {X86_INS_XCRYPTCFB, nullptr}, {X86_INS_XCRYPTCTR, nullptr}, {X86_INS_XCRYPTECB, nullptr}, {X86_INS_XCRYPTOFB, nullptr}, {X86_INS_XEND, nullptr}, {X86_INS_XGETBV, nullptr}, {X86_INS_XLATB, &Capstone2LlvmIrTranslatorX86_impl::translateXlatb}, {X86_INS_XRELEASE, nullptr}, {X86_INS_XRSTOR, nullptr}, {X86_INS_XRSTOR64, nullptr}, {X86_INS_XRSTORS, nullptr}, {X86_INS_XRSTORS64, nullptr}, {X86_INS_XSAVE, nullptr}, {X86_INS_XSAVE64, nullptr}, {X86_INS_XSAVEC, nullptr}, {X86_INS_XSAVEC64, nullptr}, {X86_INS_XSAVEOPT, nullptr}, {X86_INS_XSAVEOPT64, nullptr}, {X86_INS_XSAVES, nullptr}, {X86_INS_XSAVES64, nullptr}, {X86_INS_XSETBV, nullptr}, {X86_INS_XSHA1, nullptr}, {X86_INS_XSHA256, nullptr}, {X86_INS_XSTORE, nullptr}, {X86_INS_XTEST, nullptr}, {X86_INS_FDISI8087_NOP, &Capstone2LlvmIrTranslatorX86_impl::translateNop}, {X86_INS_FENI8087_NOP, &Capstone2LlvmIrTranslatorX86_impl::translateNop}, // pseudo instructions {X86_INS_CMPSS, nullptr}, {X86_INS_CMPEQSS, nullptr}, {X86_INS_CMPLTSS, nullptr}, {X86_INS_CMPLESS, nullptr}, {X86_INS_CMPUNORDSS, nullptr}, {X86_INS_CMPNEQSS, nullptr}, {X86_INS_CMPNLTSS, nullptr}, {X86_INS_CMPNLESS, nullptr}, {X86_INS_CMPORDSS, nullptr}, {X86_INS_CMPSD, &Capstone2LlvmIrTranslatorX86_impl::translateCompareString}, {X86_INS_CMPEQSD, nullptr}, {X86_INS_CMPLTSD, nullptr}, {X86_INS_CMPLESD, nullptr}, {X86_INS_CMPUNORDSD, nullptr}, {X86_INS_CMPNEQSD, nullptr}, {X86_INS_CMPNLTSD, nullptr}, {X86_INS_CMPNLESD, nullptr}, {X86_INS_CMPORDSD, nullptr}, {X86_INS_CMPPS, nullptr}, {X86_INS_CMPEQPS, nullptr}, {X86_INS_CMPLTPS, nullptr}, {X86_INS_CMPLEPS, nullptr}, {X86_INS_CMPUNORDPS, nullptr}, {X86_INS_CMPNEQPS, nullptr}, {X86_INS_CMPNLTPS, nullptr}, {X86_INS_CMPNLEPS, nullptr}, {X86_INS_CMPORDPS, nullptr}, {X86_INS_CMPPD, nullptr}, {X86_INS_CMPEQPD, nullptr}, {X86_INS_CMPLTPD, nullptr}, {X86_INS_CMPLEPD, nullptr}, {X86_INS_CMPUNORDPD, nullptr}, {X86_INS_CMPNEQPD, nullptr}, {X86_INS_CMPNLTPD, nullptr}, {X86_INS_CMPNLEPD, nullptr}, {X86_INS_CMPORDPD, nullptr}, {X86_INS_VCMPSS, nullptr}, {X86_INS_VCMPEQSS, nullptr}, {X86_INS_VCMPLTSS, nullptr}, {X86_INS_VCMPLESS, nullptr}, {X86_INS_VCMPUNORDSS, nullptr}, {X86_INS_VCMPNEQSS, nullptr}, {X86_INS_VCMPNLTSS, nullptr}, {X86_INS_VCMPNLESS, nullptr}, {X86_INS_VCMPORDSS, nullptr}, {X86_INS_VCMPEQ_UQSS, nullptr}, {X86_INS_VCMPNGESS, nullptr}, {X86_INS_VCMPNGTSS, nullptr}, {X86_INS_VCMPFALSESS, nullptr}, {X86_INS_VCMPNEQ_OQSS, nullptr}, {X86_INS_VCMPGESS, nullptr}, {X86_INS_VCMPGTSS, nullptr}, {X86_INS_VCMPTRUESS, nullptr}, {X86_INS_VCMPEQ_OSSS, nullptr}, {X86_INS_VCMPLT_OQSS, nullptr}, {X86_INS_VCMPLE_OQSS, nullptr}, {X86_INS_VCMPUNORD_SSS, nullptr}, {X86_INS_VCMPNEQ_USSS, nullptr}, {X86_INS_VCMPNLT_UQSS, nullptr}, {X86_INS_VCMPNLE_UQSS, nullptr}, {X86_INS_VCMPORD_SSS, nullptr}, {X86_INS_VCMPEQ_USSS, nullptr}, {X86_INS_VCMPNGE_UQSS, nullptr}, {X86_INS_VCMPNGT_UQSS, nullptr}, {X86_INS_VCMPFALSE_OSSS, nullptr}, {X86_INS_VCMPNEQ_OSSS, nullptr}, {X86_INS_VCMPGE_OQSS, nullptr}, {X86_INS_VCMPGT_OQSS, nullptr}, {X86_INS_VCMPTRUE_USSS, nullptr}, {X86_INS_VCMPSD, nullptr}, {X86_INS_VCMPEQSD, nullptr}, {X86_INS_VCMPLTSD, nullptr}, {X86_INS_VCMPLESD, nullptr}, {X86_INS_VCMPUNORDSD, nullptr}, {X86_INS_VCMPNEQSD, nullptr}, {X86_INS_VCMPNLTSD, nullptr}, {X86_INS_VCMPNLESD, nullptr}, {X86_INS_VCMPORDSD, nullptr}, {X86_INS_VCMPEQ_UQSD, nullptr}, {X86_INS_VCMPNGESD, nullptr}, {X86_INS_VCMPNGTSD, nullptr}, {X86_INS_VCMPFALSESD, nullptr}, {X86_INS_VCMPNEQ_OQSD, nullptr}, {X86_INS_VCMPGESD, nullptr}, {X86_INS_VCMPGTSD, nullptr}, {X86_INS_VCMPTRUESD, nullptr}, {X86_INS_VCMPEQ_OSSD, nullptr}, {X86_INS_VCMPLT_OQSD, nullptr}, {X86_INS_VCMPLE_OQSD, nullptr}, {X86_INS_VCMPUNORD_SSD, nullptr}, {X86_INS_VCMPNEQ_USSD, nullptr}, {X86_INS_VCMPNLT_UQSD, nullptr}, {X86_INS_VCMPNLE_UQSD, nullptr}, {X86_INS_VCMPORD_SSD, nullptr}, {X86_INS_VCMPEQ_USSD, nullptr}, {X86_INS_VCMPNGE_UQSD, nullptr}, {X86_INS_VCMPNGT_UQSD, nullptr}, {X86_INS_VCMPFALSE_OSSD, nullptr}, {X86_INS_VCMPNEQ_OSSD, nullptr}, {X86_INS_VCMPGE_OQSD, nullptr}, {X86_INS_VCMPGT_OQSD, nullptr}, {X86_INS_VCMPTRUE_USSD, nullptr}, {X86_INS_VCMPPS, nullptr}, {X86_INS_VCMPEQPS, nullptr}, {X86_INS_VCMPLTPS, nullptr}, {X86_INS_VCMPLEPS, nullptr}, {X86_INS_VCMPUNORDPS, nullptr}, {X86_INS_VCMPNEQPS, nullptr}, {X86_INS_VCMPNLTPS, nullptr}, {X86_INS_VCMPNLEPS, nullptr}, {X86_INS_VCMPORDPS, nullptr}, {X86_INS_VCMPEQ_UQPS, nullptr}, {X86_INS_VCMPNGEPS, nullptr}, {X86_INS_VCMPNGTPS, nullptr}, {X86_INS_VCMPFALSEPS, nullptr}, {X86_INS_VCMPNEQ_OQPS, nullptr}, {X86_INS_VCMPGEPS, nullptr}, {X86_INS_VCMPGTPS, nullptr}, {X86_INS_VCMPTRUEPS, nullptr}, {X86_INS_VCMPEQ_OSPS, nullptr}, {X86_INS_VCMPLT_OQPS, nullptr}, {X86_INS_VCMPLE_OQPS, nullptr}, {X86_INS_VCMPUNORD_SPS, nullptr}, {X86_INS_VCMPNEQ_USPS, nullptr}, {X86_INS_VCMPNLT_UQPS, nullptr}, {X86_INS_VCMPNLE_UQPS, nullptr}, {X86_INS_VCMPORD_SPS, nullptr}, {X86_INS_VCMPEQ_USPS, nullptr}, {X86_INS_VCMPNGE_UQPS, nullptr}, {X86_INS_VCMPNGT_UQPS, nullptr}, {X86_INS_VCMPFALSE_OSPS, nullptr}, {X86_INS_VCMPNEQ_OSPS, nullptr}, {X86_INS_VCMPGE_OQPS, nullptr}, {X86_INS_VCMPGT_OQPS, nullptr}, {X86_INS_VCMPTRUE_USPS, nullptr}, {X86_INS_VCMPPD, nullptr}, {X86_INS_VCMPEQPD, nullptr}, {X86_INS_VCMPLTPD, nullptr}, {X86_INS_VCMPLEPD, nullptr}, {X86_INS_VCMPUNORDPD, nullptr}, {X86_INS_VCMPNEQPD, nullptr}, {X86_INS_VCMPNLTPD, nullptr}, {X86_INS_VCMPNLEPD, nullptr}, {X86_INS_VCMPORDPD, nullptr}, {X86_INS_VCMPEQ_UQPD, nullptr}, {X86_INS_VCMPNGEPD, nullptr}, {X86_INS_VCMPNGTPD, nullptr}, {X86_INS_VCMPFALSEPD, nullptr}, {X86_INS_VCMPNEQ_OQPD, nullptr}, {X86_INS_VCMPGEPD, nullptr}, {X86_INS_VCMPGTPD, nullptr}, {X86_INS_VCMPTRUEPD, nullptr}, {X86_INS_VCMPEQ_OSPD, nullptr}, {X86_INS_VCMPLT_OQPD, nullptr}, {X86_INS_VCMPLE_OQPD, nullptr}, {X86_INS_VCMPUNORD_SPD, nullptr}, {X86_INS_VCMPNEQ_USPD, nullptr}, {X86_INS_VCMPNLT_UQPD, nullptr}, {X86_INS_VCMPNLE_UQPD, nullptr}, {X86_INS_VCMPORD_SPD, nullptr}, {X86_INS_VCMPEQ_USPD, nullptr}, {X86_INS_VCMPNGE_UQPD, nullptr}, {X86_INS_VCMPNGT_UQPD, nullptr}, {X86_INS_VCMPFALSE_OSPD, nullptr}, {X86_INS_VCMPNEQ_OSPD, nullptr}, {X86_INS_VCMPGE_OQPD, nullptr}, {X86_INS_VCMPGT_OQPD, nullptr}, {X86_INS_VCMPTRUE_USPD, nullptr}, {X86_INS_ENDING, nullptr}, // mark the end of the list of insn }; } // namespace capstone2llvmir } // namespace retdec
33.376866
98
0.744131
[ "vector" ]
a3783bd18588f0a4d0a2907a7428503894dadb74
2,135
hpp
C++
Source/Core/Engine/BasicActions.hpp
andraantariksa/PlasmaEngine
481ea008ed15b531476533a6f675bc9bfdfa7db2
[ "MIT" ]
70
2020-10-19T15:17:36.000Z
2022-03-29T06:23:20.000Z
Source/Core/Engine/BasicActions.hpp
andraantariksa/PlasmaEngine
481ea008ed15b531476533a6f675bc9bfdfa7db2
[ "MIT" ]
90
2020-10-21T09:56:03.000Z
2022-02-19T18:36:37.000Z
Source/Core/Engine/BasicActions.hpp
andraantariksa/PlasmaEngine
481ea008ed15b531476533a6f675bc9bfdfa7db2
[ "MIT" ]
13
2020-12-28T20:18:57.000Z
2022-01-20T08:43:29.000Z
// MIT Licensed (see LICENSE.md). #pragma once namespace Plasma { ////Basic Actions//////// /// Delay action. Delays by time in seconds. class ActionDelay : public Action { public: LightningDeclareType(ActionDelay, TypeCopyMode::ReferenceType); ActionDelay(float duration) : mTimeLeft(duration) { mFlags.SetFlag(ActionFlag::Schedulable); } ActionState::Enum Update(float dt) override { mFlags.SetFlag(ActionFlag::Started); mTimeLeft -= dt; if (mTimeLeft > 0.0f) return ActionState::Running; else return ActionState::Completed; } private: float mTimeLeft; }; class ActionDelayOnce : public Action { public: ActionDelayOnce() { } ActionState::Enum Update(float dt) override { if (!mFlags.IsSet(ActionFlag::Started)) { mFlags.SetFlag(ActionFlag::Started); return ActionState::Running; } else { return ActionState::Completed; } } private: }; /// Temporary action (needs to be reworked for lightning) that sends an /// event to an object. Takes ownership of the event to send. class ActionEvent : public Action { public: String mEventName; HandleOf<Event> mEvent; HandleOf<Object> mTargetObject; ActionEvent(Object* targetObject, StringParam eventNameToSend, Event* eventToSend) { mTargetObject = targetObject; mEventName = eventNameToSend; mEvent = eventToSend; } ActionState::Enum Update(float dt) override { if (mTargetObject.IsNull()) return ActionState::Completed; if (Object* eventObject = mTargetObject) { Event* event = mEvent; if (event == nullptr) { // Should this be an error? DoNotifyError("ActionEvent Failed", "The event inside the action was destructed. Did you " "send a C++ event? C++ events are destructed and " "generally cannot be saved for later."); return ActionState::Completed; } eventObject->GetDispatcher()->Dispatch(mEventName, event); mEvent.Delete(); } return ActionState::Completed; } }; } // namespace Plasma
21.35
84
0.652459
[ "object" ]
a37bd4582edc8fc8edac008a74bd52803481b0d0
6,791
cc
C++
tensorflow_serving/servables/tensorflow/saved_model_warmup.cc
yuanbaopeng/serving
39bec581e9bd8ba1c8d4af4e01e04c4ca70721e6
[ "Apache-2.0" ]
2
2019-07-08T22:26:33.000Z
2019-08-28T03:36:48.000Z
tensorflow_serving/servables/tensorflow/saved_model_warmup.cc
LiZeB/serving
5ec333eb438de58216ff95a2fe50d92e9d6876a8
[ "Apache-2.0" ]
null
null
null
tensorflow_serving/servables/tensorflow/saved_model_warmup.cc
LiZeB/serving
5ec333eb438de58216ff95a2fe50d92e9d6876a8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Google Inc. 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_serving/servables/tensorflow/saved_model_warmup.h" #include "google/protobuf/wrappers.pb.h" #include "tensorflow/cc/saved_model/constants.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/io/record_reader.h" #include "tensorflow/core/lib/monitoring/sampler.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/protobuf/config.pb.h" #include "tensorflow_serving/apis/prediction_log.pb.h" #include "tensorflow_serving/servables/tensorflow/classifier.h" #include "tensorflow_serving/servables/tensorflow/multi_inference.h" #include "tensorflow_serving/servables/tensorflow/predict_util.h" #include "tensorflow_serving/servables/tensorflow/regressor.h" #include "tensorflow_serving/servables/tensorflow/util.h" namespace tensorflow { namespace serving { namespace { auto* model_warm_up_latency = monitoring::Sampler<2>::New( { "/tensorflow/serving/model_warmup_latency", "Distribution of wall time (in microseconds) for warming up the model.", "model_path", "status", }, // Scale of 10, power of 1.8 with bucket count 33 (~20 minutes). monitoring::Buckets::Exponential(10, 1.8, 33)); uint64 GetLatencyMicroseconds(const uint64 start_microseconds) { const uint64 end_microseconds = Env::Default()->NowMicros(); // Avoid clock skew. if (end_microseconds < start_microseconds) return 0; return end_microseconds - start_microseconds; } Status RunWarmupRequest(const PredictionLog& warmup_record, const RunOptions& run_options, const MetaGraphDef& meta_graph_def, Session* session) { switch (warmup_record.log_type_case()) { case PredictionLog::kRegressLog: { RegressionResponse response; TF_RETURN_IF_ERROR(RunRegress(run_options, meta_graph_def, {}, session, warmup_record.regress_log().request(), &response)); } break; case PredictionLog::kClassifyLog: { ClassificationResponse response; TF_RETURN_IF_ERROR(RunClassify(run_options, meta_graph_def, {}, session, warmup_record.classify_log().request(), &response)); } break; case PredictionLog::kPredictLog: { PredictResponse response; TF_RETURN_IF_ERROR(RunPredict(run_options, meta_graph_def, {}, session, warmup_record.predict_log().request(), &response)); } break; case PredictionLog::kMultiInferenceLog: { MultiInferenceResponse response; TF_RETURN_IF_ERROR(RunMultiInference( run_options, meta_graph_def, {}, session, warmup_record.multi_inference_log().request(), &response)); } break; case PredictionLog::kSessionRunLog: return errors::Unimplemented(strings::StrCat( "Unsupported log_type for warmup: ", warmup_record.log_type_case())); default: break; } return Status::OK(); } } // namespace constexpr char WarmupConsts::kRequestsFileName[]; constexpr int WarmupConsts::kMaxNumRecords; Status RunSavedModelWarmup(const ModelWarmupOptions& model_warmup_options, const RunOptions& run_options, const string& export_dir, SavedModelBundle* bundle) { const uint64 start_microseconds = Env::Default()->NowMicros(); const string warmup_path = io::JoinPath(export_dir, kSavedModelAssetsExtraDirectory, WarmupConsts::kRequestsFileName); if (!tensorflow::Env::Default()->FilesExist({warmup_path}, nullptr)) { LOG(INFO) << "No warmup data file found at " << warmup_path; // Having warmup data is optional, return OK return Status::OK(); } const int num_request_iterations = [&]() { if (model_warmup_options.has_num_request_iterations()) { return model_warmup_options.num_request_iterations().value(); } // Default of 1. return 1; }(); LOG(INFO) << "Starting to read warmup data for model at " << warmup_path << " with model-warmup-options " << model_warmup_options.DebugString(); std::unique_ptr<tensorflow::RandomAccessFile> tf_record_file; TF_RETURN_IF_ERROR(tensorflow::Env::Default()->NewRandomAccessFile( warmup_path, &tf_record_file)); std::unique_ptr<tensorflow::io::SequentialRecordReader> tf_record_file_reader; tf_record_file_reader.reset( new tensorflow::io::SequentialRecordReader(tf_record_file.get())); int num_warmup_records = 0; string record; Status status = tf_record_file_reader->ReadRecord(&record); tensorflow::serving::PredictionLog prediction_log; while (status.ok()) { if (!prediction_log.ParseFromString(record)) { return errors::InvalidArgument(strings::StrCat( "Failed to parse warmup record: ", record, " from ", warmup_path)); } for (int i = 0; i < num_request_iterations; ++i) { TF_RETURN_IF_ERROR(RunWarmupRequest(prediction_log, run_options, bundle->meta_graph_def, bundle->session.get())); } ++num_warmup_records; if (num_warmup_records > WarmupConsts::kMaxNumRecords) { return errors::InvalidArgument( "Number of warmup records exceeeds the maximum (", WarmupConsts::kMaxNumRecords, ") at ", warmup_path); } status = tf_record_file_reader->ReadRecord(&record); } const auto warmup_latency = GetLatencyMicroseconds(start_microseconds); model_warm_up_latency->GetCell(export_dir, status.ToString()) ->Add(warmup_latency); // OUT_OF_RANGE error means EOF was reached, do not return error in this case if (!errors::IsOutOfRange(status)) { return status; } LOG(INFO) << "Finished reading warmup data for model at " << warmup_path << ". Number of warmup records read: " << num_warmup_records << ". Elapsed time (microseconds): " << warmup_latency << "."; return Status::OK(); } } // namespace serving } // namespace tensorflow
40.909639
80
0.67884
[ "model" ]
a384ba1739bd61849afbffdae9e42fd9bef3cd55
20,422
hpp
C++
include/ecto/python/streambuf.hpp
fujiehuang/ecto
fea744337aa1fad1397c9a3ba5baa143993cb5eb
[ "BSD-3-Clause" ]
null
null
null
include/ecto/python/streambuf.hpp
fujiehuang/ecto
fea744337aa1fad1397c9a3ba5baa143993cb5eb
[ "BSD-3-Clause" ]
null
null
null
include/ecto/python/streambuf.hpp
fujiehuang/ecto
fea744337aa1fad1397c9a3ba5baa143993cb5eb
[ "BSD-3-Clause" ]
null
null
null
// Willow Garage BSD License not applicable #pragma once // original source from http://cci.lbl.gov/cctbx_sources/boost_adaptbx/python_streambuf.h // original license //*** Copyright Notice *** // //cctbx Copyright (c) 2006, The Regents of the University of //California, through Lawrence Berkeley National Laboratory (subject to //receipt of any required approvals from the U.S. Dept. of Energy). All //rights reserved. // //If you have questions about your rights to use or distribute this //software, please contact Berkeley Lab's Technology Transfer Department //at TTD@lbl.gov referring to "cctbx (LBNL Ref CR-1726)" // //This software package includes code written by others which may be //governed by separate license agreements. Please refer to the associated //licenses for further details. // //NOTICE. This software was developed under funding from the U.S. //Department of Energy. As such, the U.S. Government has been granted for //itself and others acting on its behalf a paid-up, nonexclusive, //irrevocable, worldwide license in the Software to reproduce, prepare //derivative works, and perform publicly and display publicly. Beginning //five (5) years after the date permission to assert copyright is obtained //from the U.S. Department of Energy, and subject to any subsequent five //(5) year renewals, the U.S. Government is granted for itself and others //acting on its behalf a paid-up, nonexclusive, irrevocable, worldwide //license in the Software to reproduce, prepare derivative works, //distribute copies to the public, perform publicly and display publicly, //and to permit others to do so. // //*** License agreement *** // //cctbx Copyright (c) 2006, The Regents of the University of //California, through Lawrence Berkeley National Laboratory (subject to //receipt of any required approvals from the U.S. Dept. of Energy). 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 University of California, Lawrence Berkeley //National Laboratory, U.S. Dept. of Energy 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 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. // //You are under no obligation whatsoever to provide any bug fixes, //patches, or upgrades to the features, functionality or performance of //the source code ("Enhancements") to anyone; however, if you choose to //make your Enhancements available either publicly, or directly to //Lawrence Berkeley National Laboratory, without imposing a separate //written license agreement for such Enhancements, then you hereby grant //the following license: a non-exclusive, royalty-free perpetual license //to install, use, modify, prepare derivative works, incorporate into //other computer software, distribute, and sublicense such enhancements or //derivative works thereof, in binary and source code form. #include <boost/python/object.hpp> #include <boost/python/str.hpp> #include <boost/python/extract.hpp> #include <boost/optional.hpp> #include <boost/utility/typed_in_place_factory.hpp> #include <streambuf> #include <iostream> namespace ecto { namespace py { namespace bp = boost::python; /// A stream buffer getting data from and putting data into a Python file object /** The aims are as follow: - Given a C++ function acting on a standard stream, e.g. \code void read_inputs(std::istream& input) { ... input >> something >> something_else; } \endcode and given a piece of Python code which creates a file-like object, to be able to pass this file object to that C++ function, e.g. \code import gzip gzip_file_obj = gzip.GzipFile(...) read_inputs(gzip_file_obj) \endcode and have the standard stream pull data from and put data into the Python file object. - When Python \c read_inputs() returns, the Python object is able to continue reading or writing where the C++ code left off. - Operations in C++ on mere files should be competitively fast compared to the direct use of \c std::fstream. \b Motivation - the standard Python library offer of file-like objects (files, compressed files and archives, network, ...) is far superior to the offer of streams in the C++ standard library and Boost C++ libraries. - i/o code involves a fair amount of text processing which is more efficiently prototyped in Python but then one may need to rewrite a time-critical part in C++, in as seamless a manner as possible. \b Usage This is 2-step: - a trivial wrapper function \code using ecto::python::streambuf; void read_inputs_wrapper(streambuf& input) { streambuf::istream is(input); read_inputs(is); } def("read_inputs", read_inputs_wrapper); \endcode which has to be written every time one wants a Python binding for such a C++ function. - the Python side \code from boost.python import streambuf read_inputs(streambuf(python_file_obj=obj, buffer_size=1024)) \endcode \c buffer_size is optional. See also: \c default_buffer_size Note: references are to the C++ standard (the numbers between parentheses at the end of references are margin markers). */ inline std::string file_and_line_as_string( const char* file, long line) { std::ostringstream o; o << file << "(" << line << ")"; return o.str(); } #define TBXX_ASSERT(condition) \ if (!(condition)) { \ throw std::runtime_error( \ file_and_line_as_string( \ __FILE__, __LINE__) \ + ": ASSERT(" #condition ") failure."); \ } #define TBXX_UNREACHABLE_ERROR() \ std::runtime_error( \ "Control flow passes through branch that should be unreachable: " \ + file_and_line_as_string(__FILE__, __LINE__)) class streambuf : public std::basic_streambuf<char> { private: typedef std::basic_streambuf<char> base_t; public: /* The syntax using base_t::char_type; would be nicer but Visual Studio C++ 8 chokes on it */ typedef base_t::char_type char_type; typedef base_t::int_type int_type; typedef base_t::pos_type pos_type; typedef base_t::off_type off_type; typedef base_t::traits_type traits_type; // work around Visual C++ 7.1 problem inline static int traits_type_eof() { return traits_type::eof(); } /// The default size of the read and write buffer. /** They are respectively used to buffer data read from and data written to the Python file object. It can be modified from Python. */ static std::size_t default_buffer_size; /// Construct from a Python file object /** if buffer_size is 0 the current default_buffer_size is used. */ streambuf( bp::object& python_file_obj, std::size_t buffer_size_=0) : py_read (getattr(python_file_obj, "read", bp::object())), py_write(getattr(python_file_obj, "write", bp::object())), py_seek (getattr(python_file_obj, "seek", bp::object())), py_tell (getattr(python_file_obj, "tell", bp::object())), buffer_size(buffer_size_ != 0 ? buffer_size_ : default_buffer_size), write_buffer(0), pos_of_read_buffer_end_in_py_file(0), pos_of_write_buffer_end_in_py_file(buffer_size), farthest_pptr(0), file_obj(python_file_obj) { TBXX_ASSERT(buffer_size != 0); /* Some Python file objects (e.g. sys.stdout and sys.stdin) have non-functional seek and tell. If so, assign None to py_tell and py_seek. */ if (py_tell != bp::object()) { try { py_tell(); } catch (bp::error_already_set&) { py_tell = bp::object(); py_seek = bp::object(); /* Boost.Python does not do any Python exception handling whatsoever So we need to catch it by hand like so. */ PyErr_Clear(); } } if (py_write != bp::object()) { // C-like string to make debugging easier write_buffer = new char[buffer_size + 1]; write_buffer[buffer_size] = '\0'; setp(write_buffer, write_buffer + buffer_size); // 27.5.2.4.5 (5) farthest_pptr = pptr(); } else { // The first attempt at output will result in a call to overflow setp(0, 0); } if (py_tell != bp::object()) { off_type py_pos = bp::extract<off_type>(py_tell()); pos_of_read_buffer_end_in_py_file = py_pos; pos_of_write_buffer_end_in_py_file = py_pos; } } /// Mundane destructor freeing the allocated resources virtual ~streambuf() { if (write_buffer) delete[] write_buffer; } /// C.f. C++ standard section 27.5.2.4.3 /** It is essential to override this virtual function for the stream member function readsome to work correctly (c.f. 27.6.1.3, alinea 30) */ virtual std::streamsize showmanyc() { int_type const failure = traits_type::eof(); int_type status = underflow(); if (status == failure) return -1; return egptr() - gptr(); } /// C.f. C++ standard section 27.5.2.4.3 virtual int_type underflow() { int_type const failure = traits_type::eof(); if (py_read == bp::object()) { throw std::invalid_argument( "That Python file object has no 'read' attribute"); } read_buffer = py_read(buffer_size); char *read_buffer_data; bp::ssize_t py_n_read; if (PyBytes_AsStringAndSize(read_buffer.ptr(), &read_buffer_data, &py_n_read) == -1) { setg(0, 0, 0); throw std::invalid_argument( "The method 'read' of the Python file object " "did not return a string."); } off_type n_read = (off_type)py_n_read; pos_of_read_buffer_end_in_py_file += n_read; setg(read_buffer_data, read_buffer_data, read_buffer_data + n_read); // ^^^27.5.2.3.1 (4) if (n_read == 0) return failure; return traits_type::to_int_type(read_buffer_data[0]); } /// C.f. C++ standard section 27.5.2.4.5 virtual int_type overflow(int_type c=traits_type_eof()) { if (py_write == bp::object()) { throw std::invalid_argument( "That Python file object has no 'write' attribute"); } farthest_pptr = std::max(farthest_pptr, pptr()); off_type n_written = (off_type)(farthest_pptr - pbase()); bp::str chunk(pbase(), farthest_pptr); py_write(chunk); if (!traits_type::eq_int_type(c, traits_type::eof())) { py_write(traits_type::to_char_type(c)); n_written++; } if (n_written) { pos_of_write_buffer_end_in_py_file += n_written; setp(pbase(), epptr()); // ^^^ 27.5.2.4.5 (5) farthest_pptr = pptr(); } return traits_type::eq_int_type( c, traits_type::eof()) ? traits_type::not_eof(c) : c; } /// Update the python file to reflect the state of this stream buffer /** Empty the write buffer into the Python file object and set the seek position of the latter accordingly (C++ standard section 27.5.2.4.2). If there is no write buffer or it is empty, but there is a non-empty read buffer, set the Python file object seek position to the seek position in that read buffer. */ virtual int sync() { int result = 0; farthest_pptr = std::max(farthest_pptr, pptr()); if (farthest_pptr && farthest_pptr > pbase()) { off_type delta = pptr() - farthest_pptr; int_type status = overflow(); if (traits_type::eq_int_type(status, traits_type::eof())) result = -1; if (py_seek != bp::object()) py_seek(delta, 1); } else if (gptr() && gptr() < egptr()) { if (py_seek != bp::object()) py_seek(gptr() - egptr(), 1); } return result; } /// C.f. C++ standard section 27.5.2.4.2 /** This implementation is optimised to look whether the position is within the buffers, so as to avoid calling Python seek or tell. It is important for many applications that the overhead of calling into Python is avoided as much as possible (e.g. parsers which may do a lot of backtracking) */ virtual pos_type seekoff(off_type off, std::ios_base::seekdir way, std::ios_base::openmode which= std::ios_base::in | std::ios_base::out) { /* In practice, "which" is either std::ios_base::in or out since we end up here because either seekp or seekg was called on the stream using this buffer. That simplifies the code in a few places. */ int const failure = off_type(-1); if (py_seek == bp::object()) { throw std::invalid_argument( "That Python file object has no 'seek' attribute"); } // we need the read buffer to contain something! if (which == std::ios_base::in && !gptr()) { if (traits_type::eq_int_type(underflow(), traits_type::eof())) { return failure; } } // compute the whence parameter for Python seek int whence; switch (way) { case std::ios_base::beg: whence = 0; break; case std::ios_base::cur: whence = 1; break; case std::ios_base::end: whence = 2; break; default: return failure; } // Let's have a go boost::optional<off_type> result = seekoff_without_calling_python( off, way, which); if (!result) { // we need to call Python if (which == std::ios_base::out) overflow(); if (way == std::ios_base::cur) { if (which == std::ios_base::in) off -= egptr() - gptr(); else if (which == std::ios_base::out) off += pptr() - pbase(); } py_seek(off, whence); result = off_type(bp::extract<off_type>(py_tell())); if (which == std::ios_base::in) underflow(); } return *result; } /// C.f. C++ standard section 27.5.2.4.2 virtual pos_type seekpos(pos_type sp, std::ios_base::openmode which= std::ios_base::in | std::ios_base::out) { return streambuf::seekoff(sp, std::ios_base::beg, which); } private: bp::object py_read, py_write, py_seek, py_tell; std::size_t buffer_size; /* This is actually a Python string and the actual read buffer is its internal data, i.e. an array of characters. We use a Boost.Python object so as to hold on it: as a result, the actual buffer can't go away. */ bp::object read_buffer; /* A mere array of char's allocated on the heap at construction time and de-allocated only at destruction time. */ char *write_buffer; off_type pos_of_read_buffer_end_in_py_file, pos_of_write_buffer_end_in_py_file; // the farthest place the buffer has been written into char *farthest_pptr; boost::optional<off_type> seekoff_without_calling_python( off_type off, std::ios_base::seekdir way, std::ios_base::openmode which) { boost::optional<off_type> const failure; // Buffer range and current position off_type buf_begin, buf_end, buf_cur, upper_bound; off_type pos_of_buffer_end_in_py_file; if (which == std::ios_base::in) { pos_of_buffer_end_in_py_file = pos_of_read_buffer_end_in_py_file; buf_begin = reinterpret_cast<std::streamsize>(eback()); buf_cur = reinterpret_cast<std::streamsize>(gptr()); buf_end = reinterpret_cast<std::streamsize>(egptr()); upper_bound = buf_end; } else if (which == std::ios_base::out) { pos_of_buffer_end_in_py_file = pos_of_write_buffer_end_in_py_file; buf_begin = reinterpret_cast<std::streamsize>(pbase()); buf_cur = reinterpret_cast<std::streamsize>(pptr()); buf_end = reinterpret_cast<std::streamsize>(epptr()); farthest_pptr = std::max(farthest_pptr, pptr()); upper_bound = reinterpret_cast<std::streamsize>(farthest_pptr) + 1; } else { throw TBXX_UNREACHABLE_ERROR(); } // Sought position in "buffer coordinate" off_type buf_sought; if (way == std::ios_base::cur) { buf_sought = buf_cur + off; } else if (way == std::ios_base::beg) { buf_sought = buf_end + (off - pos_of_buffer_end_in_py_file); } else if (way == std::ios_base::end) { return failure; } else { throw TBXX_UNREACHABLE_ERROR(); } // if the sought position is not in the buffer, give up if (buf_sought < buf_begin || buf_sought >= upper_bound) return failure; // we are in wonderland if (which == std::ios_base::in) gbump(buf_sought - buf_cur); else if (which == std::ios_base::out) pbump(buf_sought - buf_cur); return pos_of_buffer_end_in_py_file + (buf_sought - buf_end); } public: class istream : public std::istream { public: istream(streambuf& buf) : std::istream(&buf) { exceptions(std::ios_base::badbit); } ~istream() { if (this->good()) this->sync(); } }; class ostream : public std::ostream { public: ostream(streambuf& buf) : std::ostream(&buf) { exceptions(std::ios_base::badbit); } ~ostream() { if (this->good()) this->flush(); } }; bp::object file_obj; //original handle }; std::size_t streambuf::default_buffer_size = 1024; struct streambuf_capsule { streambuf python_streambuf; streambuf_capsule( bp::object& python_file_obj, std::size_t buffer_size=0) : python_streambuf(python_file_obj, buffer_size) {} bp::object get_original_file() const {return python_streambuf.file_obj;} }; struct ostream : streambuf_capsule, streambuf::ostream { ostream( bp::object& python_file_obj, std::size_t buffer_size=0) : streambuf_capsule(python_file_obj, buffer_size), streambuf::ostream(python_streambuf) {} ~ostream() { try { if (this->good()) this->flush(); } catch (bp::error_already_set&) { PyErr_Clear(); // fixme this should not throw in the detructor // throw std::runtime_error( std::cerr << ( "Problem closing python ostream.\n" " Known limitation: the error is unrecoverable. Sorry.\n" " Suggestion for programmer: add ostream.flush() before" " returning.") << std::endl; } } }; struct istream : streambuf_capsule, streambuf::istream { istream( bp::object& python_file_obj, std::size_t buffer_size=0) : streambuf_capsule(python_file_obj, buffer_size), streambuf::istream(python_streambuf) {} }; }} // boost_adaptbx::python
34.496622
89
0.648125
[ "object" ]
a388cd39016764fb36a2c1a2dfdee8428a1ca624
11,291
tcc
C++
include/mpm_explicit.tcc
xinyiqian97/mpm
1ccc3d201f663e0fa99850448816d1f803840e49
[ "MIT" ]
null
null
null
include/mpm_explicit.tcc
xinyiqian97/mpm
1ccc3d201f663e0fa99850448816d1f803840e49
[ "MIT" ]
null
null
null
include/mpm_explicit.tcc
xinyiqian97/mpm
1ccc3d201f663e0fa99850448816d1f803840e49
[ "MIT" ]
null
null
null
//! Constructor template <unsigned Tdim> mpm::MPMExplicit<Tdim>::MPMExplicit(std::unique_ptr<IO>&& io) : mpm::MPMBase<Tdim>(std::move(io)) { //! Logger console_ = spdlog::get("MPMExplicit"); } //! MPM Explicit solver template <unsigned Tdim> bool mpm::MPMExplicit<Tdim>::solve() { bool status = true; // Get analysis type USL/USF if (io_->analysis_type() == "MPMExplicitUSL2D" || io_->analysis_type() == "MPMExplicitUSL3D") this->usl_ = true; console_->error("Analysis{} {}", io_->analysis_type()); // Initialise MPI rank and size int mpi_rank = 0; int mpi_size = 1; #ifdef USE_MPI // Get MPI rank MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); // Get number of MPI ranks MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); #endif // Phase const unsigned phase = 0; // Test if checkpoint resume is needed bool resume = false; if (analysis_.find("resume") != analysis_.end()) resume = analysis_["resume"]["resume"].template get<bool>(); // Pressure smoothing if (analysis_.find("pressure_smoothing") != analysis_.end()) pressure_smoothing_ = analysis_["pressure_smoothing"].template get<bool>(); // Initialise material bool mat_status = this->initialise_materials(); if (!mat_status) status = false; // Initialise mesh bool mesh_status = this->initialise_mesh(); if (!mesh_status) status = false; // Initialise particles bool particle_status = this->initialise_particles(); if (!particle_status) status = false; // Assign material to particles // Get particle properties auto particle_props = io_->json_object("particle"); // Material id const auto material_id = particle_props["material_id"].template get<unsigned>(); // Get material from list of materials auto material = materials_.at(material_id); // Iterate over each particle to assign material mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::assign_material, std::placeholders::_1, material)); // Assign material to particle sets if (particle_props["particle_sets"].size() != 0) { // Assign material to particles in the specific sets bool set_material_status = this->apply_properties_to_particles_sets(); } // Compute mass mesh_->iterate_over_particles(std::bind( &mpm::ParticleBase<Tdim>::compute_mass, std::placeholders::_1, phase)); // Check point resume if (resume) this->checkpoint_resume(); auto solver_begin = std::chrono::steady_clock::now(); // Main loop for (; step_ < nsteps_; ++step_) { if (mpi_rank == 0) console_->info("Step: {} of {}.\n", step_, nsteps_); // Create a TBB task group tbb::task_group task_group; // Spawn a task for initialising nodes and cells task_group.run([&] { // Initialise nodes mesh_->iterate_over_nodes( std::bind(&mpm::NodeBase<Tdim>::initialise, std::placeholders::_1)); mesh_->iterate_over_cells( std::bind(&mpm::Cell<Tdim>::activate_nodes, std::placeholders::_1)); // mesh_->find_active_nodes(); }); // Spawn a task for particles task_group.run([&] { // Iterate over each particle to compute shapefn mesh_->iterate_over_particles(std::bind( &mpm::ParticleBase<Tdim>::compute_shapefn, std::placeholders::_1)); }); task_group.wait(); // Assign mass and momentum to nodes mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::map_mass_momentum_to_nodes, std::placeholders::_1, phase)); #ifdef USE_MPI // Run if there is more than a single MPI task if (mpi_size > 1) { // MPI all reduce nodal mass mesh_->allreduce_nodal_scalar_property( std::bind(&mpm::NodeBase<Tdim>::mass, std::placeholders::_1, phase), std::bind(&mpm::NodeBase<Tdim>::update_mass, std::placeholders::_1, false, phase, std::placeholders::_2)); // MPI all reduce nodal momentum mesh_->allreduce_nodal_vector_property( std::bind(&mpm::NodeBase<Tdim>::momentum, std::placeholders::_1, phase), std::bind(&mpm::NodeBase<Tdim>::update_momentum, std::placeholders::_1, false, phase, std::placeholders::_2)); } #endif // Compute nodal velocity mesh_->iterate_over_nodes_predicate( std::bind(&mpm::NodeBase<Tdim>::compute_velocity, std::placeholders::_1), std::bind(&mpm::NodeBase<Tdim>::status, std::placeholders::_1)); // Update stress first if (!usl_) { // Iterate over each particle to calculate strain mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_strain, std::placeholders::_1, phase, dt_)); // Iterate over each particle to update particle volume mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::update_volume_strainrate, std::placeholders::_1, phase, this->dt_)); // Pressure smoothing if (pressure_smoothing_) { // Assign pressure to nodes mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::map_pressure_to_nodes, std::placeholders::_1, phase)); #ifdef USE_MPI // Run if there is more than a single MPI task if (mpi_size > 1) { // MPI all reduce nodal pressure mesh_->allreduce_nodal_scalar_property( std::bind(&mpm::NodeBase<Tdim>::pressure, std::placeholders::_1, phase), std::bind(&mpm::NodeBase<Tdim>::update_pressure, std::placeholders::_1, false, phase, std::placeholders::_2)); } #endif // Smooth pressure over particles mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_pressure_smoothing, std::placeholders::_1, phase)); } // Iterate over each particle to compute stress mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_stress, std::placeholders::_1, phase)); } // Spawn a task for external force task_group.run([&] { // Iterate over each particle to compute nodal body force mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::map_body_force, std::placeholders::_1, phase, this->gravity_)); // Iterate over each particle to map traction force to nodes mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::map_traction_force, std::placeholders::_1, phase)); //! Apply nodal tractions if (nodal_tractions_) this->apply_nodal_tractions(); }); // Spawn a task for internal force task_group.run([&] { // Iterate over each particle to compute nodal internal force mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::map_internal_force, std::placeholders::_1, phase)); }); task_group.wait(); #ifdef USE_MPI // Run if there is more than a single MPI task if (mpi_size > 1) { // MPI all reduce external force mesh_->allreduce_nodal_vector_property( std::bind(&mpm::NodeBase<Tdim>::external_force, std::placeholders::_1, phase), std::bind(&mpm::NodeBase<Tdim>::update_external_force, std::placeholders::_1, false, phase, std::placeholders::_2)); // MPI all reduce internal force mesh_->allreduce_nodal_vector_property( std::bind(&mpm::NodeBase<Tdim>::internal_force, std::placeholders::_1, phase), std::bind(&mpm::NodeBase<Tdim>::update_internal_force, std::placeholders::_1, false, phase, std::placeholders::_2)); } #endif // Iterate over active nodes to compute acceleratation and velocity mesh_->iterate_over_nodes_predicate( std::bind(&mpm::NodeBase<Tdim>::compute_acceleration_velocity, std::placeholders::_1, phase, this->dt_), std::bind(&mpm::NodeBase<Tdim>::status, std::placeholders::_1)); // Use nodal velocity to update position if (velocity_update_) // Iterate over each particle to compute updated position mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_updated_position_velocity, std::placeholders::_1, phase, this->dt_)); else // Iterate over each particle to compute updated position mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_updated_position, std::placeholders::_1, phase, this->dt_)); // Update Stress Last if (usl_ == true) { // Iterate over each particle to calculate strain mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_strain, std::placeholders::_1, phase, dt_)); // Iterate over each particle to update particle volume mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::update_volume_strainrate, std::placeholders::_1, phase, this->dt_)); // Pressure smoothing if (pressure_smoothing_) { // Assign pressure to nodes mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::map_pressure_to_nodes, std::placeholders::_1, phase)); #ifdef USE_MPI // Run if there is more than a single MPI task if (mpi_size > 1) { // MPI all reduce nodal pressure mesh_->allreduce_nodal_scalar_property( std::bind(&mpm::NodeBase<Tdim>::pressure, std::placeholders::_1, phase), std::bind(&mpm::NodeBase<Tdim>::update_pressure, std::placeholders::_1, false, phase, std::placeholders::_2)); } #endif // Smooth pressure over particles mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_pressure_smoothing, std::placeholders::_1, phase)); } // Iterate over each particle to compute stress mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_stress, std::placeholders::_1, phase)); } // Locate particles auto unlocatable_particles = mesh_->locate_particles_mesh(); if (!unlocatable_particles.empty()) throw std::runtime_error("Particle outside the mesh domain"); if (step_ % output_steps_ == 0) { // HDF5 outputs this->write_hdf5(this->step_, this->nsteps_); #ifdef USE_VTK // VTK outputs this->write_vtk(this->step_, this->nsteps_); #endif } } auto solver_end = std::chrono::steady_clock::now(); console_->info("Rank {}, Explicit {} solver duration: {} ms", mpi_rank, (this->usl_ ? "USL" : "USF"), std::chrono::duration_cast<std::chrono::milliseconds>( solver_end - solver_begin) .count()); return status; }
35.506289
80
0.62014
[ "mesh" ]
a38a622bf7bbc9b40e6f171664c8fcf005179e33
35,543
cpp
C++
test/ocp/floating_base_split_ocp_test.cpp
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
1
2021-09-04T07:43:04.000Z
2021-09-04T07:43:04.000Z
test/ocp/floating_base_split_ocp_test.cpp
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
null
null
null
test/ocp/floating_base_split_ocp_test.cpp
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <memory> #include <gtest/gtest.h> #include "Eigen/Core" #include "idocp/robot/robot.hpp" #include "idocp/robot/contact_status.hpp" #include "idocp/ocp/split_ocp.hpp" #include "idocp/ocp/split_solution.hpp" #include "idocp/ocp/split_direction.hpp" #include "idocp/ocp/kkt_residual.hpp" #include "idocp/ocp/kkt_matrix.hpp" #include "idocp/cost/cost_function.hpp" #include "idocp/cost/cost_function_data.hpp" #include "idocp/cost/joint_space_cost.hpp" #include "idocp/constraints/constraints.hpp" #include "idocp/constraints/joint_position_lower_limit.hpp" #include "idocp/constraints/joint_position_upper_limit.hpp" #include "idocp/constraints/joint_velocity_lower_limit.hpp" #include "idocp/constraints/joint_velocity_upper_limit.hpp" #include "idocp/ocp/riccati_factorization.hpp" #include "idocp/ocp/riccati_gain.hpp" #include "idocp/ocp/riccati_matrix_factorizer.hpp" #include "idocp/ocp/riccati_matrix_inverter.hpp" namespace idocp { class FloatingBaseSplitOCPTest : public ::testing::Test { protected: virtual void SetUp() { srand((unsigned int) time(0)); urdf = "../urdf/anymal/anymal.urdf"; std::vector<int> contact_frames = {14, 24, 34, 44}; robot = Robot(urdf, contact_frames); std::random_device rnd; std::vector<bool> is_contact_active; for (const auto frame : contact_frames) { is_contact_active.push_back(rnd()%2==0); } contact_status = ContactStatus(robot.max_point_contacts()); contact_status.setContactStatus(is_contact_active); q_prev = Eigen::VectorXd::Zero(robot.dimq()); robot.generateFeasibleConfiguration(q_prev); s = SplitSolution::Random(robot, contact_status); s_next = SplitSolution::Random(robot, contact_status); s_tmp = SplitSolution::Random(robot, contact_status); d = SplitDirection::Random(robot, contact_status); d_next = SplitDirection::Random(robot, contact_status); dtau = std::abs(Eigen::VectorXd::Random(1)[0]); t = std::abs(Eigen::VectorXd::Random(1)[0]); auto joint_cost = std::make_shared<JointSpaceCost>(robot); const Eigen::VectorXd q_weight = Eigen::VectorXd::Random(robot.dimv()).array().abs(); Eigen::VectorXd q_ref = Eigen::VectorXd::Random(robot.dimq()); robot.normalizeConfiguration(q_ref); const Eigen::VectorXd v_weight = Eigen::VectorXd::Random(robot.dimv()).array().abs(); const Eigen::VectorXd v_ref = Eigen::VectorXd::Random(robot.dimv()); const Eigen::VectorXd a_weight = Eigen::VectorXd::Random(robot.dimv()).array().abs(); const Eigen::VectorXd a_ref = Eigen::VectorXd::Random(robot.dimv()); const Eigen::VectorXd u_weight = Eigen::VectorXd::Random(robot.dimv()).array().abs(); const Eigen::VectorXd u_ref = Eigen::VectorXd::Random(robot.dimv()); const Eigen::VectorXd qf_weight = Eigen::VectorXd::Random(robot.dimv()).array().abs(); const Eigen::VectorXd vf_weight = Eigen::VectorXd::Random(robot.dimv()).array().abs(); joint_cost->set_q_weight(q_weight); joint_cost->set_q_ref(q_ref); joint_cost->set_v_weight(v_weight); joint_cost->set_v_ref(v_ref); joint_cost->set_a_weight(a_weight); joint_cost->set_a_ref(a_ref); joint_cost->set_u_weight(u_weight); joint_cost->set_u_ref(u_ref); joint_cost->set_qf_weight(qf_weight); joint_cost->set_vf_weight(vf_weight); cost = std::make_shared<CostFunction>(); cost->push_back(joint_cost); cost_data = cost->createCostFunctionData(robot); constraints = std::make_shared<Constraints>(); auto joint_lower_limit = std::make_shared<JointPositionLowerLimit>(robot); auto joint_upper_limit = std::make_shared<JointPositionUpperLimit>(robot); auto velocity_lower_limit = std::make_shared<JointVelocityLowerLimit>(robot); auto velocity_upper_limit = std::make_shared<JointVelocityUpperLimit>(robot); constraints->push_back(joint_upper_limit); constraints->push_back(joint_lower_limit); constraints->push_back(velocity_lower_limit); constraints->push_back(velocity_upper_limit); constraints_data = constraints->createConstraintsData(robot); kkt_matrix = KKTMatrix(robot); kkt_residual = KKTResidual(robot); kkt_matrix.setContactStatus(contact_status); kkt_residual.setContactStatus(contact_status); robot_dynamics = RobotDynamics(robot); gain = RiccatiGain(robot); factorizer = RiccatiMatrixFactorizer(robot); inverter = RiccatiMatrixInverter(robot); gain.setContactStatus(contact_status); inverter.setContactStatus(contact_status); } virtual void TearDown() { } double dtau, t; std::string urdf; Robot robot; ContactStatus contact_status; std::shared_ptr<CostFunction> cost; CostFunctionData cost_data; std::shared_ptr<Constraints> constraints; ConstraintsData constraints_data; Eigen::VectorXd q_prev; SplitSolution s, s_next, s_tmp; SplitDirection d, d_next; KKTMatrix kkt_matrix; KKTResidual kkt_residual; RobotDynamics robot_dynamics; RiccatiGain gain; RiccatiMatrixFactorizer factorizer; RiccatiMatrixInverter inverter; }; TEST_F(FloatingBaseSplitOCPTest, isFeasible) { SplitOCP ocp(robot, cost, constraints); EXPECT_EQ(constraints->isFeasible(robot, constraints_data, s), ocp.isFeasible(robot, s)); } TEST_F(FloatingBaseSplitOCPTest, KKTErrorNormOnlyStateEquation) { auto empty_cost = std::make_shared<CostFunction>(); auto empty_constraints = std::make_shared<Constraints>(); contact_status.setContactStatus(std::vector<bool>({false, false, false, false})); kkt_residual.setContactStatus(contact_status); kkt_matrix.setContactStatus(contact_status); s.setContactStatus(contact_status); SplitOCP ocp(robot, empty_cost, empty_constraints); robot.RNEA(s.q, s.v, s.a, s.u); s.beta.setZero(); s.mu_stack().setZero(); ocp.initConstraints(robot, 2, dtau, s); constraints->setSlackAndDual(robot, constraints_data, dtau, s); ocp.computeKKTResidual(robot, contact_status, t, dtau, q_prev, s, s_next); const double kkt_error = ocp.squaredNormKKTResidual(dtau); robot.subtractConfiguration(s.q, s_next.q, kkt_residual.Fq()); robot.dSubtractdConfigurationPlus(s.q, s_next.q, kkt_matrix.Fqq); robot.dSubtractdConfigurationMinus(q_prev, s.q, kkt_matrix.Fqq_prev); kkt_residual.Fq() += dtau * s.v; kkt_residual.Fv() = s.v + dtau * s.a - s_next.v; kkt_residual.lq() = kkt_matrix.Fqq.transpose() * s_next.lmd + kkt_matrix.Fqq_prev.transpose() * s.lmd; kkt_residual.lv() = dtau * s_next.lmd + s_next.gmm - s.gmm; kkt_residual.la() = dtau * s_next.gmm; const double kkt_error_ref = kkt_residual.Fq().squaredNorm() + kkt_residual.Fv().squaredNorm() + kkt_residual.lq().squaredNorm() + kkt_residual.lv().squaredNorm() + kkt_residual.la().squaredNorm() + dtau*dtau*s.u.head(6).squaredNorm(); EXPECT_DOUBLE_EQ(kkt_error, kkt_error_ref); const auto pair = ocp.costAndConstraintViolation(robot, t, dtau, s); EXPECT_DOUBLE_EQ(pair.first, 0); } TEST_F(FloatingBaseSplitOCPTest, KKTErrorNormStateEquationAndInverseDynamics) { auto empty_cost = std::make_shared<CostFunction>(); auto empty_constraints = std::make_shared<Constraints>(); contact_status.setContactStatus(std::vector<bool>({false, false, false, false})); kkt_residual.setContactStatus(contact_status); kkt_matrix.setContactStatus(contact_status); s.setContactStatus(contact_status); s.mu_stack().setZero(); SplitOCP ocp(robot, empty_cost, empty_constraints); ocp.computeKKTResidual(robot, contact_status, t, dtau, q_prev, s, s_next); const double kkt_error = ocp.squaredNormKKTResidual(dtau); robot.subtractConfiguration(s.q, s_next.q, kkt_residual.Fq()); robot.dSubtractdConfigurationPlus(s.q, s_next.q, kkt_matrix.Fqq); robot.dSubtractdConfigurationMinus(q_prev, s.q, kkt_matrix.Fqq_prev); kkt_residual.Fq() += dtau * s.v; kkt_residual.Fv() = s.v + dtau * s.a - s_next.v; kkt_residual.lq() = kkt_matrix.Fqq.transpose() * s_next.lmd + kkt_matrix.Fqq_prev.transpose() * s.lmd; kkt_residual.lv() = dtau * s_next.lmd + s_next.gmm - s.gmm; kkt_residual.la() = dtau * s_next.gmm; Eigen::VectorXd u_res = Eigen::VectorXd::Zero(robot.dimv()); Eigen::MatrixXd du_dq = Eigen::MatrixXd::Zero(robot.dimv(), robot.dimv()); Eigen::MatrixXd du_dv = Eigen::MatrixXd::Zero(robot.dimv(), robot.dimv()); Eigen::MatrixXd du_da = Eigen::MatrixXd::Zero(robot.dimv(), robot.dimv()); robot.RNEA(s.q, s.v, s.a, kkt_residual.u_res); kkt_residual.u_res -= s.u; robot.RNEADerivatives(s.q, s.v, s.a, du_dq, du_dv, du_da); kkt_residual.lq() += dtau * du_dq.transpose() * s.beta; kkt_residual.lv() += dtau * du_dv.transpose() * s.beta; kkt_residual.la() += dtau * du_da.transpose() * s.beta; kkt_residual.lu -= dtau * s.beta; double kkt_error_ref = kkt_residual.Fq().squaredNorm() + kkt_residual.Fv().squaredNorm() + kkt_residual.lq().squaredNorm() + kkt_residual.lv().squaredNorm() + kkt_residual.la().squaredNorm() + kkt_residual.lu.squaredNorm() + dtau*dtau*kkt_residual.u_res.squaredNorm() + dtau*dtau*s.u.head(6).squaredNorm(); EXPECT_DOUBLE_EQ(kkt_error, kkt_error_ref); auto pair = ocp.costAndConstraintViolation(robot, t, dtau, s); EXPECT_DOUBLE_EQ(pair.first, 0); } TEST_F(FloatingBaseSplitOCPTest, KKTErrorNormStateEquationAndRobotDynamics) { auto empty_cost = std::make_shared<CostFunction>(); auto empty_constraints = std::make_shared<Constraints>(); kkt_residual.setContactStatus(contact_status); kkt_matrix.setContactStatus(contact_status); s.setContactStatus(contact_status); SplitOCP ocp(robot, empty_cost, empty_constraints); ocp.computeKKTResidual(robot, contact_status, t, dtau, q_prev, s, s_next); const double kkt_error = ocp.squaredNormKKTResidual(dtau); robot.subtractConfiguration(s.q, s_next.q, kkt_residual.Fq()); robot.dSubtractdConfigurationPlus(s.q, s_next.q, kkt_matrix.Fqq); robot.dSubtractdConfigurationMinus(q_prev, s.q, kkt_matrix.Fqq_prev); kkt_residual.Fq() += dtau * s.v; kkt_residual.Fv() = s.v + dtau * s.a - s_next.v; kkt_residual.lq() = kkt_matrix.Fqq.transpose() * s_next.lmd + kkt_matrix.Fqq_prev.transpose() * s.lmd; kkt_residual.lv() = dtau * s_next.lmd + s_next.gmm - s.gmm; kkt_residual.la() = dtau * s_next.gmm; Eigen::VectorXd u_res = Eigen::VectorXd::Zero(robot.dimv()); Eigen::MatrixXd du_dq = Eigen::MatrixXd::Zero(robot.dimv(), robot.dimv()); Eigen::MatrixXd du_dv = Eigen::MatrixXd::Zero(robot.dimv(), robot.dimv()); Eigen::MatrixXd du_da = Eigen::MatrixXd::Zero(robot.dimv(), robot.dimv()); Eigen::MatrixXd du_df = Eigen::MatrixXd::Zero(robot.dimv(), contact_status.dimf()); robot.setContactForces(contact_status, s.f); robot.RNEA(s.q, s.v, s.a, kkt_residual.u_res); kkt_residual.u_res -= s.u; robot.RNEADerivatives(s.q, s.v, s.a, du_dq, du_dv, du_da); robot.updateKinematics(s.q, s.v, s.a); robot.dRNEAPartialdFext(contact_status, du_df); kkt_residual.lq() += dtau * du_dq.transpose() * s.beta; kkt_residual.lv() += dtau * du_dv.transpose() * s.beta; kkt_residual.la() += dtau * du_da.transpose() * s.beta; kkt_residual.lf() += dtau * du_df.transpose() * s.beta; kkt_residual.lu -= dtau * s.beta; robot.computeBaumgarteResidual(contact_status, dtau, dtau, kkt_residual.C().tail(contact_status.dimf())); robot.computeBaumgarteDerivatives(contact_status, dtau, dtau, kkt_matrix.Cq().bottomRows(contact_status.dimf()), kkt_matrix.Cv().bottomRows(contact_status.dimf()), kkt_matrix.Ca().bottomRows(contact_status.dimf())); kkt_residual.lq() += kkt_matrix.Cq().transpose() * s.mu_stack(); kkt_residual.lv() += kkt_matrix.Cv().transpose() * s.mu_stack(); kkt_residual.la() += kkt_matrix.Ca().transpose() * s.mu_stack(); kkt_residual.lu.head(6) += dtau * s.mu_stack().head(6); kkt_residual.C().head(6) = dtau * s.u.head(6); double kkt_error_ref = kkt_residual.Fq().squaredNorm() + kkt_residual.Fv().squaredNorm() + kkt_residual.lq().squaredNorm() + kkt_residual.lv().squaredNorm() + kkt_residual.la().squaredNorm() + kkt_residual.lf().squaredNorm() + kkt_residual.lu.squaredNorm() + dtau*dtau*kkt_residual.u_res.squaredNorm() + kkt_residual.C().squaredNorm(); EXPECT_DOUBLE_EQ(kkt_error, kkt_error_ref); auto pair = ocp.costAndConstraintViolation(robot, t, dtau, s); EXPECT_DOUBLE_EQ(pair.first, 0); const double violation_ref = kkt_residual.Fx().lpNorm<1>() + dtau * kkt_residual.u_res.lpNorm<1>() + kkt_residual.C().lpNorm<1>(); EXPECT_DOUBLE_EQ(pair.second, violation_ref); } TEST_F(FloatingBaseSplitOCPTest, KKTErrorNormEmptyCost) { auto empty_cost = std::make_shared<CostFunction>(); SplitOCP ocp(robot, empty_cost, constraints); ocp.initConstraints(robot, 2, dtau, s); constraints->setSlackAndDual(robot, constraints_data, dtau, s); ocp.computeKKTResidual(robot, contact_status, t, dtau, q_prev, s, s_next); const double kkt_error = ocp.squaredNormKKTResidual(dtau); kkt_residual.setContactStatus(contact_status); kkt_matrix.setContactStatus(contact_status); s.setContactStatus(contact_status); constraints->augmentDualResidual(robot, constraints_data, dtau, s, kkt_residual); constraints->augmentDualResidual(robot, constraints_data, dtau, s.u, kkt_residual.lu); stateequation::LinearizeForwardEuler(robot, dtau, q_prev, s, s_next, kkt_matrix, kkt_residual); robot_dynamics.linearizeRobotDynamics(robot, contact_status, dtau, s, kkt_matrix, kkt_residual); double kkt_error_ref = 0; kkt_error_ref += kkt_residual.lq().squaredNorm(); kkt_error_ref += kkt_residual.lv().squaredNorm(); kkt_error_ref += kkt_residual.la().squaredNorm(); kkt_error_ref += kkt_residual.lf().squaredNorm(); kkt_error_ref += kkt_residual.lu.squaredNorm(); kkt_error_ref += stateequation::SquaredNormStateEuqationResidual(kkt_residual); kkt_error_ref += robot_dynamics.squaredNormRobotDynamicsResidual(dtau, kkt_residual); kkt_error_ref += constraints->squaredNormPrimalAndDualResidual(constraints_data); EXPECT_DOUBLE_EQ(kkt_error, kkt_error_ref); } TEST_F(FloatingBaseSplitOCPTest, KKTErrorNormEmptyConstraints) { auto empty_constraints = std::make_shared<Constraints>(); SplitOCP ocp(robot, cost, empty_constraints); ocp.initConstraints(robot, 2, dtau, s); ocp.computeKKTResidual(robot, contact_status, t, dtau, q_prev, s, s_next); const double kkt_error = ocp.squaredNormKKTResidual(dtau); kkt_residual.setContactStatus(contact_status); kkt_matrix.setContactStatus(contact_status); s.setContactStatus(contact_status); cost->computeStageCostDerivatives(robot, cost_data, t, dtau, s, kkt_residual); cost->lu(robot, cost_data, t, dtau, s.u, kkt_residual.lu); stateequation::LinearizeForwardEuler(robot, dtau, q_prev, s, s_next, kkt_matrix, kkt_residual); robot_dynamics.linearizeRobotDynamics(robot, contact_status, dtau, s, kkt_matrix, kkt_residual); double kkt_error_ref = 0; kkt_error_ref += kkt_residual.lq().squaredNorm(); kkt_error_ref += kkt_residual.lv().squaredNorm(); kkt_error_ref += kkt_residual.la().squaredNorm(); kkt_error_ref += kkt_residual.lf().squaredNorm(); kkt_error_ref += kkt_residual.lu.squaredNorm(); kkt_error_ref += stateequation::SquaredNormStateEuqationResidual(kkt_residual); kkt_error_ref += robot_dynamics.squaredNormRobotDynamicsResidual(dtau, kkt_residual); EXPECT_DOUBLE_EQ(kkt_error, kkt_error_ref); } TEST_F(FloatingBaseSplitOCPTest, KKTErrorNorm) { SplitOCP ocp(robot, cost, constraints); ocp.initConstraints(robot, 2, dtau, s); constraints->setSlackAndDual(robot, constraints_data, dtau, s); ocp.computeKKTResidual(robot, contact_status, t, dtau, q_prev, s, s_next); const double kkt_error = ocp.squaredNormKKTResidual(dtau); kkt_matrix.setContactStatus(contact_status); kkt_residual.setContactStatus(contact_status); kkt_residual.setZero(); if (contact_status.hasActiveContacts()) { robot.updateKinematics(s.q, s.v, s.a); } cost->computeStageCostDerivatives(robot, cost_data, t, dtau, s, kkt_residual); cost->lu(robot, cost_data, t, dtau, s.u, kkt_residual.lu); constraints->augmentDualResidual(robot, constraints_data, dtau, s, kkt_residual); constraints->augmentDualResidual(robot, constraints_data, dtau, s.u, kkt_residual.lu); stateequation::LinearizeForwardEuler(robot, dtau, q_prev, s, s_next, kkt_matrix, kkt_residual); robot_dynamics.linearizeRobotDynamics(robot, contact_status, dtau, s, kkt_matrix, kkt_residual); double kkt_error_ref = 0; kkt_error_ref += kkt_residual.lq().squaredNorm(); kkt_error_ref += kkt_residual.lv().squaredNorm(); kkt_error_ref += kkt_residual.la().squaredNorm(); kkt_error_ref += kkt_residual.lf().squaredNorm(); kkt_error_ref += kkt_residual.lu.squaredNorm(); kkt_error_ref += stateequation::SquaredNormStateEuqationResidual(kkt_residual); kkt_error_ref += robot_dynamics.squaredNormRobotDynamicsResidual(dtau, kkt_residual); kkt_error_ref += constraints->squaredNormPrimalAndDualResidual(constraints_data); EXPECT_DOUBLE_EQ(kkt_error, kkt_error_ref); } TEST_F(FloatingBaseSplitOCPTest, costAndConstraintViolation) { SplitOCP ocp(robot, cost, constraints); ocp.initConstraints(robot, 2, dtau, s); constraints->setSlackAndDual(robot, constraints_data, dtau, s); ocp.computeKKTResidual(robot, contact_status, t, dtau, q_prev, s, s_next); const auto pair = ocp.costAndConstraintViolation(robot, t, dtau, s); const double cost_ref = cost->l(robot, cost_data, t, dtau, s) + constraints->costSlackBarrier(constraints_data); EXPECT_DOUBLE_EQ(pair.first, cost_ref); robot.subtractConfiguration(s.q, s_next.q, kkt_residual.Fq()); kkt_residual.Fq() += dtau * s.v; kkt_residual.Fv() = s.v + dtau * s.a - s_next.v; robot.setContactForces(contact_status, s.f); robot.RNEA(s.q, s.v, s.a, kkt_residual.u_res); kkt_residual.u_res -= s.u; robot.updateKinematics(s.q, s.v, s.a); robot.computeBaumgarteResidual(contact_status, dtau, dtau, kkt_residual.C_contacts()); constraints->computePrimalAndDualResidual(robot, constraints_data, dtau, s); const double violation_ref = kkt_residual.Fq().lpNorm<1>() + kkt_residual.Fv().lpNorm<1>() + dtau * kkt_residual.u_res.lpNorm<1>() + kkt_residual.C_contacts().lpNorm<1>() + dtau * s.u.head(6).lpNorm<1>() + constraints->l1NormPrimalResidual(constraints_data); EXPECT_DOUBLE_EQ(pair.second, violation_ref); } TEST_F(FloatingBaseSplitOCPTest, costAndConstraintViolationWithStepSize) { SplitOCP ocp(robot, cost, constraints); ocp.initConstraints(robot, 2, dtau, s); constraints->setSlackAndDual(robot, constraints_data, dtau, s); const double step_size = 0.3; const auto pair = ocp.costAndConstraintViolation(robot, contact_status, step_size, t, dtau, s, d, s_next, d_next); robot.integrateConfiguration(s.q, d.dq(), step_size, s_tmp.q); s_tmp.v = s.v + step_size * d.dv(); s_tmp.a = s.a + step_size * d.da(); s_tmp.f_stack() = s.f_stack() + step_size * d.df(); s_tmp.set_f(); robot.setContactForces(contact_status, s_tmp.f); s_tmp.u = s.u + step_size * d.du; robot.updateKinematics(s_tmp.q, s_tmp.v, s_tmp.a); const double cost_ref = cost->l(robot, cost_data, t, dtau, s_tmp) + constraints->costSlackBarrier(constraints_data, step_size); EXPECT_NEAR(pair.first, cost_ref, dtau); robot.subtractConfiguration(s_tmp.q, s_next.q, kkt_residual.Fq()); kkt_residual.Fq() += dtau * s_tmp.v - step_size * d_next.dq(); kkt_residual.Fv() = s_tmp.v + dtau * s_tmp.a - s_next.v - step_size * d_next.dv(); robot.setContactForces(contact_status, s_tmp.f); robot.RNEA(s_tmp.q, s_tmp.v, s_tmp.a, kkt_residual.u_res); kkt_residual.u_res -= s_tmp.u; robot.updateKinematics(s_tmp.q, s_tmp.v, s_tmp.a); robot.computeBaumgarteResidual(contact_status, dtau, dtau, kkt_residual.C_contacts()); constraints->computePrimalAndDualResidual(robot, constraints_data, dtau, s_tmp); double violation_ref = 0; violation_ref += kkt_residual.Fx().lpNorm<1>(); violation_ref += dtau * kkt_residual.u_res.lpNorm<1>(); violation_ref += kkt_residual.C_contacts().lpNorm<1>(); violation_ref += dtau * s_tmp.u.head(6).lpNorm<1>(); violation_ref += constraints->l1NormPrimalResidual(constraints_data); EXPECT_DOUBLE_EQ(pair.second, violation_ref); } TEST_F(FloatingBaseSplitOCPTest, riccatiRecursion) { const int dimv = robot.dimv(); const int dimf = contact_status.dimf(); const int dimc = contact_status.dimf() + robot.dim_passive(); const int dim_passive = robot.dim_passive(); std::cout << "dimf = " << dimf << std::endl; std::cout << "dimc = " << dimc << std::endl; s.setContactStatus(contact_status); SplitOCP ocp(robot, cost, constraints); while (!ocp.isFeasible(robot, s)) { s.v = Eigen::VectorXd::Random(dimv); s.u = Eigen::VectorXd::Random(dimv); } ASSERT_TRUE(ocp.isFeasible(robot, s)); ocp.initConstraints(robot, 5, dtau, s); ocp.linearizeOCP(robot, contact_status, t, dtau, q_prev, s, s_next); const auto pair = ocp.costAndConstraintViolation(robot, t, dtau, s); RiccatiFactorization riccati_next(robot); const Eigen::MatrixXd seed_mat = Eigen::MatrixXd::Random(2*dimv, 2*dimv); const Eigen::MatrixXd P = seed_mat * seed_mat.transpose() + Eigen::MatrixXd::Identity(2*dimv, 2*dimv); riccati_next.Pqq = P.topLeftCorner(dimv, dimv); riccati_next.Pqv = P.topRightCorner(dimv, dimv); riccati_next.Pvq = riccati_next.Pqv.transpose(); riccati_next.Pvv = P.bottomRightCorner(dimv, dimv); RiccatiFactorization riccati(robot); ocp.backwardRiccatiRecursion(dtau, riccati_next, riccati); ocp.forwardRiccatiRecursion(dtau, d, d_next); robot.updateKinematics(s.q, s.v, s.a); cost->lq(robot, cost_data, t, dtau, s, kkt_residual); cost->lv(robot, cost_data, t, dtau, s, kkt_residual); cost->la(robot, cost_data, t, dtau, s, kkt_residual); cost->lf(robot, cost_data, t, dtau, s, kkt_residual); cost->lu(robot, cost_data, t, dtau, s.u, kkt_residual.lu); Eigen::VectorXd q_res = Eigen::VectorXd::Zero(dimv); Eigen::VectorXd v_res = Eigen::VectorXd::Zero(dimv); Eigen::VectorXd u_res = Eigen::VectorXd::Zero(dimv); Eigen::MatrixXd du_dq = Eigen::MatrixXd::Zero(dimv, dimv); Eigen::MatrixXd du_dv = Eigen::MatrixXd::Zero(dimv, dimv); Eigen::MatrixXd du_da = Eigen::MatrixXd::Zero(dimv, dimv); Eigen::MatrixXd du_df = Eigen::MatrixXd::Zero(dimv, dimf); robot.subtractConfiguration(s.q, s_next.q, kkt_residual.Fq()); kkt_residual.Fq() += dtau * s.v; kkt_residual.Fv() = s.v + dtau * s.a - s_next.v; robot.dSubtractdConfigurationPlus(s.q, s_next.q, kkt_matrix.Fqq); robot.dSubtractdConfigurationMinus(q_prev, s.q, kkt_matrix.Fqq_prev); robot.setContactForces(contact_status, s.f); robot.RNEA(s.q, s.v, s.a, kkt_residual.u_res); kkt_residual.u_res.noalias() -= s.u; robot.RNEADerivatives(s.q, s.v, s.a, du_dq, du_dv, du_da); robot.dRNEAPartialdFext(contact_status, du_df); robot.computeBaumgarteResidual(contact_status, dtau, dtau, kkt_residual.C_contacts()); robot.computeBaumgarteDerivatives(contact_status, dtau, dtau, kkt_matrix.Cq_contacts(), kkt_matrix.Cv_contacts(), kkt_matrix.Ca_contacts()); kkt_residual.C_floating_base() = dtau * (s.u.head(dim_passive)+kkt_residual.u_res.head(dim_passive)); kkt_matrix.Cq_floating_base() = dtau * du_dq.topRows(dim_passive); kkt_matrix.Cv_floating_base() = dtau * du_dv.topRows(dim_passive); kkt_matrix.Ca_floating_base() = dtau * du_da.topRows(dim_passive); kkt_matrix.Cf_floating_base() = dtau * du_df.topRows(dim_passive); Eigen::MatrixXd Cu = Eigen::MatrixXd::Zero(dimc, dimv); Cu.topLeftCorner(dim_passive, dim_passive) = dtau * Eigen::MatrixXd::Identity(dim_passive, dim_passive); constraints->setSlackAndDual(robot, constraints_data, dtau, s); constraints->augmentDualResidual(robot, constraints_data, dtau, s.u, kkt_residual.lu); cost->luu(robot, cost_data, t, dtau, s.u, kkt_matrix.Quu); constraints->condenseSlackAndDual(robot, constraints_data, dtau, s.u, kkt_matrix.Quu, kkt_residual.lu); const Eigen::VectorXd lu_condensed = kkt_residual.lu + kkt_matrix.Quu * kkt_residual.u_res; kkt_residual.lq() += du_dq.transpose() * lu_condensed; kkt_residual.lv() += du_dv.transpose() * lu_condensed; kkt_residual.la() += du_da.transpose() * lu_condensed; kkt_residual.lf() += du_df.transpose() * lu_condensed; kkt_residual.lq() += kkt_matrix.Fqq.transpose() * s_next.lmd + kkt_matrix.Fqq_prev.transpose() * s.lmd; kkt_residual.lv() += dtau * s_next.lmd + s_next.gmm - s.gmm; kkt_residual.la() += dtau * s_next.gmm; constraints->augmentDualResidual(robot, constraints_data, dtau, s, kkt_residual); kkt_residual.lq() += kkt_matrix.Cq().transpose() * s.mu_stack(); kkt_residual.lv() += kkt_matrix.Cv().transpose() * s.mu_stack(); kkt_residual.la() += kkt_matrix.Ca().transpose() * s.mu_stack(); kkt_residual.lf() += kkt_matrix.Cf().transpose() * s.mu_stack(); kkt_residual.lu -= dtau * s.beta; kkt_residual.lu += Cu.transpose() * s.mu_stack(); kkt_matrix.Qqq() = du_dq.transpose() * kkt_matrix.Quu * du_dq; kkt_matrix.Qqv() = du_dq.transpose() * kkt_matrix.Quu * du_dv; kkt_matrix.Qqa() = du_dq.transpose() * kkt_matrix.Quu * du_da; kkt_matrix.Qvv() = du_dv.transpose() * kkt_matrix.Quu * du_dv; kkt_matrix.Qva() = du_dv.transpose() * kkt_matrix.Quu * du_da; kkt_matrix.Qaa() = du_da.transpose() * kkt_matrix.Quu * du_da; kkt_matrix.Qqf() = du_dq.transpose() * kkt_matrix.Quu * du_df; kkt_matrix.Qvf() = du_dv.transpose() * kkt_matrix.Quu * du_df; kkt_matrix.Qaf() = du_da.transpose() * kkt_matrix.Quu * du_df; kkt_matrix.Qff() = du_df.transpose() * kkt_matrix.Quu * du_df; constraints->condenseSlackAndDual(robot, constraints_data, dtau, s, kkt_matrix, kkt_residual); cost->computeStageCostHessian(robot, cost_data, t, dtau, s, kkt_matrix); factorizer.setStateEquationDerivative(kkt_matrix.Fqq); // factorizer.setStateEquationDerivativeInverse(kkt_matrix.Fqq_prev); inverter.setContactStatus(contact_status); gain.setContactStatus(contact_status); kkt_matrix.Qvq() = kkt_matrix.Qqv().transpose(); kkt_matrix.Qaq() = kkt_matrix.Qqa().transpose(); kkt_matrix.Qav() = kkt_matrix.Qva().transpose(); if (contact_status.dimf() > 0) { kkt_matrix.Qfq() = kkt_matrix.Qqf().transpose(); kkt_matrix.Qfv() = kkt_matrix.Qvf().transpose(); kkt_matrix.Qfa() = kkt_matrix.Qaf().transpose(); } // std::cout << "in test" << std::endl; // std::cout << std::setprecision(20) << "Qqq\n" << kkt_matrix.Qqq() << std::endl; // std::cout << std::setprecision(20) << "Qqv\n" << kkt_matrix.Qqv() << std::endl; // std::cout << std::setprecision(20) << "Qqa\n" << kkt_matrix.Qqa() << std::endl; // std::cout << std::setprecision(20) << "Qqf\n" << kkt_matrix.Qqf() << std::endl; // std::cout << std::setprecision(20) << "Qvq\n" << kkt_matrix.Qvq() << std::endl; // std::cout << std::setprecision(20) << "Qvv\n" << kkt_matrix.Qvv() << std::endl; // std::cout << std::setprecision(20) << "Qva\n" << kkt_matrix.Qva() << std::endl; // std::cout << std::setprecision(20) << "Qvf\n" << kkt_matrix.Qvf() << std::endl; // std::cout << std::setprecision(20) << "Qaq\n" << kkt_matrix.Qaq() << std::endl; // std::cout << std::setprecision(20) << "Qav\n" << kkt_matrix.Qav() << std::endl; // std::cout << std::setprecision(20) << "Qaa\n" << kkt_matrix.Qaa() << std::endl; // std::cout << std::setprecision(20) << "Qaf\n" << kkt_matrix.Qaf() << std::endl; // std::cout << std::setprecision(20) << "Qfq\n" << kkt_matrix.Qfq() << std::endl; // std::cout << std::setprecision(20) << "Qfv\n" << kkt_matrix.Qfv() << std::endl; // std::cout << std::setprecision(20) << "Qfa\n" << kkt_matrix.Qfa() << std::endl; // std::cout << std::setprecision(20) << "Qff\n" << kkt_matrix.Qff() << std::endl; // std::cout << std::setprecision(20) << "Cq\n" << kkt_matrix.Cq() << std::endl; // std::cout << std::setprecision(20) << "Cv\n" << kkt_matrix.Cv() << std::endl; // std::cout << std::setprecision(20) << "Ca\n" << kkt_matrix.Ca() << std::endl; // std::cout << std::setprecision(20) << "Cf\n" << kkt_matrix.Cf() << std::endl; // std::cout << std::setprecision(20) << "lq\n" << kkt_residual.lq() << std::endl; // std::cout << std::setprecision(20) << "lv\n" << kkt_residual.lv() << std::endl; // std::cout << std::setprecision(20) << "la\n" << kkt_residual.la() << std::endl; // std::cout << std::setprecision(20) << "lf\n" << kkt_residual.lf() << std::endl; // std::cout << std::setprecision(20) << "C\n" << kkt_residual.C() << std::endl; factorizer.factorize_F(dtau, riccati_next.Pqq, riccati_next.Pqv, riccati_next.Pvq, riccati_next.Pvv, kkt_matrix.Qqq(), kkt_matrix.Qqv(), kkt_matrix.Qvq(), kkt_matrix.Qvv()); factorizer.factorize_H(dtau, riccati_next.Pqv, riccati_next.Pvv, kkt_matrix.Qqa(), kkt_matrix.Qva()); factorizer.factorize_G(dtau, riccati_next.Pvv, kkt_matrix.Qaa()); factorizer.factorize_la(dtau, riccati_next.Pvq, riccati_next.Pvv, kkt_residual.Fq(), kkt_residual.Fv(), riccati_next.sv, kkt_residual.la()); kkt_matrix.Qaq() = kkt_matrix.Qqa().transpose(); kkt_matrix.Qav() = kkt_matrix.Qva().transpose(); Eigen::MatrixXd G = Eigen::MatrixXd::Zero(dimv+dimf+dimc, dimv+dimf+dimc); G.topLeftCorner(dimv+dimf, dimv+dimf) = kkt_matrix.Qafaf(); G.topRightCorner(dimv+dimf, dimc) = kkt_matrix.Caf().transpose(); G.bottomLeftCorner(dimc, dimv+dimf) = kkt_matrix.Caf(); const Eigen::MatrixXd Ginv = G.inverse(); // Eigen::MatrixXd Ginv = Eigen::MatrixXd::Zero(dimv+dimf+dimc, dimv+dimf+dimc); // inverter.invert(kkt_matrix.Qafaf(), kkt_matrix.Caf(), Ginv); Eigen::MatrixXd Qqvaf = Eigen::MatrixXd::Zero(2*dimv, dimv+dimf); Qqvaf.topLeftCorner(dimv, dimv) = kkt_matrix.Qqa(); Qqvaf.topRightCorner(dimv, dimf) = kkt_matrix.Qqf(); Qqvaf.bottomLeftCorner(dimv, dimv) = kkt_matrix.Qva(); Qqvaf.bottomRightCorner(dimv, dimf) = kkt_matrix.Qvf(); EXPECT_TRUE(Qqvaf.transpose().isApprox(kkt_matrix.Qafqv())); gain.computeFeedbackGain(Ginv, Qqvaf.transpose(), kkt_matrix.Cqv()); gain.computeFeedforward(Ginv, kkt_residual.laf(), kkt_residual.C()); Eigen::MatrixXd Pqq_ref = Eigen::MatrixXd::Zero(dimv, dimv); Eigen::MatrixXd Pqv_ref = Eigen::MatrixXd::Zero(dimv, dimv); Eigen::MatrixXd Pvq_ref = Eigen::MatrixXd::Zero(dimv, dimv); Eigen::MatrixXd Pvv_ref = Eigen::MatrixXd::Zero(dimv, dimv); Eigen::VectorXd sq_ref = Eigen::VectorXd::Zero(dimv); Eigen::VectorXd sv_ref = Eigen::VectorXd::Zero(dimv); Pqq_ref = kkt_matrix.Qqq(); Pqq_ref += gain.Kaq().transpose() * kkt_matrix.Qqa().transpose(); Pqv_ref = kkt_matrix.Qqv(); Pqv_ref += gain.Kaq().transpose() * kkt_matrix.Qva().transpose(); Pvq_ref = kkt_matrix.Qvq(); Pvq_ref += gain.Kav().transpose() * kkt_matrix.Qqa().transpose(); Pvv_ref = kkt_matrix.Qvv(); Pvv_ref += gain.Kav().transpose() * kkt_matrix.Qva().transpose(); Pqq_ref += gain.Kfq().transpose() * kkt_matrix.Qqf().transpose(); Pqv_ref += gain.Kfq().transpose() * kkt_matrix.Qvf().transpose(); Pvq_ref += gain.Kfv().transpose() * kkt_matrix.Qqf().transpose(); Pvv_ref += gain.Kfv().transpose() * kkt_matrix.Qvf().transpose(); Pqq_ref += gain.Kmuq().transpose() * kkt_matrix.Cq(); Pqv_ref += gain.Kmuq().transpose() * kkt_matrix.Cv(); Pvq_ref += gain.Kmuv().transpose() * kkt_matrix.Cq(); Pvv_ref += gain.Kmuv().transpose() * kkt_matrix.Cv(); sq_ref = riccati_next.sq - kkt_residual.lq(); sq_ref -= riccati_next.Pqq * kkt_residual.Fq(); sq_ref -= riccati_next.Pqv * kkt_residual.Fv(); sq_ref -= kkt_matrix.Qqa() * gain.ka(); sv_ref = dtau * riccati_next.sq + riccati_next.sv - kkt_residual.lv(); sv_ref -= dtau * riccati_next.Pqq * kkt_residual.Fq(); sv_ref -= riccati_next.Pvq * kkt_residual.Fq(); sv_ref -= dtau * riccati_next.Pqv * kkt_residual.Fv(); sv_ref -= riccati_next.Pvv * kkt_residual.Fv(); sv_ref -= kkt_matrix.Qva() * gain.ka(); sq_ref -= kkt_matrix.Qqf() * gain.kf(); sv_ref -= kkt_matrix.Qvf() * gain.kf(); sq_ref -= kkt_matrix.Cq().transpose() * gain.kmu(); sv_ref -= kkt_matrix.Cv().transpose() * gain.kmu(); // factorizer.correctP(Pqq_ref, Pqv_ref); // factorizer.correct_s(sq_ref); EXPECT_TRUE(riccati.Pqq.isApprox(Pqq_ref, 1.0e-10)); EXPECT_TRUE(riccati.Pqv.isApprox(Pqv_ref, 1.0e-10)); EXPECT_TRUE(riccati.Pvq.isApprox(Pvq_ref, 1.0e-10));; EXPECT_TRUE(riccati.Pvv.isApprox(Pvv_ref, 1.0e-10)); EXPECT_TRUE(riccati.sq.isApprox(sq_ref, 1.0e-10)); EXPECT_TRUE(riccati.sv.isApprox(sv_ref, 1.0e-10)); std::cout << riccati.Pqq - Pqq_ref << std::endl; std::cout << riccati.Pqv - Pqv_ref << std::endl; std::cout << riccati.Pvq - Pvq_ref << std::endl; std::cout << riccati.Pvv - Pvv_ref << std::endl; std::cout << riccati.sq - sq_ref << std::endl; std::cout << riccati.sv - sv_ref << std::endl; EXPECT_TRUE(riccati.Pqq.transpose().isApprox(riccati.Pqq)); EXPECT_TRUE(riccati.Pqv.transpose().isApprox(riccati.Pvq)); EXPECT_TRUE(riccati.Pvv.transpose().isApprox(riccati.Pvv)); const Eigen::VectorXd da_ref = gain.ka() + gain.Kaq() * d.dq() + gain.Kav() * d.dv(); const Eigen::VectorXd dq_next_ref = d.dq() + dtau * d.dv() + kkt_residual.Fq(); const Eigen::VectorXd dv_next_ref = d.dv() + dtau * d.da() + kkt_residual.Fv(); EXPECT_TRUE(d_next.dq().isApprox(dq_next_ref)); EXPECT_TRUE(d_next.dv().isApprox(dv_next_ref)); ocp.computeCondensedDirection(robot, dtau, s, d); EXPECT_TRUE(d.df().isApprox(gain.kf()+gain.Kfq()*d.dq()+gain.Kfv()*d.dv(), 1.0e-10)); EXPECT_TRUE(d.dmu().isApprox(gain.kmu()+gain.Kmuq()*d.dq()+gain.Kmuv()*d.dv(), 1.0e-10)); Eigen::MatrixXd Kuq = Eigen::MatrixXd::Zero(robot.dimv(), robot.dimv()); Eigen::MatrixXd Kuv = Eigen::MatrixXd::Zero(robot.dimv(), robot.dimv()); ocp.getStateFeedbackGain(Kuq, Kuv); Eigen::MatrixXd Kuq_ref = du_dq + du_da * gain.Kaq(); if (dimf > 0) { Kuq_ref += du_df * gain.Kfq(); } Eigen::MatrixXd Kuv_ref = du_dv + du_da * gain.Kav(); if (dimf > 0) { Kuv_ref += du_df * gain.Kfv(); } EXPECT_TRUE(Kuq.isApprox(Kuq_ref, 1.0e-10)); EXPECT_TRUE(Kuv.isApprox(Kuv_ref, 1.0e-10)); ocp.computeKKTResidual(robot, contact_status, t, dtau, q_prev, s, s_next); const auto pair_ref = ocp.costAndConstraintViolation(robot, t, dtau, s); EXPECT_DOUBLE_EQ(pair.first, pair_ref.first); EXPECT_DOUBLE_EQ(pair.second, pair_ref.second); } } // namespace idocp int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
52.656296
115
0.694764
[ "vector" ]
a38c6730b4aff5cdcf7c0896db73e67b54fc4e6f
2,136
cc
C++
RecoTracker/TkSeedGenerator/plugins/CombinedMultiHitGenerator.cc
malbouis/cmssw
16173a30d3f0c9ecc5419c474bb4d272c58b65c8
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoTracker/TkSeedGenerator/plugins/CombinedMultiHitGenerator.cc
malbouis/cmssw
16173a30d3f0c9ecc5419c474bb4d272c58b65c8
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoTracker/TkSeedGenerator/plugins/CombinedMultiHitGenerator.cc
malbouis/cmssw
16173a30d3f0c9ecc5419c474bb4d272c58b65c8
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "CombinedMultiHitGenerator.h" #include "RecoTracker/TkHitPairs/interface/HitPairGeneratorFromLayerPair.h" #include "RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayers.h" #include "RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayersFactory.h" #include "RecoPixelVertexing/PixelTriplets/interface/LayerTriplets.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Framework/interface/Event.h" #include "DataFormats/Common/interface/Handle.h" CombinedMultiHitGenerator::CombinedMultiHitGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC) : theSeedingLayerToken(iC.consumes<SeedingLayerSetsHits>(cfg.getParameter<edm::InputTag>("SeedingLayers"))) { edm::ParameterSet generatorPSet = cfg.getParameter<edm::ParameterSet>("GeneratorPSet"); std::string generatorName = generatorPSet.getParameter<std::string>("ComponentName"); theGenerator = MultiHitGeneratorFromPairAndLayersFactory::get()->create(generatorName, generatorPSet, iC); theGenerator->init(std::make_unique<HitPairGeneratorFromLayerPair>(iC, 0, 1, &theLayerCache), &theLayerCache); } CombinedMultiHitGenerator::~CombinedMultiHitGenerator() {} void CombinedMultiHitGenerator::hitSets(const TrackingRegion& region, OrderedMultiHits& result, const edm::Event& ev, const edm::EventSetup& es) { edm::Handle<SeedingLayerSetsHits> hlayers; ev.getByToken(theSeedingLayerToken, hlayers); const SeedingLayerSetsHits& layers = *hlayers; if (layers.numberOfLayersInSet() != 3) throw cms::Exception("Configuration") << "CombinedMultiHitGenerator expects SeedingLayerSetsHits::numberOfLayersInSet() to be 3, got " << layers.numberOfLayersInSet(); theGenerator->initES(es); std::vector<LayerTriplets::LayerSetAndLayers> trilayers = LayerTriplets::layers(layers); for (const auto& setAndLayers : trilayers) { theGenerator->hitSets(region, result, ev, es, setAndLayers.first, setAndLayers.second); } theLayerCache.clear(); }
52.097561
113
0.752809
[ "vector" ]
a38c9d08c2fabf3b76c33a00896f33fd5a11b2a5
36,005
cpp
C++
source/parser.cpp
sur5r/binspector
9eeb9af463254edf1056d59944c49d00770e36f0
[ "BSL-1.0" ]
119
2015-01-14T18:03:20.000Z
2022-03-18T14:02:46.000Z
source/parser.cpp
sur5r/binspector
9eeb9af463254edf1056d59944c49d00770e36f0
[ "BSL-1.0" ]
8
2015-03-06T01:18:39.000Z
2021-05-04T21:55:34.000Z
source/parser.cpp
sur5r/binspector
9eeb9af463254edf1056d59944c49d00770e36f0
[ "BSL-1.0" ]
22
2015-01-09T16:18:38.000Z
2022-03-13T13:41:04.000Z
/* Copyright 2014 Adobe 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) */ /****************************************************************************************************/ // identity #include <binspector/parser.hpp> // boost #include <boost/filesystem/fstream.hpp> // asl #include <adobe/algorithm/find.hpp> #include <adobe/algorithm/sorted.hpp> #include <adobe/implementation/token.hpp> #include <adobe/array.hpp> #include <adobe/string.hpp> /****************************************************************************************************/ namespace { /****************************************************************************************************/ #if 0 #pragma mark - #endif /*************************************************************************************************/ CONSTANT_KEY(big); CONSTANT_KEY(const); CONSTANT_KEY(default); CONSTANT_KEY(delimiter); CONSTANT_KEY(die); CONSTANT_KEY(else); CONSTANT_KEY(enumerate); CONSTANT_KEY(float); CONSTANT_KEY(if); CONSTANT_KEY(include); CONSTANT_KEY(invariant); CONSTANT_KEY(invis); CONSTANT_KEY(little); CONSTANT_KEY(noprint); CONSTANT_KEY(notify); CONSTANT_KEY(sentry); CONSTANT_KEY(shuffle); CONSTANT_KEY(signal); CONSTANT_KEY(signed); CONSTANT_KEY(skip); CONSTANT_KEY(slot); CONSTANT_KEY(struct); CONSTANT_KEY(summary); CONSTANT_KEY(terminator); CONSTANT_KEY(typedef); CONSTANT_KEY(unsigned); CONSTANT_KEY(while); adobe::name_t keyword_table[] = { key_big, key_const, key_default, key_delimiter, key_die, key_else, key_enumerate, key_float, key_if, key_include, key_invariant, key_invis, key_little, key_noprint, key_notify, key_sentry, key_shuffle, key_signal, key_signed, key_skip, key_slot, key_struct, key_summary, key_terminator, key_typedef, key_unsigned, key_while, }; /*************************************************************************************************/ bool keyword_lookup(const adobe::name_t& name) { #ifndef NDEBUG static bool inited_s = false; if (!inited_s) { assert(adobe::is_sorted(keyword_table)); inited_s = true; } #endif return binary_search(keyword_table, name, adobe::less(), adobe::constructor<adobe::name_t>()) != boost::end(keyword_table); } /****************************************************************************************************/ template <typename T> struct temp_assign_and_call { template <typename U> temp_assign_and_call(T& variable, const T& value, U callback) : variable_m(variable), old_value_m(variable), proc_m(callback) { variable_m = value; call(); } ~temp_assign_and_call() { variable_m = old_value_m; call(); } private: void call() { if (proc_m) proc_m(variable_m); } T& variable_m; T old_value_m; std::function<void(const T&)> proc_m; }; /****************************************************************************************************/ } // namespace /****************************************************************************************************/ std::string get_input_line(std::istream& stream, std::streampos position) { static std::vector<char> line_buffer(1024, 0); stream.clear(); stream.seekg(position); stream.getline(&line_buffer[0], line_buffer.size()); return std::string(&line_buffer[0], &line_buffer[static_cast<std::size_t>(stream.gcount())]); } /****************************************************************************************************/ binspector_parser_t::binspector_parser_t(std::istream& in, const adobe::line_position_t& position, const include_directory_set_t& include_directory_set, const set_structure_proc_t& set_structure_proc, const add_field_proc_t& add_field_proc, const add_unnamed_field_proc_t& add_unnamed_field_proc, const add_typedef_proc_t& add_typedef_proc, const included_file_set_t& included_file_set) : adobe::expression_parser(in, position), include_directory_set_m(include_directory_set), included_file_set_m(included_file_set), set_structure_proc_m(set_structure_proc), add_field_proc_m(add_field_proc), add_unnamed_field_proc_m(add_unnamed_field_proc), add_typedef_proc_m(add_typedef_proc) { if (!set_structure_proc_m) throw std::runtime_error("A set structure callback is required"); if (!add_field_proc_m) throw std::runtime_error("An add field callback is required"); if (!add_unnamed_field_proc_m) throw std::runtime_error("An add unnamed field callback is required"); if (!add_typedef_proc_m) throw std::runtime_error("An add typedef callback is required"); set_keyword_extension_lookup(std::bind(&keyword_lookup, std::placeholders::_1)); set_comment_bypass(true); } /****************************************************************************************************/ void binspector_parser_t::parse() { try { if (!is_struct_set()) throw_exception("Format description must not be empty"); require_token(adobe::eof_k); } catch (const adobe::stream_error_t& error) { // Necessary to keep stream_error_t from being caught by the next catch throw error; } catch (const std::exception& error) { putback(); throw adobe::stream_error_t(error, next_position()); } } /****************************************************************************************************/ bool binspector_parser_t::is_struct_set() { bool result = false; while (is_struct() || is_pp_statement()) result = true; return result; } /****************************************************************************************************/ bool binspector_parser_t::is_struct() { if (!is_keyword(key_struct)) return false; adobe::name_t structure_name; require_identifier(structure_name); require_token(adobe::open_brace_k); temp_assign_and_call<adobe::name_t> tmp(current_struct_m, structure_name, set_structure_proc_m); is_statement_set(); require_token(adobe::close_brace_k); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_statement_set() { bool result = false; while (is_scope_or_statement()) result = true; return result; } /****************************************************************************************************/ bool binspector_parser_t::is_scope_or_statement() { return is_conditional_scope() || is_enum_scope() || is_sentry_scope() || is_statement(); } /****************************************************************************************************/ bool binspector_parser_t::is_conditional_scope() { if (!is_if_scope()) return false; is_else_scope(); return true; } /****************************************************************************************************/ void binspector_parser_t::insert_parser_metadata(adobe::dictionary_t& parameters) { const adobe::line_position_t& line_position(next_position()); parameters[key_parse_info_filename].assign(line_position.stream_name()); parameters[key_parse_info_line_number].assign(line_position.line_number_m); } /****************************************************************************************************/ bool binspector_parser_t::is_if_scope() { if (!is_keyword(key_if)) return false; adobe::array_t expression; require_token(adobe::open_parenthesis_k); require_expression(expression); require_token(adobe::close_parenthesis_k); static std::size_t uid_s(0); static const adobe::array_t empty_array_k; std::string lambda_identifier; // REVISIT (fbrereto) : String concatenation here. lambda_identifier += std::string("<") + current_struct_m.c_str() + ":if_" + boost::lexical_cast<std::string>(++uid_s) + ">"; adobe::name_t identifier(lambda_identifier.c_str()); adobe::dictionary_t parameters; parameters[key_field_if_expression].assign(expression); parameters[key_field_conditional_type].assign(conditional_expression_t(if_k)); parameters[key_field_name].assign(identifier); parameters[key_field_size_expression].assign(empty_array_k); parameters[key_field_offset_expression].assign(empty_array_k); parameters[key_field_type].assign(value_field_type_struct); parameters[key_named_type_name].assign(identifier); insert_parser_metadata(parameters); add_field_proc_m(identifier, parameters); require_scope_content(identifier); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_else_scope() { if (!is_keyword(key_else)) return false; static std::size_t uid_s(0); static const adobe::array_t empty_array_k; std::string lambda_identifier; // REVISIT (fbrereto) : String concatenation here. lambda_identifier += std::string("<") + current_struct_m.c_str() + ":else_" + boost::lexical_cast<std::string>(++uid_s) + ">"; adobe::name_t identifier(lambda_identifier.c_str()); adobe::dictionary_t parameters; parameters[key_field_if_expression].assign(empty_array_k); parameters[key_field_conditional_type].assign(conditional_expression_t(else_k)); parameters[key_field_name].assign(identifier); parameters[key_field_size_expression].assign(empty_array_k); parameters[key_field_offset_expression].assign(empty_array_k); parameters[key_field_type].assign(value_field_type_struct); parameters[key_named_type_name].assign(identifier); insert_parser_metadata(parameters); add_field_proc_m(identifier, parameters); require_scope_content(identifier); return true; } /****************************************************************************************************/ void binspector_parser_t::require_scope_content(adobe::name_t scope_name) { temp_assign_and_call<adobe::name_t> tmp(current_struct_m, scope_name, set_structure_proc_m); if (is_token(adobe::open_brace_k)) { is_statement_set(); require_token(adobe::close_brace_k); } else if (!is_scope_or_statement()) { throw_exception("Expected scope or statement"); } } /****************************************************************************************************/ bool binspector_parser_t::is_enum_scope() { if (!is_keyword(key_enumerate)) return false; require_token(adobe::open_parenthesis_k); adobe::array_t expression; require_expression(expression); require_token(adobe::close_parenthesis_k); static std::size_t uid_s(0); static const adobe::array_t empty_array_k; std::string lambda_identifier; // REVISIT (fbrereto) : String concatenation here. lambda_identifier += std::string("<") + current_struct_m.c_str() + ":enumerate_" + boost::lexical_cast<std::string>(++uid_s) + ">"; adobe::name_t identifier(lambda_identifier.c_str()); adobe::dictionary_t parameters; parameters[key_enumerated_expression].assign(expression); parameters[key_field_name].assign(identifier); parameters[key_field_size_expression].assign(empty_array_k); parameters[key_field_offset_expression].assign(empty_array_k); parameters[key_field_type].assign(value_field_type_enumerated); parameters[key_named_type_name].assign(identifier); insert_parser_metadata(parameters); add_field_proc_m(identifier, parameters); require_enum_content(identifier); return true; } /****************************************************************************************************/ void binspector_parser_t::require_enum_content(adobe::name_t scope_name) { temp_assign_and_call<adobe::name_t> tmp(current_struct_m, scope_name, set_structure_proc_m); if (!is_enum_entry_map() && !is_enum_entry_list()) throw_exception("Expected an enumerate list or map, but found neither"); } /****************************************************************************************************/ bool binspector_parser_t::is_enum_entry_list() { if (!is_token(adobe::open_bracket_k)) return false; if (!is_enum_list_item_set()) throw_exception("Enumerate list must have at least one option"); require_token(adobe::close_bracket_k); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_enum_list_item_set() { if (!is_enum_list_item()) return false; while (is_token(adobe::comma_k)) { if (!is_enum_list_item()) throw_exception("Expected an enumerate list item after the comma"); } return true; } /****************************************************************************************************/ bool binspector_parser_t::is_enum_list_item() { adobe::array_t expression; if (!is_expression(expression)) return false; static std::size_t uid_s(0); static const adobe::array_t empty_array_k; std::string lambda_identifier; // REVISIT (fbrereto) : String concatenation here. lambda_identifier += std::string("<") + current_struct_m.c_str() + ":enumerate_list_option_" + boost::lexical_cast<std::string>(++uid_s) + ">"; adobe::name_t identifier(lambda_identifier.c_str()); adobe::dictionary_t parameters; parameters[key_enumerated_option_expression].assign(expression); parameters[key_field_name].assign(identifier); parameters[key_field_size_expression].assign(empty_array_k); parameters[key_field_offset_expression].assign(empty_array_k); parameters[key_field_type].assign(value_field_type_enumerated_option); parameters[key_named_type_name].assign(identifier); insert_parser_metadata(parameters); add_field_proc_m(identifier, parameters); // This call adds an empty structure to the structure map. Remember the list // is intended to be syntactic sugar, so this kind of "hack" is OK. temp_assign_and_call<adobe::name_t> tmp(current_struct_m, identifier, set_structure_proc_m); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_enum_entry_map() { if (!is_token(adobe::open_brace_k)) return false; if (!is_enum_map_item_set()) throw_exception("Enumerate map must have at least one option"); // must be last in the enumerate construct! is_enum_map_default(); require_token(adobe::close_brace_k); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_enum_map_item_set() { bool result = false; while (is_enum_map_item()) result = true; return result; } /****************************************************************************************************/ bool binspector_parser_t::is_enum_map_item() { adobe::array_t expression; if (!is_expression(expression)) return false; require_token(adobe::colon_k); static std::size_t uid_s(0); static const adobe::array_t empty_array_k; std::string lambda_identifier; // REVISIT (fbrereto) : String concatenation here. lambda_identifier += std::string("<") + current_struct_m.c_str() + ":enumerate_map_option_" + boost::lexical_cast<std::string>(++uid_s) + ">"; adobe::name_t identifier(lambda_identifier.c_str()); adobe::dictionary_t parameters; parameters[key_enumerated_option_expression].assign(expression); parameters[key_field_name].assign(identifier); parameters[key_field_size_expression].assign(empty_array_k); parameters[key_field_offset_expression].assign(empty_array_k); parameters[key_field_type].assign(value_field_type_enumerated_option); parameters[key_named_type_name].assign(identifier); insert_parser_metadata(parameters); add_field_proc_m(identifier, parameters); require_scope_content(identifier); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_enum_map_default() { if (!is_keyword(key_default)) return false; require_token(adobe::colon_k); static std::size_t uid_s(0); static const adobe::array_t empty_array_k; std::string lambda_identifier; // REVISIT (fbrereto) : String concatenation here. lambda_identifier += std::string("<") + current_struct_m.c_str() + ":enumerate_default_" + boost::lexical_cast<std::string>(++uid_s) + ">"; adobe::name_t identifier(lambda_identifier.c_str()); adobe::dictionary_t parameters; parameters[key_field_name].assign(identifier); parameters[key_field_size_expression].assign(empty_array_k); parameters[key_field_offset_expression].assign(empty_array_k); parameters[key_field_type].assign(value_field_type_enumerated_default); parameters[key_named_type_name].assign(identifier); insert_parser_metadata(parameters); add_field_proc_m(identifier, parameters); require_scope_content(identifier); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_sentry_scope() { if (!is_keyword(key_sentry)) return false; require_token(adobe::open_parenthesis_k); adobe::array_t expression; require_expression(expression); require_token(adobe::close_parenthesis_k); static std::size_t uid_s(0); static const adobe::array_t empty_array_k; std::string lambda_identifier; // REVISIT (fbrereto) : String concatenation here. lambda_identifier += std::string("<") + current_struct_m.c_str() + ":sentry_" + boost::lexical_cast<std::string>(++uid_s) + ">"; adobe::name_t identifier(lambda_identifier.c_str()); adobe::dictionary_t parameters; parameters[key_sentry_expression].assign(expression); parameters[key_field_name].assign(identifier); parameters[key_field_size_expression].assign(empty_array_k); parameters[key_field_offset_expression].assign(empty_array_k); parameters[key_field_type].assign(value_field_type_sentry); parameters[key_named_type_name].assign(identifier); insert_parser_metadata(parameters); add_field_proc_m(identifier, parameters); require_scope_content(identifier); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_statement() { bool success(is_typedef() || is_unnamed_statement() || is_named_statement()); if (success) require_token(adobe::semicolon_k); return success; } /****************************************************************************************************/ bool binspector_parser_t::is_unnamed_statement() { return is_notify() || is_summary() || is_die(); } /****************************************************************************************************/ bool binspector_parser_t::is_named_statement() { return is_invariant() || is_constant() || is_skip() || is_slot() || is_signal() || is_field(); // field should be last because atoms only // require an expression which most everything // falls into; the more explicit stuff should // come first. } /****************************************************************************************************/ bool binspector_parser_t::is_field_type(adobe::name_t& named_field_identifier, atom_base_type_t& atom_base_type, adobe::array_t& bit_count_expression, adobe::array_t& is_big_endian_expression) { if (is_named_field(named_field_identifier)) return true; if (is_atom_field(atom_base_type, bit_count_expression, is_big_endian_expression)) return true; return false; } /****************************************************************************************************/ bool binspector_parser_t::is_named_field(adobe::name_t& named_field_identifier) { return is_identifier(named_field_identifier); } /****************************************************************************************************/ bool binspector_parser_t::is_atom_field(atom_base_type_t& atom_base_type, adobe::array_t& bit_count_expression, adobe::array_t& is_big_endian_expression) { static const adobe::array_t is_little_endian_expression_k(1, adobe::any_regular_t(false)); static const adobe::array_t is_big_endian_expression_k(1, adobe::any_regular_t(true)); if (is_keyword(key_signed)) atom_base_type = atom_signed_k; else if (is_keyword(key_unsigned)) atom_base_type = atom_unsigned_k; else if (is_keyword(key_float)) atom_base_type = atom_float_k; else return false; require_expression(bit_count_expression); if (is_keyword(key_little)) is_big_endian_expression = is_little_endian_expression_k; else if (is_keyword(key_big)) is_big_endian_expression = is_big_endian_expression_k; else require_expression(is_big_endian_expression); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_typedef() { adobe::name_t named_field_identifier; atom_base_type_t atom_type(atom_unknown_k); adobe::array_t bit_count_expression; adobe::array_t is_big_endian_expression; adobe::name_t new_type_identifier; if (!is_keyword(key_typedef)) return false; if (!is_field_type( named_field_identifier, atom_type, bit_count_expression, is_big_endian_expression)) throw_exception("Field type expected"); require_identifier(new_type_identifier); adobe::dictionary_t parameters; parameters[key_field_name].assign(new_type_identifier); parameters[key_field_size_type].assign(field_size_none_k); // intentionally fixed parameters[key_field_size_expression].assign(adobe::array_t()); // intentionally fixed parameters[key_field_offset_expression].assign(adobe::array_t()); // intentionally fixed if (named_field_identifier != adobe::name_t()) { parameters[key_field_type].assign(value_field_type_typedef_named); parameters[key_named_type_name].assign(named_field_identifier); } else { parameters[key_field_type].assign(value_field_type_typedef_atom); parameters[key_atom_base_type].assign(atom_type); parameters[key_atom_bit_count_expression].assign(bit_count_expression); parameters[key_atom_is_big_endian_expression].assign(is_big_endian_expression); } insert_parser_metadata(parameters); add_typedef_proc_m(new_type_identifier, parameters); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_invariant() { return is_simple_assign_field(key_invariant, value_field_type_invariant); } /****************************************************************************************************/ bool binspector_parser_t::is_constant() { bool is_const(is_keyword(key_const)); bool is_invis(!is_const && is_keyword(key_invis)); if (!is_const && !is_invis) return false; adobe::name_t name; require_identifier(name); require_token(adobe::assign_k); adobe::array_t expression; require_expression(expression); // REVISIT (fbrereto) : // I should generalize these into "decorators", add them to the grammar and // reduce is_constant into a forwarding of is_simple_assign_field bool noprint(false); if (is_keyword(key_noprint) || is_invis) noprint = true; adobe::dictionary_t parameters; parameters[key_field_type].assign(value_field_type_const); parameters[key_field_name].assign(name); parameters[key_const_expression].assign(expression); parameters[key_const_no_print].assign(noprint); insert_parser_metadata(parameters); add_field_proc_m(name, parameters); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_notify() { if (!is_keyword(key_notify)) return false; adobe::array_t argument_list_expression; if (is_argument_list(argument_list_expression) == false) throw_exception("argument list required"); adobe::dictionary_t parameters; parameters[key_field_type].assign(value_field_type_notify); parameters[key_field_name].assign(value_field_type_notify); parameters[key_notify_expression].assign(argument_list_expression); insert_parser_metadata(parameters); add_unnamed_field_proc_m(parameters); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_skip() { if (!is_keyword(key_skip)) return false; adobe::name_t name; require_identifier(name); require_token(adobe::open_bracket_k); adobe::array_t expression; require_expression(expression); require_token(adobe::close_bracket_k); adobe::dictionary_t parameters; parameters[key_field_type].assign(value_field_type_skip); parameters[key_field_name].assign(name); parameters[key_skip_expression].assign(expression); insert_parser_metadata(parameters); add_field_proc_m(name, parameters); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_field() { adobe::name_t named_field_identifier; atom_base_type_t atom_type(atom_unknown_k); adobe::array_t bit_count_expression; adobe::array_t is_big_endian_expression; bool named_field(is_named_field(named_field_identifier)); bool atom_field(!named_field && is_atom_field(atom_type, bit_count_expression, is_big_endian_expression)); if (!named_field && !atom_field) return false; adobe::name_t field_identifier; require_identifier(field_identifier); adobe::array_t field_size_expression; field_size_t field_size_type(field_size_none_k); adobe::array_t offset_expression; adobe::array_t callback_expression; bool shuffleable(false); is_field_size(field_size_type, field_size_expression, shuffleable); // optional is_offset(offset_expression); // optional try { static const adobe::array_t empty_array_k; adobe::dictionary_t parameters; parameters[key_field_name].assign(field_identifier); parameters[key_field_size_type].assign(field_size_type); parameters[key_field_size_expression].assign(field_size_expression); parameters[key_field_offset_expression].assign(offset_expression); parameters[key_field_shuffle].assign(shuffleable); // add the field to the current structure description if (named_field) { parameters[key_field_type].assign(value_field_type_named); parameters[key_named_type_name].assign(named_field_identifier); } else { parameters[key_field_type].assign(value_field_type_atom); parameters[key_atom_base_type].assign(atom_type); parameters[key_atom_bit_count_expression].assign(bit_count_expression); parameters[key_atom_is_big_endian_expression].assign(is_big_endian_expression); } insert_parser_metadata(parameters); add_field_proc_m(field_identifier, parameters); } catch (const std::exception& error) { putback(); throw adobe::stream_error_t(error, next_position()); } return true; } /****************************************************************************************************/ bool binspector_parser_t::is_field_size(field_size_t& field_size_type, adobe::array_t& field_size_expression, bool& shuffleable) { if (!is_token(adobe::open_bracket_k)) return false; if (is_keyword(key_while)) { field_size_type = field_size_while_k; require_token(adobe::colon_k); } else if (is_keyword(key_terminator)) { field_size_type = field_size_terminator_k; require_token(adobe::colon_k); } else if (is_keyword(key_delimiter)) { field_size_type = field_size_delimiter_k; require_token(adobe::colon_k); } else { field_size_type = field_size_integer_k; } require_expression(field_size_expression); require_token(adobe::close_bracket_k); shuffleable = is_keyword(key_shuffle); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_slot() { return is_simple_assign_field(key_slot, value_field_type_slot); } /****************************************************************************************************/ bool binspector_parser_t::is_signal() { return is_simple_assign_field(key_signal, value_field_type_signal); } /****************************************************************************************************/ bool binspector_parser_t::is_offset(adobe::array_t& offset_expression) { if (!is_token(adobe::at_k)) return false; require_expression(offset_expression); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_summary() { if (!is_keyword(key_summary)) return false; adobe::array_t argument_list_expression; if (is_argument_list(argument_list_expression) == false) throw_exception("argument list required"); adobe::dictionary_t parameters; parameters[key_field_type].assign(value_field_type_summary); parameters[key_field_name].assign(value_field_type_summary); parameters[key_summary_expression].assign(argument_list_expression); insert_parser_metadata(parameters); add_unnamed_field_proc_m(parameters); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_die() { if (!is_keyword(key_die)) return false; adobe::array_t argument_list_expression; if (is_argument_list(argument_list_expression) == false) throw_exception("argument list required"); adobe::dictionary_t parameters; parameters[key_field_type].assign(value_field_type_die); parameters[key_field_name].assign(value_field_type_die); parameters[key_die_expression].assign(argument_list_expression); insert_parser_metadata(parameters); add_unnamed_field_proc_m(parameters); return true; } /****************************************************************************************************/ bool binspector_parser_t::is_pp_statement() { return is_pp_include(); } /****************************************************************************************************/ bool binspector_parser_t::is_pp_include() { if (!is_keyword(key_include)) return false; adobe::any_regular_t value; require_token(adobe::string_k, value); std::string value_str(value.cast<std::string>()); // std::cerr << "Include file " << value_str << '\n'; // do the parse; so far we don't support include directories; at this point // it'll get complicated when it does. // // we also need to track which files we include so we do not include them twice. boost::filesystem::path parsepath(include_directory_set_m[0] / value_str.c_str()); // REVISIT (fbrereto) : A std::string to a c-string to a std::string to a... c'mon. if (!exists(parsepath)) throw_exception( adobe::make_string("Could not find requested include file: ", value_str.c_str()) .c_str()); // check if file has already been parsed and added to the AST. if (adobe::find(included_file_set_m, parsepath) != included_file_set_m.end()) return true; included_file_set_m.push_back(parsepath); boost::filesystem::ifstream include_stream(parsepath); adobe::line_position_t::getline_proc_t getline(new adobe::line_position_t::getline_proc_impl_t( std::bind(&get_input_line, std::ref(include_stream), std::placeholders::_2))); adobe::line_position_t position(adobe::name_t(parsepath.string().c_str()), getline); try { binspector_parser_t(include_stream, position, include_directory_set_m, set_structure_proc_m, add_field_proc_m, add_unnamed_field_proc_m, add_typedef_proc_m, included_file_set_m) .parse(); } catch (const adobe::stream_error_t& error) { throw std::runtime_error(adobe::format_stream_error(include_stream, error)); } return true; } /****************************************************************************************************/ void binspector_parser_t::require_identifier(adobe::name_t& name_result) { const adobe::stream_lex_token_t& result(get_token()); if (result.first != adobe::identifier_k) throw_exception(adobe::identifier_k, result.first); name_result = result.second.cast<adobe::name_t>(); } /****************************************************************************************************/ bool binspector_parser_t::is_simple_assign_field(adobe::name_t keyword, adobe::name_t field_type) { if (!is_keyword(keyword)) return false; adobe::name_t name; require_identifier(name); require_token(adobe::assign_k); adobe::array_t expression; require_expression(expression); adobe::dictionary_t parameters; parameters[key_field_type].assign(field_type); parameters[key_field_name].assign(name); parameters[key_field_assign_expression].assign(expression); parameters[key_field_size_type].assign(field_size_none_k); // intentionally fixed parameters[key_field_size_expression].assign(adobe::array_t()); // intentionally fixed parameters[key_field_offset_expression].assign(adobe::array_t()); // intentionally fixed insert_parser_metadata(parameters); add_field_proc_m(name, parameters); return true; } /****************************************************************************************************/
33.649533
102
0.595251
[ "vector" ]
a38cb7c5cc5f757924d6dd924a9b9fc3f4cd3472
11,025
cpp
C++
src/linad99/fvar_mat.cpp
wStockhausen/admb
876ec704ae974d0ed3bcc329f243dbc401ad0e6d
[ "BSD-3-Clause" ]
79
2015-01-16T14:14:22.000Z
2022-01-24T06:28:15.000Z
src/linad99/fvar_mat.cpp
wStockhausen/admb
876ec704ae974d0ed3bcc329f243dbc401ad0e6d
[ "BSD-3-Clause" ]
172
2015-01-21T01:53:57.000Z
2022-03-29T19:57:31.000Z
src/linad99/fvar_mat.cpp
wStockhausen/admb
876ec704ae974d0ed3bcc329f243dbc401ad0e6d
[ "BSD-3-Clause" ]
22
2015-01-15T18:11:54.000Z
2022-01-11T21:47:51.000Z
/** Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California */ #include "fvar.hpp" #include "param_init_bounded_number_matrix.h" #ifndef OPT_LIB #include <cassert> #endif /** Default constructor */ dvar_matrix::dvar_matrix() { allocate(); } /** Copy constructor. \param other */ dvar_matrix::dvar_matrix(const dvar_matrix& other) { if (!(other)) { //cerr << "Making a copy of an unallocated dvar_matrix" << endl; allocate(); } else { index_min = other.index_min; index_max = other.index_max; shape = other.shape; if (shape) { (shape->ncopies)++; } m = other.m; } } /** Copy constructor */ dvar_matrix::dvar_matrix(const dmatrix& other) { index_min = other.index_min; index_max = other.index_max; if ((m = new dvar_vector[rowsize()]) == 0) { cerr << " Error allocating memory in dvar_matrix contructor"<<endl; ad_exit(21); } if ( (shape =new mat_shapex(m)) == 0) { cerr << " Error allocating memory in dvar_matrix contructor"<<endl; } m -= rowmin(); for (int i = rowmin(); i <= rowmax(); ++i) { m[i].allocate(other(i).indexmin(), other(i).indexmax()); elem(i) = other.elem(i); } } /** Destructor */ dvar_matrix::~dvar_matrix() { if (shape) { if (shape->ncopies) { (shape->ncopies)--; } else { deallocate(); } } } /** Constructs AD variable matrix with dimensions nrl to nrh by ncl to nch. \param nrl row lower index \param nrh row higher index \param ncl column lower index \param nch column higher index */ dvar_matrix::dvar_matrix(int nrl, int nrh, int ncl, int nch) { allocate(nrl,nrh,ncl,nch); #ifndef OPT_LIB initialize(); #endif } /** * Description not yet available. * \param */ dvar_matrix::dvar_matrix(int nrl, int nrh, kkludge_object kk) { allocate(nrl,nrh); #ifndef OPT_LIB initialize(); #endif } /** * Description not yet available. * \param */ dvar_matrix::dvar_matrix(int nrl,int nrh) { allocate(nrl,nrh); #ifndef OPT_LIB initialize(); #endif } /** * Description not yet available. * \param */ dvar_matrix::dvar_matrix(const param_init_bounded_number_matrix& pibnm) { int indexmin = pibnm.indexmin(); int indexmax = pibnm.indexmax(); allocate(indexmin, indexmax); #ifndef OPT_LIB initialize(); #endif for (int i = indexmin; i <= indexmax; i++) { dvar_vector v(pibnm(i)); this->operator()(i) = v; } } /** * Description not yet available. * \param */ dvar_matrix dvar_matrix::sub(int nrl,int nrh) { if (allocated(*this)) { dvar_matrix tmp(nrl,nrh); for (int i=nrl; i<=nrh; i++) { tmp[i].shallow_copy((*this)(i)); } return tmp; } else { return *this; } } /** Allocate variable matrix with dimension [nrl to nrh] where columns are empty. If nrl greater than nrh, then dvar_matrix is initialized as empty. \param nrl lower index \param nrh upper index */ void dvar_matrix::allocate(int nrl, int nrh) { if (nrl > nrh) { allocate(); } else { index_min = nrl; index_max = nrh; if ((m = new dvar_vector[rowsize()]) == 0) { cerr << " Error allocating memory in dvar_matrix::allocate(int, int)\n"; ad_exit(1); } if ((shape = new mat_shapex(m)) == 0) { cerr << " Error allocating memory in dvar_matrix::allocate(int, int)\n"; ad_exit(1); } m -= rowmin(); for (int i = nrl; i <= nrh; ++i) { elem(i).allocate(); } } } /** Allocates AD variable matrix with dimensions nrl to nrh by ncl to nch. \param nrl row lower index \param nrh row higher index \param ncl column lower index \param nch column higher index */ void dvar_matrix::allocate(int nrl, int nrh, int ncl, int nch) { allocate(nrl, nrh); for (int i = nrl; i <= nrh; ++i) { elem(i).allocate(ncl, nch); } } /** Allocate variable matrix with dimension [nrl to nrh] where columns are empty. If nrl greater than nrh, then dvar_matrix is initialized as empty. \param nrl lower index \param nrh upper index */ void dvar_matrix::allocate(ad_integer nrl, ad_integer nrh) { allocate(static_cast<int>(nrl), static_cast<int>(nrh)); } /** Allocate variable matrix using the same dimensions as m1. */ void dvar_matrix::allocate(const dmatrix& m1) { if (m1.shape) { int nrl = m1.rowmin(); int nrh = m1.rowmax(); index_min = nrl; index_max = nrh; if ((m = new dvar_vector[rowsize()]) == 0) { cerr << " Error allocating memory in dvar_matrix contructor\n"; ad_exit(21); } if ((shape = new mat_shapex(m)) == 0) { cerr << " Error allocating memory in dvar_matrix contructor\n"; } m -= rowmin(); for (int i = nrl; i <= nrh; ++i) { m[i].allocate(m1(i)); } } else { //cerr << "Warning -- trying to make a dvar_matrix copy of an " // " unallocated dmatrix" << endl; allocate(); } } /** Allocate variable matrix using the same dimensions as m1. */ void dvar_matrix::allocate(const dvar_matrix& m1) { if (m1.shape) { int nrl = m1.rowmin(); int nrh = m1.rowmax(); index_min = nrl; index_max = nrh; if ((m = new dvar_vector[rowsize()]) == 0) { cerr << " Error allocating memory in dvar_matrix contructor"<<endl; ad_exit(21); } if ((shape=new mat_shapex(m)) == 0) { cerr << " Error allocating memory in dvar_matrix contructor"<<endl; } m -= rowmin(); for (int i = nrl; i <= nrh; ++i) { m[i].allocate(m1(i)); } } else { //cerr << "Warning -- trying to make a dvar_matrix copy of an " // "unallocated dvar_matrix" << endl; allocate(); } } /** * Description not yet available. * \param */ dvar_matrix::dvar_matrix(int nrl, int nrh, const ivector& ncl, const ivector& nch) { allocate(nrl,nrh,ncl,nch); #ifndef OPT_LIB initialize(); #endif } /** Allocate variable matrix with dimensions [nrl to nrh] x [ncl to nch] where ncl and nch. \param nrl lower row index \param nrl upper row index \param ncl vector of lower column indexes \param nch vector of upper column indexes */ void dvar_matrix::allocate( int nrl, int nrh, const ivector& ncl, const ivector& nch) { if (nrl > nrh) { allocate(); } else { if (nrl != ncl.indexmin() || nrh != ncl.indexmax() || nrl != nch.indexmin() || nrh != nch.indexmax()) { cerr << "Incompatible array bounds in " "dvar_matrix(int nrl, int nrh, const ivector& ncl, const ivector& nch)" << endl ; ad_exit(1); } index_min = nrl; index_max = nrh; if ((m = new dvar_vector[rowsize()]) == 0) { cerr << " Error allocating memory in dvar_matrix contructor"<<endl; ad_exit(21); } if ((shape = new mat_shapex(m)) == 0) { cerr << " Error allocating memory in dvar_matrix contructor"<<endl; } m -= rowmin(); for (int i = nrl; i <= nrh; ++i) { m[i].allocate(ncl[i], nch[i]); } } } /** * Description not yet available. * \param */ dvar_matrix::dvar_matrix(int nrl, int nrh, int ncl, const ivector& nch) { allocate(nrl,nrh,ncl,nch); #ifndef OPT_LIB initialize(); #endif } /** Allocate variable matrix with dimensions [nrl to nrh] x [ncl to nch] where nch is a vector of indexes. \param nrl lower row index \param nrh upper row index \param ncl lower column index \param nch vector upper column indexes */ void dvar_matrix::allocate(int nrl, int nrh, int ncl, const ivector& nch) { if (nrl>nrh) { allocate(); } else { if (nrl != nch.indexmin() || nrh != nch.indexmax()) { cerr << "Incompatible array bounds in " "dvar_matrix(int nrl, int nrh, const int& ncl, const ivector& nch)" << endl; ad_exit(1); } index_min = nrl; index_max = nrh; if ((m = new dvar_vector[rowsize()]) == 0) { cerr << " Error allocating memory in dvar_matrix contructor"<<endl; ad_exit(21); } if ((shape = new mat_shapex(m)) == 0) { cerr << " Error allocating memory in dvar_matrix contructor"<<endl; } m -= rowmin(); for (int i = nrl; i <= nrh; ++i) { m[i].allocate(ncl,nch[i]); } } } /** Allocate variable matrix with dimensions [nrl to nrh] x [ncl to nch] where ncl is a vector of indexes. \param nrl lower row index \param nrh upper row index \param ncl vector lower column indexes \param nch upper column index */ void dvar_matrix::allocate(int nrl, int nrh, const ivector& ncl, int nch) { allocate(nrl, nrh); for (int i = nrl; i <= nrh; ++i) { elem(i).allocate(ncl(i), nch); } } /** Shallow copy other data structure pointers. \param other dvar3_array */ void dvar_matrix::shallow_copy(const dvar_matrix& other) { if (other.shape) { shape = other.shape; ++(shape->ncopies); m = other.m; index_min = other.index_min; index_max = other.index_max; } else { #ifdef DEBUG cerr << "Warning -- Unable to shallow copy an unallocated dvar_matrix.\n"; #endif allocate(); } } /// Does not allocate, but initializes members. void dvar_matrix::allocate() { index_min = 1; index_max = 0; shape = nullptr; m = nullptr; } /// Deallocate dvar_matrix memory. void dvar_matrix::deallocate() { if (shape) { if (shape->ncopies > 0) { --(shape->ncopies); } else { m = static_cast<dvar_vector*>(shape->get_pointer()); delete [] m; delete shape; } allocate(); } #if defined(DIAG) else { cerr << "Warning -- Unable to deallocate an unallocated dvar_matrix.\n"; } #endif } /** Assigns other values to dvar_matrix. \param values dmatrix */ dvar_matrix& dvar_matrix::operator=(const dvar_matrix& other) { if (!allocated(*this)) { shallow_copy(other); } else { if (rowmin() != other.rowmin() || rowmax() != other.rowmax()) { cerr << "Error: Incompatible array bounds in " "dvar_matrix& dvar_matrix::operator=(const dvar_matrix&)\n"; ad_exit(1); } // check for condition that both matrices don't point to the same object if (m != other.m) { for (int i = rowmin(); i <= rowmax(); ++i) { elem(i) = other.elem(i); } } } return *this; } /** Assigns scalar matrix values to dvar_matrix. \param matrix dmatrix */ dvar_matrix& dvar_matrix::operator=(const dmatrix& matrix) { if (rowmin() != matrix.rowmin() || rowmax() != matrix.rowmax()) { cerr << "Error: Incompatible array bounds in " << "dvar_matrix& dvar_matrix::operator=(const dmatrix&)\n"; ad_exit(1); } for (int i = rowmin(); i <= rowmax(); ++i) { elem(i) = matrix.elem(i); } return *this; } /** * Description not yet available. * \param */ void copy_status(const ostream& _s, const dvar_matrix& m1) { ostream& s= (ostream&) _s; s << " matrix_copy flags \n"; for (int i=m1.rowmin(); i<=m1.rowmax(); i++) { copy_status(s,m1[i]); } s <<"\n"; }
20.155393
78
0.607619
[ "object", "shape", "vector" ]
a38cc192ed10197d54eea1c175f1bb51be56703f
22,139
cpp
C++
src/armnnOnnxParser/test/Conv2D.cpp
tuanhe/armnn
8a4bd6671d0106dfb788b8c9019f2f9646770f8d
[ "MIT" ]
1
2021-07-03T23:46:08.000Z
2021-07-03T23:46:08.000Z
src/armnnOnnxParser/test/Conv2D.cpp
tuanhe/armnn
8a4bd6671d0106dfb788b8c9019f2f9646770f8d
[ "MIT" ]
null
null
null
src/armnnOnnxParser/test/Conv2D.cpp
tuanhe/armnn
8a4bd6671d0106dfb788b8c9019f2f9646770f8d
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include <boost/test/unit_test.hpp> #include "armnnOnnxParser/IOnnxParser.hpp" #include "ParserPrototxtFixture.hpp" BOOST_AUTO_TEST_SUITE(OnnxParser) struct SimpleConv2DFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser> { SimpleConv2DFixture() { m_Prototext = R"( ir_version: 3 producer_name: "CNTK" producer_version: "2.5.1" domain: "ai.cntk" model_version: 1 graph { name: "CNTKGraph" input { name: "Input" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 3 } dim { dim_value: 3 } } } } } input { name: "Weight" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 3 } dim { dim_value: 3 } } } } } initializer { dims: 1 dims: 1 dims: 3 dims: 3 data_type: 1 float_data: 2 float_data: 1 float_data: 0 float_data: 6 float_data: 2 float_data: 1 float_data: 4 float_data: 1 float_data: 2 name: "Weight" } node { input: "Input" input: "Weight" output: "Output" name: "Convolution" op_type: "Conv" attribute { name: "kernel_shape" ints: 3 ints: 3 type: INTS } attribute { name: "strides" ints: 1 ints: 1 type: INTS } attribute { name: "auto_pad" s: "VALID" type: STRING } attribute { name: "group" i: 1 type: INT } attribute { name: "dilations" ints: 1 ints: 1 type: INTS } doc_string: "" domain: "" } output { name: "Output" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 1 } } } } } } opset_import { version: 7 })"; Setup(); } }; struct Conv2DWithBiasesFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser> { Conv2DWithBiasesFixture() { m_Prototext = R"( ir_version: 3 producer_name: "CNTK" producer_version: "2.5.1" domain: "ai.cntk" model_version: 1 graph { name: "CNTKGraph" input { name: "Input" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 2 } dim { dim_value: 2 } } } } } input { name: "Weight" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 2 } dim { dim_value: 2 } } } } } initializer { dims: 1 dims: 1 dims: 2 dims: 2 data_type: 1 float_data: 2 float_data: 1 float_data: 0 float_data: 6 name: "Weight" } input { name: "Bias" type { tensor_type { elem_type: 1 shape { dim { dim_value: 4 } } } } } initializer { dims: 4 data_type: 1 float_data: 10 float_data: 0 float_data: 0 float_data: 0 name: "Bias" } node { input: "Input" input: "Weight" input: "Bias" output: "Output" name: "Convolution" op_type: "Conv" attribute { name: "kernel_shape" ints: 2 ints: 2 type: INTS } attribute { name: "strides" ints: 1 ints: 1 type: INTS } attribute { name: "auto_pad" s: "SAME_UPPER" type: STRING } attribute { name: "group" i: 1 type: INT } attribute { name: "dilations" ints: 1 ints: 1 type: INTS } doc_string: "" domain: "" } output { name: "Output" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 2 } dim { dim_value: 2 } } } } } } opset_import { version: 7 })"; Setup(); } }; struct Conv2DDimReducingFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser> { Conv2DDimReducingFixture() { m_Prototext = R"( ir_version: 3 producer_name: "CNTK" producer_version: "2.5.1" domain: "ai.cntk" model_version: 1 graph { name: "CNTKGraph" input { name: "Input" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 3 } dim { dim_value: 2 } dim { dim_value: 2 } } } } } input { name: "Weight" type { tensor_type { elem_type: 1 shape { dim { dim_value: 2 } dim { dim_value: 3 } dim { dim_value: 1 } dim { dim_value: 1 } } } } } initializer { dims: 2 dims: 3 dims: 1 dims: 1 data_type: 1 float_data: -1 float_data: 2 float_data: 0 float_data: 1 float_data: 0 float_data: 0 name: "Weight" } node { input: "Input" input: "Weight" output: "Output" name: "Convolution" op_type: "Conv" attribute { name: "kernel_shape" ints: 1 ints: 1 type: INTS } attribute { name: "strides" ints: 1 ints: 1 type: INTS } attribute { name: "group" i: 1 type: INT } attribute { name: "dilations" ints: 1 ints: 1 type: INTS } doc_string: "" domain: "" } output { name: "Output" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 2 } dim { dim_value: 2 } dim { dim_value: 2 } } } } } } opset_import { version: 7 })"; Setup(); } }; struct Conv2DwithDilationFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser> { Conv2DwithDilationFixture() { m_Prototext = R"( ir_version: 3 producer_name: "CNTK" producer_version: "2.5.1" domain: "ai.cntk" model_version: 1 graph { name: "CNTKGraph" input { name: "Input" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 6 } dim { dim_value: 6 } } } } } input { name: "Weight" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 3 } dim { dim_value: 3 } } } } } initializer { dims: 1 dims: 1 dims: 3 dims: 3 data_type: 1 float_data: 2 float_data: 1 float_data: 0 float_data: 6 float_data: 2 float_data: 1 float_data: 4 float_data: 1 float_data: 2 name: "Weight" } node { input: "Input" input: "Weight" output: "Output" name: "Convolution" op_type: "Conv" attribute { name: "kernel_shape" ints: 3 ints: 3 type: INTS } attribute { name: "strides" ints: 1 ints: 1 type: INTS } attribute { name: "auto_pad" s: "VALID" type: STRING } attribute { name: "group" i: 1 type: INT } attribute { name: "dilations" ints: 2 ints: 2 type: INTS } doc_string: "" domain: "" } output { name: "Output" type { tensor_type { elem_type: 1 shape { dim { dim_value: 1 } dim { dim_value: 1 } dim { dim_value: 2 } dim { dim_value: 2 } } } } } } opset_import { version: 7 })"; Setup(); } }; BOOST_FIXTURE_TEST_CASE(ValidConvTest, SimpleConv2DFixture) { RunTest<4>({{"Input", {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}}}, {{"Output", {1.0 * 2 + 2.0 * 1 + 3.0 * 0 + 4.0 * 6 + 5.0 * 2 + 6.0 * 1 + 7.0 * 4 + 8.0 * 1 + 9.0 * 2}}}); } BOOST_FIXTURE_TEST_CASE(ValidConvWithBiasTest, Conv2DWithBiasesFixture) { RunTest<4>({{"Input", {1.0, 2.0, 3.0, 4.0}}}, {{"Output", {1.0 * 2 + 2.0 * 1 + 3.0 * 0 + 4 * 6 + 10, 2.0 * 2 + 0 * 1 + 4.0 * 0 + 0 * 6 + 10, 3.0 * 2 + 4.0 * 1 + 0 * 0 + 0 * 6 + 10, 4.0 * 2 + 0 * 1 + 0 * 0 + 0 * 6 + 10}}}); } BOOST_FIXTURE_TEST_CASE(ValidConvDimReducTest, Conv2DDimReducingFixture) { RunTest<4>({{"Input", {1.0, 2.0, 3.0, 4.0, -1, -2, 3, 4, 1 , 1, 1, 1 }}}, {{"Output", {-1 * 1 + 2 * -1, -1 * 2 + 2 * -2, -1 * 3 + 2 * 3, -1 * 4 + 2 * 4, 1, 2, 3, 4}}}); } BOOST_FIXTURE_TEST_CASE(ValidConvWithDilationTest, Conv2DwithDilationFixture) { RunTest<4>({{"Input", {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0}}}, {{"Output", {39.0, 58.0, 153.0, 172.0 }}}); } BOOST_AUTO_TEST_SUITE_END()
35.650564
105
0.207597
[ "shape" ]
a3953dd75ad1c75df9313e72412ed076693f31ec
3,070
cpp
C++
oneflow/core/boxing/symmetric_b_to_p_boxing.cpp
Tron-x/oneflow
6febac5afab38c74da594a4200f85121a98e51c4
[ "Apache-2.0" ]
null
null
null
oneflow/core/boxing/symmetric_b_to_p_boxing.cpp
Tron-x/oneflow
6febac5afab38c74da594a4200f85121a98e51c4
[ "Apache-2.0" ]
null
null
null
oneflow/core/boxing/symmetric_b_to_p_boxing.cpp
Tron-x/oneflow
6febac5afab38c74da594a4200f85121a98e51c4
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The OneFlow 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 "oneflow/core/boxing/eager_boxing_interpreter.h" #include "oneflow/core/framework/device.h" #include "oneflow/core/framework/nd_sbp.h" #include "oneflow/core/job/global_for.h" #include "oneflow/core/job/resource_desc.h" #include "oneflow/core/control/global_process_ctx.h" #include "oneflow/core/functional/functional.h" namespace oneflow { namespace { bool IsAllBroadcastNdSbp(Symbol<NdSbp> nd_sbp) { for (const auto& sbp_parallel : nd_sbp->sbp_parallel()) { if (!sbp_parallel.has_broadcast_parallel()) { return false; } } return true; } bool IsAllPartialSumNdSbp(Symbol<NdSbp> nd_sbp) { for (const auto& sbp_parallel : nd_sbp->sbp_parallel()) { if (!sbp_parallel.has_partial_sum_parallel()) { return false; } } return true; } Maybe<void> RawCheckSymmetricBToP(Symbol<PlacedNdSbp> in, Symbol<PlacedNdSbp> out, const Shape& logical_shape) { CHECK_EQ_OR_RETURN(in->nd_sbp()->sbp_parallel_size(), 1); CHECK_EQ_OR_RETURN(out->nd_sbp()->sbp_parallel_size(), 1); CHECK_OR_RETURN(IsAllBroadcastNdSbp(in->nd_sbp())); CHECK_OR_RETURN(IsAllPartialSumNdSbp(out->nd_sbp())); CHECK_OR_RETURN(in->placement() == out->placement()); return Maybe<void>::Ok(); } static constexpr auto* CheckSymmetricBToP = DECORATE(&RawCheckSymmetricBToP, ThreadLocalCopiable); } // namespace Maybe<one::Tensor> SymmetricBToP(const std::shared_ptr<one::Tensor>& tensor, Symbol<PlacedNdSbp> in, Symbol<PlacedNdSbp> out) { const auto& tensor_nd_sbp = JUST(tensor->nd_sbp()); CHECK_OR_RETURN(tensor_nd_sbp == in->nd_sbp()); const auto& tensor_placement = JUST(tensor->parallel_desc()); CHECK_OR_RETURN(tensor_placement == in->placement()); int64_t root = JUST(tensor_placement->MachineId4ParallelId(0)); std::shared_ptr<one::Tensor> local_tensor = JUST(tensor->cur_rank_phy_tensor()); if (root == GlobalProcessCtx::Rank()) { // do nothing } else { const std::string& device_type = Device::Type4DeviceTag(tensor_placement->device_tag()); local_tensor = JUST(one::functional::ZerosLike(local_tensor)); } return JUST(one::functional::LocalToConsistent(local_tensor, out->placement(), *JUST(GetSbpList(out->nd_sbp())), *tensor->shape(), tensor->dtype())); } COMMAND(RegisterBoxingFunction("symmetric-b-to-p", CheckSymmetricBToP, &SymmetricBToP)); } // namespace oneflow
38.375
100
0.712704
[ "shape" ]
a398a88c8a5eb95a5685f23895528750247ac15f
3,147
cpp
C++
purelib/utils/experimental/thread_basic.cpp
xubingyue/libxstudio365
99a11fe8ac1644fcc2d4d5331779c4b13afa158e
[ "MIT" ]
null
null
null
purelib/utils/experimental/thread_basic.cpp
xubingyue/libxstudio365
99a11fe8ac1644fcc2d4d5331779c4b13afa158e
[ "MIT" ]
null
null
null
purelib/utils/experimental/thread_basic.cpp
xubingyue/libxstudio365
99a11fe8ac1644fcc2d4d5331779c4b13afa158e
[ "MIT" ]
4
2017-09-04T02:11:00.000Z
2022-01-01T06:21:49.000Z
#include <errno.h> #include <signal.h> #include <process.h> #include "thread_basic.h" #ifndef _WIN32 #include <string.h> #endif #include <iostream> using namespace thelib::asy; int thread_basic::spawn(THREAD_PROC base, void* arg, size_t stacksize, int flags, _Thrd_t* pthr) { _Thrd_t thr; int retc = 0; #ifdef _WIN32 #ifdef _WIN32_WCE SetLastError(0); thr._Hnd = ::CreateThread(nullptr, stacksize, base, arg, flags, (LPDWORD)&thr._Id); #else thr._Hnd = (HANDLE)::_beginthreadex(nullptr, stacksize, (unsigned int(__stdcall*)(void*))base, arg, flags, &thr._Id); retc = GetLastError(); #endif #else pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, flags); pthread_attr_setstacksize(&attr, stacksize); retc = pthread_create(&thr._Id, &attr, base, arg); pthread_attr_destroy(&attr); #endif //#if 1 // thr._Hnd = ::_beginthreadex(nullptr, stacksize, //#endif if(pthr != nullptr) { *pthr = thr; } return retc; } int thread_basic::join(_Thrd_t thr) { #ifdef _WIN32 return WaitForSingleObject(thr._Hnd, INFINITE); #else return pthread_join(thr._Id, NULL); #endif } //int thread_basic::join_n(thr_handle* thrs, size_t number) //{ // int retc = 0; //#ifdef _WIN32 // retc = WaitForMultipleObjects(number, thrs, TRUE, INFINITE); //#else // for(size_t i = 0; i < number; ++i) // { // retc += thread_basic::join(thrs[i]); // } //#endif // return retc; //} thread_basic::thread_basic(void) { #ifdef __GNUC__ this->joinable = false; #endif } thread_basic::~thread_basic(void) { close(); } int thread_basic::open(int flags, size_t stacksize) { if(!this->is_open()) { int stat = thread_basic::spawn((THREAD_PROC)thread_basic::_ThreadEntry, this, stacksize, flags, &this->_Thr); #ifdef __GNUC__ this->joinable = (0 == stat && (thr_joinable == flags || 0 == flags)); #endif return stat; } return 0; } bool thread_basic::is_open(void) const { return !_Thr_is_null(_Thr); } void thread_basic::close(void) { if(this->is_open()) { thr_kill(this->_Thr); this->join(); this->_Reset_handle(); } } int thread_basic::join(void) { int ret = 0; if( this->is_joinable() ) { #ifdef __GNUC__ this->joinable = false; #endif ret = thread_basic::join(this->_Thr); #ifdef _WIN32 ::CloseHandle(this->_Thr._Hnd); #endif this->_Reset_handle(); return ret; } return 0; } bool thread_basic::is_joinable(void) const { #ifdef _WIN32 return this->is_open(); #else return this->joinable; #endif } thr_id thread_basic::get_id(void) const { return thr_getid(this->_Thr); } void* thread_basic::get_handle(void) const { return this->_Thr._Hnd; } void thread_basic::_Reset_handle(void) { this->_Thr._Hnd = 0; } thread_return_t thread_basic::_ThreadEntry(thread_basic& object) { return object.svc(); }
20.435065
122
0.612329
[ "object" ]