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
aa27770cb03994a0115f2893cf0e0189d713f978
6,486
cpp
C++
ros/src/computing/perception/detection/lidar_tracker/packages/lidar_imm_ukf_pda_track/nodes/visualize_detected_objects/visualize_detected_objects.cpp
K1504296/Autoware
0de5ae709a84d6c87ffef9b3099771d5efc19f0d
[ "BSD-3-Clause" ]
64
2018-11-19T02:34:05.000Z
2021-12-27T06:19:48.000Z
dink/src/computing/perception/detection/lidar_tracker/packages/lidar_imm_ukf_pda_track/nodes/visualize_detected_objects/visualize_detected_objects.cpp
920911love/DINK
d760ea99f21c4d6334ff5f517b49c4fdfca32399
[ "BSD-3-Clause" ]
null
null
null
dink/src/computing/perception/detection/lidar_tracker/packages/lidar_imm_ukf_pda_track/nodes/visualize_detected_objects/visualize_detected_objects.cpp
920911love/DINK
d760ea99f21c4d6334ff5f517b49c4fdfca32399
[ "BSD-3-Clause" ]
34
2018-11-27T08:57:32.000Z
2022-02-18T08:06:04.000Z
/* * Copyright (c) 2018, Nagoya University * 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 Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "visualize_detected_objects.h" #include <visualization_msgs/MarkerArray.h> #include <tf/transform_datatypes.h> #include <cmath> VisualizeDetectedObjects::VisualizeDetectedObjects() : vis_arrow_height_(0.5), vis_id_height_(1.5) { ros::NodeHandle private_nh_("~"); private_nh_.param<std::string>("pointcloud_frame", pointcloud_frame_, "velodyne"); private_nh_.param<double>("ignore_velocity_thres", ignore_velocity_thres_, 0.1); private_nh_.param<double>("visualize_arrow_velocity_thres", visualize_arrow_velocity_thres_, 0.25); sub_object_array_ = node_handle_.subscribe("/detection/lidar_tracker/objects", 1, &VisualizeDetectedObjects::callBack, this); pub_arrow_ = node_handle_.advertise<visualization_msgs::MarkerArray>("/detection/lidar_tracker/arrow_markers", 10); pub_id_ = node_handle_.advertise<visualization_msgs::MarkerArray>("/detection/lidar_tracker/id_markes", 10); } void VisualizeDetectedObjects::callBack(const autoware_msgs::DetectedObjectArray& input) { visMarkers(input); } void VisualizeDetectedObjects::visMarkers(const autoware_msgs::DetectedObjectArray& input) { visualization_msgs::MarkerArray marker_ids, marker_arows; for (size_t i = 0; i < input.objects.size(); i++) { // pose_reliable == true if tracking state is stable // skip vizualizing if tracking state is unstable if (!input.objects[i].pose_reliable) { continue; } double velocity = input.objects[i].velocity.linear.x; tf::Quaternion q(input.objects[i].pose.orientation.x, input.objects[i].pose.orientation.y, input.objects[i].pose.orientation.z, input.objects[i].pose.orientation.w); double roll, pitch, yaw; tf::Matrix3x3(q).getRPY(roll, pitch, yaw); // in the case motion model fit opposite direction if (velocity < -0.1) { velocity *= -1; yaw += M_PI; // normalize angle while (yaw > M_PI) yaw -= 2. * M_PI; while (yaw < -M_PI) yaw += 2. * M_PI; } visualization_msgs::Marker id; id.lifetime = ros::Duration(0.2); id.header.frame_id = pointcloud_frame_; id.header.stamp = input.header.stamp; id.ns = "id"; id.action = visualization_msgs::Marker::ADD; id.type = visualization_msgs::Marker::TEXT_VIEW_FACING; // green id.color.g = 1.0f; id.color.a = 1.0; id.id = input.objects[i].id; // Set the pose of the marker. This is a full 6DOF pose relative to the frame/time specified in the header id.pose.position.x = input.objects[i].pose.position.x; id.pose.position.y = input.objects[i].pose.position.y; id.pose.position.z = vis_id_height_; // convert from RPY to quartenion tf::Matrix3x3 obs_mat; obs_mat.setEulerYPR(yaw, 0, 0); // yaw, pitch, roll tf::Quaternion q_tf; obs_mat.getRotation(q_tf); id.pose.orientation.x = q_tf.getX(); id.pose.orientation.y = q_tf.getY(); id.pose.orientation.z = q_tf.getZ(); id.pose.orientation.w = q_tf.getW(); id.scale.z = 1.0; if (abs(velocity) < ignore_velocity_thres_) { velocity = 0.0; } // convert unit m/s to km/h std::string s_velocity = std::to_string(velocity * 3.6); std::string modified_sv = s_velocity.substr(0, s_velocity.find(".") + 3); std::string text = "<" + std::to_string(input.objects[i].id) + "> " + modified_sv + " km/h"; id.text = text; marker_ids.markers.push_back(id); visualization_msgs::Marker arrow; arrow.lifetime = ros::Duration(0.2); // visualize velocity arrow only if its status is Stable std::string label = input.objects[i].label; if (label == "None" || label == "Initialized" || label == "Lost" || label == "Static") { continue; } if (abs(velocity) < visualize_arrow_velocity_thres_) { continue; } arrow.header.frame_id = pointcloud_frame_; arrow.header.stamp = input.header.stamp; arrow.ns = "arrow"; arrow.action = visualization_msgs::Marker::ADD; arrow.type = visualization_msgs::Marker::ARROW; // green arrow.color.g = 1.0f; arrow.color.a = 1.0; arrow.id = input.objects[i].id; // Set the pose of the marker. This is a full 6DOF pose relative to the frame/time specified in the header arrow.pose.position.x = input.objects[i].pose.position.x; arrow.pose.position.y = input.objects[i].pose.position.y; arrow.pose.position.z = vis_arrow_height_; arrow.pose.orientation.x = q_tf.getX(); arrow.pose.orientation.y = q_tf.getY(); arrow.pose.orientation.z = q_tf.getZ(); arrow.pose.orientation.w = q_tf.getW(); // Set the scale of the arrow -- 1x1x1 here means 1m on a side arrow.scale.x = 3; arrow.scale.y = 0.1; arrow.scale.z = 0.1; marker_arows.markers.push_back(arrow); } // end input.objects loop pub_id_.publish(marker_ids); pub_arrow_.publish(marker_arows); }
37.062857
117
0.696115
[ "model" ]
aa2b7dfb9a18d332b8ec5f0cb051249b68490956
8,806
cpp
C++
robi_plugin.cpp
akalberer/robi_plugin
6e8a2d4b0abc516be67156ab0809a58ad3b829dd
[ "Apache-2.0" ]
null
null
null
robi_plugin.cpp
akalberer/robi_plugin
6e8a2d4b0abc516be67156ab0809a58ad3b829dd
[ "Apache-2.0" ]
null
null
null
robi_plugin.cpp
akalberer/robi_plugin
6e8a2d4b0abc516be67156ab0809a58ad3b829dd
[ "Apache-2.0" ]
null
null
null
#ifndef _ROBI_PLUGIN_HPP_ #define _ROBI_PLUGIN_HPP_ #include <gazebo/gazebo.hh> #include <gazebo/physics/Model.hh> #include <gazebo/physics/Joint.hh> #include <gazebo/common/PID.hh> #include <gazebo/physics/JointController.hh> #include <gazebo/physics/physics.hh> #include <string> #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> #include <ros/ros.h> #include <ros/callback_queue.h> #include <ros/subscribe_options.h> #include <std_msgs/Float32.h> #include <std_msgs/Float64.h> #include <geometry_msgs/Pose.h> #include <thread> #include <gazebo/math/Pose.hh> namespace gazebo { /// \brief Plugin to control the Robi class RobiPlugin : public ModelPlugin { /// \brief Constructor public: RobiPlugin() { const std::string left_wheel_name = "robi_model::robi::left_wheel_hinge"; } /// \brief The load function is called by Gazebo when the plugin is /// inserted into simulation /// \param[in] _model A pointer to the model that this plugin is /// attached to. /// \param[in] _sdf A pointer to the plugin's SDF element. public: virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) { // Just output a message for now std::cerr << "\nThe velodyne plugin is attach to model[" << _model->GetName() << "]\n"; // Safety check if (_model->GetJointCount() == 0) { std::cerr << "Invalid joint count, Velodyne plugin not loaded\n"; return; } std::cerr << "nof joints: " << _model->GetJointCount(); // Store the model pointer for convenience. this->model = _model; // Get the first joint. We are making an assumption about the model // that left is always first this->joint_left = _model->GetJoint("robi_model::robi::left_wheel_hinge"); this->joint_right = _model->GetJoint("robi_model::robi::right_wheel_hinge"); // Setup a P-controller, with a gain of 0.1. this->pid_left = common::PID(0.1, 0, 0); this->pid_right = common::PID(0.1, 0, 0); double velocity_left = 0; double velocity_right = 0; if(_sdf->HasElement("velocity_left")){ velocity_left = _sdf->Get<double>("velocity_left"); } if(_sdf->HasElement("velocity_right")){ velocity_right = _sdf->Get<double>("velocity_right"); } // Apply the P-controller to the joint. this->model->GetJointController()->SetVelocityPID(this->joint_left->GetScopedName(), this->pid_left); this->model->GetJointController()->SetVelocityPID(this->joint_right->GetScopedName(), this->pid_right); // Set the joint's target velocity. This target velocity is just // for demonstration purposes. std::cerr << "name joint: " << this->joint_left->GetScopedName() << std::endl; this->model->GetJointController()->SetVelocityTarget(this->joint_left->GetScopedName(), velocity_left); this->model->GetJointController()->SetVelocityTarget(this->joint_right->GetScopedName(), velocity_right); // Create the node this->node = transport::NodePtr(new transport::Node()); this->node->Init(this->model->GetWorld()->GetName()); std::cerr << "model name: " << this->model->GetName() << "\n"; // Create topic names std::string topicNameLeft = "~/" + this->model->GetName() + "/robi_cmd_left"; std::string topicNameRight = "~/" + this->model->GetName() + "/robi_cmd_right"; // Subscribe to the topic, and register a callback this->sub_left = this->node->Subscribe(topicNameLeft, &RobiPlugin::OnMsgLeft, this); this->sub_right = this->node->Subscribe(topicNameRight, &RobiPlugin::OnMsgRight, this); // Initialize ros, if it has not already bee initialized. if (!ros::isInitialized()) { int argc = 0; char **argv = NULL; ros::init(argc, argv, "gazebo_client", ros::init_options::NoSigintHandler); } // Create our ROS node. This acts in a similar manner to the Gazebo node this->rosNode.reset(new ros::NodeHandle("gazebo_client")); // Create a named topic, and subscribe to it. ros::SubscribeOptions so_left = ros::SubscribeOptions::create<std_msgs::Float32>("/" + this->model->GetName() + "/robi_cmd_left", 1, boost::bind(&RobiPlugin::OnRosMsgLeft, this, _1), ros::VoidPtr(), &this->rosQueue_left); this->rosSub_left = this->rosNode->subscribe(so_left); ros::SubscribeOptions so_right = ros::SubscribeOptions::create<std_msgs::Float32>("/" + this->model->GetName() + "/robi_cmd_right", 1, boost::bind(&RobiPlugin::OnRosMsgRight, this, _1), ros::VoidPtr(), &this->rosQueue_right); this->rosSub_right = this->rosNode->subscribe(so_right); this->rosPub_pose_x = this->rosNode->advertise<std_msgs::Float64>("/" + this->model->GetName() + "/robi_pose/x", 1); this->rosPub_pose_y = this->rosNode->advertise<std_msgs::Float64>("/" + this->model->GetName() + "/robi_pose/y", 1); // Spin up the queue helper thread. this->rosQueueThread = std::thread(std::bind(&RobiPlugin::QueueThread, this)); } /// \brief Set the velocity of the Robi /// \param[in] vel_left New target velocity for left wheel /// \param[in] vel_right New target velocity for right wheel public: void SetVelocity(const double &vel_left, const double vel_right) { // Set the joint's target velocity. this->model->GetJointController()->SetVelocityTarget(this->joint_left->GetScopedName(), vel_left); this->model->GetJointController()->SetVelocityTarget(this->joint_right->GetScopedName(), vel_right); } /// \brief Set the velocity of the Robi /// \param[in] vel_left New target velocity for left wheel public: void SetVelocityLeft(const double &vel_left) { // Set the joint's target velocity. this->model->GetJointController()->SetVelocityTarget(this->joint_left->GetScopedName(), vel_left); } /// \brief Set the velocity of the Robi /// \param[in] vel_right New target velocity for right wheel public: void SetVelocityRight(const double &vel_right) { // Set the joint's target velocity. this->model->GetJointController()->SetVelocityTarget(this->joint_right->GetScopedName(), vel_right); } /// \brief Handle incoming message /// \param[in] msg_left Repurpose a vector3 message. This function will /// only use the x component. private: void OnMsgLeft(ConstVector3dPtr &msg_left) { this->SetVelocityLeft(msg_left->x()); } /// \brief Handle incoming message /// \param[in] msg_right Repurpose a vector3 message. This function will /// only use the x component. private: void OnMsgRight(ConstVector3dPtr &msg_right) { this->SetVelocityRight(msg_right->x()); } /// \brief Handle an incoming message from ROS /// \param[in] msg A float value that is used to set the velocity of the left Robi wheel public: void OnRosMsgLeft(const std_msgs::Float32ConstPtr &msg_left) { this->SetVelocityLeft(msg_left->data); } /// \brief Handle an incoming message from ROS /// \param[in] msg A float value that is used to set the velocity of the left Robi wheel public: void OnRosMsgRight(const std_msgs::Float32ConstPtr &msg_right) { this->SetVelocityRight(msg_right->data); } /// \brief ROS helper function that processes messages private: void QueueThread() { static const double timeout = 0.01; while (this->rosNode->ok()) { this->rosQueue_left.callAvailable(ros::WallDuration(timeout)); this->rosQueue_right.callAvailable(ros::WallDuration(timeout)); gazebo::math::Pose pose = this->model->GetWorldPose(); std_msgs::Float64 msg_x; msg_x.data = pose.pos.x; std_msgs::Float64 msg_y; msg_y.data = pose.pos.y; rosPub_pose_x.publish(msg_x); rosPub_pose_y.publish(msg_y); } } private: physics::ModelPtr model; private: physics::JointPtr joint_left; private: common::PID pid_left; private: physics::JointPtr joint_right; private: common::PID pid_right; public: static const std::string left_wheel_name; /// \brief A node used for transport private: transport::NodePtr node; /// \brief A subscriber to a named topic. private: transport::SubscriberPtr sub_left; private: transport::SubscriberPtr sub_right; // ROS variables /// \brief A node use for ROS transport private: std::unique_ptr<ros::NodeHandle> rosNode; /// \brief ROS subscriber private: ros::Subscriber rosSub_left; private: ros::Subscriber rosSub_right; private: ros::Publisher rosPub_pose_x; private: ros::Publisher rosPub_pose_y; /// \brief ROS callbackqueue that helps process messages private: ros::CallbackQueue rosQueue_left; private: ros::CallbackQueue rosQueue_right; /// \brief A thread the keeps running the rosQueue private: std::thread rosQueueThread; }; // Tell Gazebo about this plugin, so that Gazebo can call Load on this plugin. GZ_REGISTER_MODEL_PLUGIN(RobiPlugin) } #endif
38.792952
228
0.698047
[ "model" ]
aa2eb756bee816d8e5099b9205878acac8c8b26d
18,290
cc
C++
chrome/browser/spellchecker/feedback_sender.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
chrome/browser/spellchecker/feedback_sender.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/spellchecker/feedback_sender.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 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. // // The |FeedbackSender| object stores the user feedback to spellcheck // suggestions in a |Feedback| object. // // When spelling service returns spellcheck results, these results first arrive // in |FeedbackSender| to assign hash identifiers for each // misspelling-suggestion pair. If the spelling service identifies the same // misspelling as already displayed to the user, then |FeedbackSender| reuses // the same hash identifiers to avoid duplication. It detects the duplicates by // comparing misspelling offsets in text. Spelling service can return duplicates // because we request spellcheck for whole paragraphs, as context around a // misspelled word is important to the spellcheck algorithm. // // All feedback is initially pending. When a user acts upon a misspelling such // that the misspelling is no longer displayed (red squiggly line goes away), // then the feedback for this misspelling is finalized. All finalized feedback // is erased after being sent to the spelling service. Pending feedback is kept // around for |kSessionHours| hours and then finalized even if user did not act // on the misspellings. // // |FeedbackSender| periodically requests a list of hashes of all remaining // misspellings in renderers. When a renderer responds with a list of hashes, // |FeedbackSender| uses the list to determine which misspellings are no longer // displayed to the user and sends the current state of user feedback to the // spelling service. #include "chrome/browser/spellchecker/feedback_sender.h" #include <algorithm> #include <iterator> #include "base/command_line.h" #include "base/hash.h" #include "base/json/json_writer.h" #include "base/location.h" #include "base/metrics/field_trial.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/spellchecker/word_trimmer.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/spellcheck_common.h" #include "chrome/common/spellcheck_marker.h" #include "chrome/common/spellcheck_messages.h" #include "components/data_use_measurement/core/data_use_user_data.h" #include "content/public/browser/render_process_host.h" #include "crypto/random.h" #include "crypto/secure_hash.h" #include "crypto/sha2.h" #include "google_apis/google_api_keys.h" #include "net/base/load_flags.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_context_getter.h" namespace spellcheck { namespace { const size_t kMaxFeedbackSizeBytes = 10 * 1024 * 1024; // 10 MB // The default URL where feedback data is sent. const char kFeedbackServiceURL[] = "https://www.googleapis.com/rpc"; // The minimum number of seconds between sending batches of feedback. const int kMinIntervalSeconds = 5; // Returns a hash of |session_start|, the current timestamp, and // |suggestion_index|. uint32_t BuildHash(const base::Time& session_start, size_t suggestion_index) { return base::Hash( base::StringPrintf("%" PRId64 "%" PRId64 "%" PRIuS, session_start.ToInternalValue(), base::Time::Now().ToInternalValue(), suggestion_index)); } uint64_t BuildAnonymousHash(const FeedbackSender::RandSalt& r, const base::string16& s) { std::unique_ptr<crypto::SecureHash> hash( crypto::SecureHash::Create(crypto::SecureHash::SHA256)); hash->Update(s.data(), s.size() * sizeof(s[0])); hash->Update(&r, sizeof(r)); uint64_t result; hash->Finish(&result, sizeof(result)); return result; } // Returns a pending feedback data structure for the spellcheck |result| and // |text|. Misspelling BuildFeedback(const SpellCheckResult& result, const base::string16& text) { size_t start = result.location; base::string16 context = TrimWords(&start, start + result.length, text, chrome::spellcheck_common::kContextWordCount); return Misspelling(context, start, result.length, std::vector<base::string16>(1, result.replacement), result.hash); } // Builds suggestion info from |suggestions|. std::unique_ptr<base::ListValue> BuildSuggestionInfo( const std::vector<Misspelling>& misspellings, bool is_first_feedback_batch, const FeedbackSender::RandSalt& salt) { std::unique_ptr<base::ListValue> list(new base::ListValue); for (const auto& raw_misspelling : misspellings) { std::unique_ptr<base::DictionaryValue> misspelling( SerializeMisspelling(raw_misspelling)); misspelling->SetBoolean("isFirstInSession", is_first_feedback_batch); misspelling->SetBoolean("isAutoCorrection", false); // hash(R) fields come from red_underline_extensions.proto // fixed64 user_misspelling_id = ... misspelling->SetString( "userMisspellingId", base::Uint64ToString(BuildAnonymousHash( salt, raw_misspelling.context.substr(raw_misspelling.location, raw_misspelling.length)))); // repeated fixed64 user_suggestion_id = ... std::unique_ptr<base::ListValue> suggestion_list(new base::ListValue()); for (const auto& suggestion : raw_misspelling.suggestions) { suggestion_list->AppendString( base::Uint64ToString(BuildAnonymousHash(salt, suggestion))); } misspelling->Set("userSuggestionId", suggestion_list.release()); list->Append(misspelling.release()); } return list; } // Builds feedback parameters from |suggestion_info|, |language|, and |country|. // Takes ownership of |suggestion_list|. std::unique_ptr<base::DictionaryValue> BuildParams( std::unique_ptr<base::ListValue> suggestion_info, const std::string& language, const std::string& country) { std::unique_ptr<base::DictionaryValue> params(new base::DictionaryValue); params->Set("suggestionInfo", suggestion_info.release()); params->SetString("key", google_apis::GetAPIKey()); params->SetString("language", language); params->SetString("originCountry", country); params->SetString("clientName", "Chrome"); return params; } // Builds feedback data from |params|. Takes ownership of |params|. std::unique_ptr<base::Value> BuildFeedbackValue( std::unique_ptr<base::DictionaryValue> params, const std::string& api_version) { std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue); result->Set("params", params.release()); result->SetString("method", "spelling.feedback"); result->SetString("apiVersion", api_version); return std::move(result); } // Returns true if the misspelling location is within text bounds. bool IsInBounds(int misspelling_location, int misspelling_length, size_t text_length) { return misspelling_location >= 0 && misspelling_length > 0 && static_cast<size_t>(misspelling_location) < text_length && static_cast<size_t>(misspelling_location + misspelling_length) <= text_length; } // Returns the feedback API version. std::string GetApiVersion() { // This guard is temporary. // TODO(rouslan): Remove the guard. http://crbug.com/247726 if (base::FieldTrialList::FindFullName(kFeedbackFieldTrialName) == kFeedbackFieldTrialEnabledGroupName && base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableSpellingFeedbackFieldTrial)) { return "v2-internal"; } return "v2"; } } // namespace FeedbackSender::FeedbackSender(net::URLRequestContextGetter* request_context, const std::string& language, const std::string& country) : request_context_(request_context), api_version_(GetApiVersion()), language_(language), country_(country), misspelling_counter_(0), feedback_(kMaxFeedbackSizeBytes), session_start_(base::Time::Now()), feedback_service_url_(kFeedbackServiceURL) { // The command-line switch is for testing and temporary. // TODO(rouslan): Remove the command-line switch when testing is complete. // http://crbug.com/247726 if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSpellingServiceFeedbackUrl)) { feedback_service_url_ = GURL(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kSpellingServiceFeedbackUrl)); } } FeedbackSender::~FeedbackSender() { } void FeedbackSender::SelectedSuggestion(uint32_t hash, int suggestion_index) { Misspelling* misspelling = feedback_.GetMisspelling(hash); // GetMisspelling() returns null for flushed feedback. Feedback is flushed // when the session expires every |kSessionHours| hours. if (!misspelling) return; misspelling->action.set_type(SpellcheckAction::TYPE_SELECT); misspelling->action.set_index(suggestion_index); misspelling->timestamp = base::Time::Now(); } void FeedbackSender::AddedToDictionary(uint32_t hash) { Misspelling* misspelling = feedback_.GetMisspelling(hash); // GetMisspelling() returns null for flushed feedback. Feedback is flushed // when the session expires every |kSessionHours| hours. if (!misspelling) return; misspelling->action.set_type(SpellcheckAction::TYPE_ADD_TO_DICT); misspelling->timestamp = base::Time::Now(); const std::set<uint32_t>& hashes = feedback_.FindMisspellings(GetMisspelledString(*misspelling)); for (uint32_t hash : hashes) { Misspelling* duplicate_misspelling = feedback_.GetMisspelling(hash); if (!duplicate_misspelling || duplicate_misspelling->action.IsFinal()) continue; duplicate_misspelling->action.set_type(SpellcheckAction::TYPE_ADD_TO_DICT); duplicate_misspelling->timestamp = misspelling->timestamp; } } void FeedbackSender::RecordInDictionary(uint32_t hash) { Misspelling* misspelling = feedback_.GetMisspelling(hash); // GetMisspelling() returns null for flushed feedback. Feedback is flushed // when the session expires every |kSessionHours| hours. if (!misspelling) return; misspelling->action.set_type(SpellcheckAction::TYPE_IN_DICTIONARY); } void FeedbackSender::IgnoredSuggestions(uint32_t hash) { Misspelling* misspelling = feedback_.GetMisspelling(hash); // GetMisspelling() returns null for flushed feedback. Feedback is flushed // when the session expires every |kSessionHours| hours. if (!misspelling) return; misspelling->action.set_type(SpellcheckAction::TYPE_PENDING_IGNORE); misspelling->timestamp = base::Time::Now(); } void FeedbackSender::ManuallyCorrected(uint32_t hash, const base::string16& correction) { Misspelling* misspelling = feedback_.GetMisspelling(hash); // GetMisspelling() returns null for flushed feedback. Feedback is flushed // when the session expires every |kSessionHours| hours. if (!misspelling) return; misspelling->action.set_type(SpellcheckAction::TYPE_MANUALLY_CORRECTED); misspelling->action.set_value(correction); misspelling->timestamp = base::Time::Now(); } void FeedbackSender::OnReceiveDocumentMarkers( int renderer_process_id, const std::vector<uint32_t>& markers) { if ((base::Time::Now() - session_start_).InHours() >= chrome::spellcheck_common::kSessionHours) { FlushFeedback(); return; } if (!feedback_.RendererHasMisspellings(renderer_process_id)) return; feedback_.FinalizeRemovedMisspellings(renderer_process_id, markers); SendFeedback(feedback_.GetMisspellingsInRenderer(renderer_process_id), !renderers_sent_feedback_.count(renderer_process_id)); renderers_sent_feedback_.insert(renderer_process_id); feedback_.EraseFinalizedMisspellings(renderer_process_id); } void FeedbackSender::OnSpellcheckResults( int renderer_process_id, const base::string16& text, const std::vector<SpellCheckMarker>& markers, std::vector<SpellCheckResult>* results) { // Don't collect feedback if not going to send it. if (!timer_.IsRunning()) return; // Generate a map of marker offsets to marker hashes. This map helps to // efficiently lookup feedback data based on the position of the misspelling // in text. typedef std::map<size_t, uint32_t> MarkerMap; MarkerMap marker_map; for (size_t i = 0; i < markers.size(); ++i) marker_map[markers[i].offset] = markers[i].hash; for (auto& result : *results) { if (!IsInBounds(result.location, result.length, text.length())) continue; MarkerMap::const_iterator marker_it = marker_map.find(result.location); if (marker_it != marker_map.end() && feedback_.HasMisspelling(marker_it->second)) { // If the renderer already has a marker for this spellcheck result, then // set the hash of the spellcheck result to be the same as the marker. result.hash = marker_it->second; } else { // If the renderer does not yet have a marker for this spellcheck result, // then generate a new hash for the spellcheck result. result.hash = BuildHash(session_start_, ++misspelling_counter_); } // Save the feedback data for the spellcheck result. feedback_.AddMisspelling(renderer_process_id, BuildFeedback(result, text)); } } void FeedbackSender::OnLanguageCountryChange(const std::string& language, const std::string& country) { FlushFeedback(); language_ = language; country_ = country; } void FeedbackSender::StartFeedbackCollection() { if (timer_.IsRunning()) return; int interval_seconds = chrome::spellcheck_common::kFeedbackIntervalSeconds; // This command-line switch is for testing and temporary. // TODO(rouslan): Remove the command-line switch when testing is complete. // http://crbug.com/247726 if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSpellingServiceFeedbackIntervalSeconds)) { base::StringToInt( base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kSpellingServiceFeedbackIntervalSeconds), &interval_seconds); if (interval_seconds < kMinIntervalSeconds) interval_seconds = kMinIntervalSeconds; static const int kSessionSeconds = chrome::spellcheck_common::kSessionHours * 60 * 60; if (interval_seconds > kSessionSeconds) interval_seconds = kSessionSeconds; } timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(interval_seconds), this, &FeedbackSender::RequestDocumentMarkers); } void FeedbackSender::StopFeedbackCollection() { if (!timer_.IsRunning()) return; FlushFeedback(); timer_.Stop(); } void FeedbackSender::RandBytes(void* p, size_t len) { crypto::RandBytes(p, len); } void FeedbackSender::OnURLFetchComplete(const net::URLFetcher* source) { for (ScopedVector<net::URLFetcher>::iterator sender_it = senders_.begin(); sender_it != senders_.end(); ++sender_it) { if (*sender_it == source) { senders_.erase(sender_it); return; } } delete source; } void FeedbackSender::RequestDocumentMarkers() { // Request document markers from all the renderers that are still alive. std::set<int> alive_renderers; for (content::RenderProcessHost::iterator it( content::RenderProcessHost::AllHostsIterator()); !it.IsAtEnd(); it.Advance()) { alive_renderers.insert(it.GetCurrentValue()->GetID()); it.GetCurrentValue()->Send(new SpellCheckMsg_RequestDocumentMarkers()); } // Asynchronously send out the feedback for all the renderers that are no // longer alive. std::vector<int> known_renderers = feedback_.GetRendersWithMisspellings(); std::sort(known_renderers.begin(), known_renderers.end()); std::vector<int> dead_renderers = base::STLSetDifference<std::vector<int>>(known_renderers, alive_renderers); for (int renderer_process_id : dead_renderers) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FeedbackSender::OnReceiveDocumentMarkers, AsWeakPtr(), renderer_process_id, std::vector<uint32_t>())); } } void FeedbackSender::FlushFeedback() { if (feedback_.Empty()) return; feedback_.FinalizeAllMisspellings(); SendFeedback(feedback_.GetAllMisspellings(), renderers_sent_feedback_.empty()); feedback_.Clear(); renderers_sent_feedback_.clear(); session_start_ = base::Time::Now(); timer_.Reset(); } void FeedbackSender::SendFeedback(const std::vector<Misspelling>& feedback_data, bool is_first_feedback_batch) { if (base::Time::Now() - last_salt_update_ > base::TimeDelta::FromHours(24)) { RandBytes(&salt_, sizeof(salt_)); last_salt_update_ = base::Time::Now(); } std::unique_ptr<base::Value> feedback_value(BuildFeedbackValue( BuildParams( BuildSuggestionInfo(feedback_data, is_first_feedback_batch, salt_), language_, country_), api_version_)); std::string feedback; base::JSONWriter::Write(*feedback_value, &feedback); // The tests use this identifier to mock the URL fetcher. static const int kUrlFetcherId = 0; net::URLFetcher* sender = net::URLFetcher::Create(kUrlFetcherId, feedback_service_url_, net::URLFetcher::POST, this).release(); data_use_measurement::DataUseUserData::AttachToFetcher( sender, data_use_measurement::DataUseUserData::SPELL_CHECKER); sender->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); sender->SetUploadData("application/json", feedback); senders_.push_back(sender); // Request context is nullptr in testing. if (request_context_.get()) { sender->SetRequestContext(request_context_.get()); sender->Start(); } } } // namespace spellcheck
39.418103
80
0.712411
[ "object", "vector" ]
aa2fb5fec0d98316031bfaef86ac380ae63ea737
7,916
cpp
C++
ShapeOperations/CsvFileUtils.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
ShapeOperations/CsvFileUtils.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
ShapeOperations/CsvFileUtils.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
/** * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved * * This file is part of GeoDa. * * GeoDa is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GeoDa is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <fstream> #include <set> #include <sstream> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <wx/stopwatch.h> #include "../logger.h" #include "CsvFileUtils.h" /** This method makes a row in the Excel CSV format. The following rules are followed: 1. If the string contanis no , or " chars, then leave as is 2. Otherwise, wrap " chars around the whole string and escape out " chars with a second ". Eg. 6" -> "6""" or 1,2,3 -> "1,2,3" 3. Each string chunk is seperated by , chars. */ void Gda::StringsToCsvRecord(const std::vector<std::string>& strings, std::string& record) { using namespace std; vector<string> escaped_strs(strings.size()); for (int i=0, iend=strings.size(); i<iend; i++) { string item(strings[i]); if (item.find('\"') != string::npos || item.find(',') != string::npos) { ostringstream ss; for (int j=0, jend=item.size(); j<jend; j++) { if (item[j] == '"') { ss << "\"\""; } else { ss << item[j]; } } escaped_strs[i] = "\"" + ss.str() + "\""; } else { escaped_strs[i] = item; } } ostringstream ss; for (int i=0, iend=escaped_strs.size(); i<iend; i++) { ss << escaped_strs[i]; if (i < iend-1) ss << ","; } record = ss.str(); } std::istream& Gda::safeGetline(std::istream& is, std::string& t) { t.clear(); // The characters in the stream are read one-by-one using a std::streambuf. // That is faster than reading them one-by-one using the std::istream. // Code that uses streambuf this way must be guarded by a sentry object. // The sentry object performs various tasks, // such as thread synchronization and updating the stream state. std::istream::sentry se(is, true); std::streambuf* sb = is.rdbuf(); for(;;) { int c = sb->sbumpc(); switch (c) { case '\r': c = sb->sgetc(); if(c == '\n') sb->sbumpc(); return is; case '\n': case EOF: return is; default: t += (char)c; } } } bool Gda::GetCsvStats(const std::string& csv_fname, int& num_rows, int& num_cols, std::vector<std::string>& first_row, wxString& err_msg) { using namespace std; ifstream file(csv_fname.c_str()); if (!file.is_open()) { err_msg << "Unable to open CSV file."; return false; } typedef Gda::csv_record_grammar<string::const_iterator> csv_rec_gram; csv_rec_gram csv_record; // CSV grammar instance using boost::spirit::ascii::space; string line; num_rows = 0; num_cols = 0; first_row.clear(); bool done = false; bool blank_line_seen_once = false; // Parse the first line Gda::safeGetline(file, line); if (line.empty()) { err_msg << "First line of CSV is empty"; file.close(); return false; } else { string::const_iterator iter = line.begin(); string::const_iterator end = line.end(); bool r = phrase_parse(iter, end, csv_record, space, first_row); if (!r || iter != end) { err_msg << "Problem parsing first line of CSV."; file.close(); return false; } num_cols = first_row.size(); num_rows++; } // count remaining number of non-blank lines in file while ( !file.eof() && file.good() && !done ) { int pos = file.tellg(); Gda::safeGetline(file, line); if (!line.empty()) num_rows++; if (pos == file.tellg()) done = true; } file.close(); return true; } /** If first_row_field_names is true, then first row of data will be ignored */ bool Gda::FillStringTableFromCsv(const std::string& csv_fname, std_str_array_type& string_table, bool first_row_field_names, wxString& err_msg) { using namespace std; wxStopWatch sw; int num_rows = 0; int num_cols = 0; std::vector<std::string> first_row; wxString stats_err_msg; bool success = Gda::GetCsvStats(csv_fname, num_rows, num_cols, first_row, stats_err_msg); if (!success) { err_msg = stats_err_msg; return false; } if (first_row_field_names) num_rows--; string_table.resize(boost::extents[num_rows][num_cols]); ifstream file(csv_fname.c_str()); if (!file.is_open()) { cout << "Error: unable to open CSV file." << endl; return false; } vector<string> v; typedef Gda::csv_record_grammar<string::const_iterator> csv_rec_gram; csv_rec_gram csv_record; // CSV grammar instance using boost::spirit::ascii::space; int row = 0; string line; // skip first row if these are field names if (first_row_field_names) Gda::safeGetline(file, line); bool done = false; while ( !file.eof() && file.good() && !done && row < num_rows ) { int pos = file.tellg(); Gda::safeGetline(file, line); if (!line.empty()) { v.clear(); string::const_iterator iter = line.begin(); string::const_iterator end = line.end(); bool r = phrase_parse(iter, end, csv_record, space, v); if (!r || iter != end) { int line_no = row+1; if (first_row_field_names) line_no++; err_msg << "Problem parsing CSV file line " << line_no << "."; file.close(); return false; } if (v.size() != num_cols) { err_msg << "First line of CSV file line has " << num_cols; err_msg << " fields, but line " << row << " has "; err_msg << v.size() << " fields. This is not valid in "; err_msg << "a CSV file."; file.close(); return false; } for (int col=0; col<num_cols; col++) { string_table[row][col] = v[col]; } row++; } if (pos == file.tellg()) done = true; } file.close(); if (row != num_rows) { err_msg << "CSV file was specified as having " << num_rows; err_msg << " records, but " << row << " records were parsed."; return false; } return true; } bool Gda::ConvertColToLongs(const std_str_array_type& string_table, int col, std::vector<wxInt64>& v, std::vector<bool>& undef, int& failed_index) { using namespace std; using boost::lexical_cast; using boost::bad_lexical_cast; int num_rows = string_table.shape()[0]; int num_cols = string_table.shape()[1]; if (col < 0 || col >= num_cols) return false; v.resize(num_rows); undef.resize(num_rows); for (int i=0; i<num_rows; i++) { string s(string_table[i][col]); boost::trim(s); undef[i] = true; if (!s.empty()) { try { v[i] = lexical_cast<wxInt64>(s); } catch (bad_lexical_cast &) { failed_index = i; return false; } undef[i] = false; } else { v[i] = 0; } } return true; } bool Gda::ConvertColToDoubles(const std_str_array_type& string_table, int col, std::vector<double>& v, std::vector<bool>& undef, int& failed_index) { using namespace std; using boost::lexical_cast; using boost::bad_lexical_cast; int num_rows = string_table.shape()[0]; int num_cols = string_table.shape()[1]; if (col < 0 || col >= num_cols) return false; v.resize(num_rows); undef.resize(num_rows); for (int i=0; i<num_rows; i++) { string s(string_table[i][col]); boost::trim(s); undef[i] = s.empty(); if (!s.empty()) { try { v[i] = lexical_cast<double>(s); } catch (bad_lexical_cast &) { failed_index = i; return false; } } else { v[i] = 0; } } return true; }
26.211921
79
0.633527
[ "object", "shape", "vector" ]
a8f713c3bdb0b66fb865901bc0b7aae1011bb1dc
5,328
cpp
C++
src/text.cpp
Tearnote/Minote
35f63fecc01cf9199db1098256277465e1d41d1e
[ "MIT" ]
8
2021-01-18T12:06:21.000Z
2022-02-13T17:12:56.000Z
src/text.cpp
Tearnote/Minote
35f63fecc01cf9199db1098256277465e1d41d1e
[ "MIT" ]
null
null
null
src/text.cpp
Tearnote/Minote
35f63fecc01cf9199db1098256277465e1d41d1e
[ "MIT" ]
null
null
null
/** * Implementation of text.h * @file */ #include "text.hpp" #include <stdarg.h> #include <stdio.h> #include "sys/opengl/vertexarray.hpp" #include "sys/opengl/texture.hpp" #include "sys/opengl/shader.hpp" #include "sys/opengl/buffer.hpp" #include "sys/opengl/draw.hpp" #include "base/array.hpp" #include "base/util.hpp" #include "store/fonts.hpp" #include "base/log.hpp" using namespace minote; /// Single glyph instance for the MSDF shader struct MsdfGlyph { vec2 position; ///< Glyph offset in the string (lower left) vec2 size; ///< Size of the glyph vec4 texBounds; ///< AABB of the atlas UVs color4 color; ///< Glyph color int transformIndex; ///< Index of the string transform from the "transforms" buffer texture }; static constexpr size_t MaxGlyphs{1024}; static constexpr size_t MaxStrings{64}; static VertexArray msdfVao = {}; static VertexBuffer<MsdfGlyph> msdfGlyphsVbo; static svector<MsdfGlyph, MaxGlyphs> msdfGlyphs; static BufferTexture<mat4> msdfTransformsTex = {}; static svector<mat4, MaxStrings> msdfTransforms; static Font* msdfFont = nullptr; static Draw<Shaders::Msdf> msdf = { .mode = DrawMode::TriangleStrip, .triangles = 2, .params = { .blending = true } }; static bool initialized = false; static void textQueueV(Font& font, float size, vec3 pos, vec3 dir, vec3 up, color4 color, const char* fmt, va_list args) { hb_buffer_t* text{nullptr}; do { // Costruct the formatted string va_list argsCopy; va_copy(argsCopy, args); size_t stringSize = vsnprintf(nullptr, 0, fmt, args) + 1; char string[stringSize]; vsnprintf(string, stringSize, fmt, argsCopy); // Pass string to HarfBuzz and shape it text = hb_buffer_create(); hb_buffer_add_utf8(text, string, -1, 0, -1); hb_buffer_set_direction(text, HB_DIRECTION_LTR); hb_buffer_set_script(text, HB_SCRIPT_LATIN); hb_buffer_set_language(text, hb_language_from_string("en", -1)); hb_shape(font.hbFont, text, nullptr, 0); // Construct the string transform vec3 eye = vec3(pos.x, pos.y, pos.z) - vec3(dir.x, dir.y, dir.z); mat4 lookat = lookAt(vec3(pos.x, pos.y, pos.z), eye, vec3(up.x, up.y, up.z)); mat4 inverted = inverse(lookat); msdfTransforms.push_back(scale(inverted, {size, size, size})); // Iterate over glyphs unsigned glyphCount = 0; hb_glyph_info_t* glyphInfo = hb_buffer_get_glyph_infos(text, &glyphCount); hb_glyph_position_t* glyphPos = hb_buffer_get_glyph_positions(text, &glyphCount); vec2 cursor {0}; for (size_t i = 0; i < glyphCount; i += 1) { auto& glyph = msdfGlyphs.emplace_back(); // Calculate glyph information size_t id = glyphInfo[i].codepoint; Font::Glyph* atlasChar = &font.metrics[id]; vec2 offset = { glyphPos[i].x_offset / 1024.0f, glyphPos[i].y_offset / 1024.0f }; float xAdvance = glyphPos[i].x_advance / 1024.0f; float yAdvance = glyphPos[i].y_advance / 1024.0f; // Fill in draw data glyph.position = cursor + offset + atlasChar->glyph.pos; glyph.size = atlasChar->glyph.size; glyph.texBounds.x = atlasChar->msdf.pos.x / (float)font.atlas.size.x; glyph.texBounds.y = atlasChar->msdf.pos.y / (float)font.atlas.size.y; glyph.texBounds.z = atlasChar->msdf.size.x / (float)font.atlas.size.x; glyph.texBounds.w = atlasChar->msdf.size.y / (float)font.atlas.size.y; glyph.color = color; glyph.transformIndex = msdfTransforms.size() - 1; // Advance position cursor.x += xAdvance; cursor.y += yAdvance; } } while(false); hb_buffer_destroy(text); msdfFont = &font; } void textInit(void) { if (initialized) return; msdfGlyphsVbo.create("msdfGlyphVbo", true); msdfVao.create("msdfVao"); msdfTransformsTex.create("msdfTransformTex", true); msdfVao.setAttribute(0, msdfGlyphsVbo, &MsdfGlyph::position, true); msdfVao.setAttribute(1, msdfGlyphsVbo, &MsdfGlyph::size, true); msdfVao.setAttribute(2, msdfGlyphsVbo, &MsdfGlyph::texBounds, true); msdfVao.setAttribute(3, msdfGlyphsVbo, &MsdfGlyph::color, true); msdfVao.setAttribute(4, msdfGlyphsVbo, &MsdfGlyph::transformIndex, true); initialized = true; } void textCleanup(void) { if (!initialized) return; msdfTransformsTex.destroy(); msdfGlyphsVbo.destroy(); msdfVao.destroy(); initialized = false; } void textQueue(Font& font, float size, vec3 pos, color4 color, const char* fmt, ...) { ASSERT(initialized); ASSERT(fmt); va_list args; va_start(args, fmt); textQueueV(font, size, pos, (vec3){1.0f, 0.0f, 0.0f}, (vec3){0.0f, 1.0f, 0.0f}, color, fmt, args); va_end(args); } void textQueueDir(Font& font, float size, vec3 pos, vec3 dir, vec3 up, color4 color, const char* fmt, ...) { ASSERT(initialized); ASSERT(fmt); va_list args; va_start(args, fmt); textQueueV(font, size, pos, dir, up, color, fmt, args); va_end(args); } void textDraw(Engine& engine) { ASSERT(initialized); if (!msdfGlyphs.size()) return; msdfGlyphsVbo.upload(msdfGlyphs); msdfTransformsTex.upload(msdfTransforms); msdf.shader = &engine.shaders.msdf; msdf.vertexarray = &msdfVao; msdf.framebuffer = engine.frame.fb; msdf.instances = msdfGlyphs.size(); msdf.shader->atlas = msdfFont->atlas; msdf.shader->transforms = msdfTransformsTex; msdf.shader->projection = engine.scene.projection; msdf.shader->view = engine.scene.view; msdf.draw(); msdfGlyphs.clear(); msdfTransforms.clear(); }
27.183673
92
0.710961
[ "shape", "transform" ]
a8fb6091bd796d0b6b0babc3bb2f3853106c5761
4,386
cpp
C++
extern/eltopo/eltopo3d/broadphase_blenderbvh.cpp
wycivil08/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
30
2015-01-29T14:06:05.000Z
2022-01-10T07:47:29.000Z
extern/eltopo/eltopo3d/broadphase_blenderbvh.cpp
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
1
2017-02-20T20:57:48.000Z
2018-12-19T23:44:38.000Z
extern/eltopo/eltopo3d/broadphase_blenderbvh.cpp
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
15
2015-04-23T02:38:36.000Z
2021-03-01T20:09:39.000Z
#if 0 // --------------------------------------------------------- // // broadphase_blenderbvh.cpp // Joseph Eagar 2010 // // Broad phase collision detection culling using blender's kdop bvh. // // --------------------------------------------------------- // --------------------------------------------------------- // Includes // --------------------------------------------------------- #include <broadphasegrid.h> #include <dynamicsurface.h> // --------------------------------------------------------- // Global externs // --------------------------------------------------------- // --------------------------------------------------------- // Local constants, typedefs, macros // --------------------------------------------------------- // --------------------------------------------------------- // Static function definitions // --------------------------------------------------------- // --------------------------------------------------------- // Member function definitions // --------------------------------------------------------- // -------------------------------------------------------- /// /// Rebuild acceleration grids according to the given triangle mesh /// // -------------------------------------------------------- static void build_bvh_tree void BroadPhaseGrid::update_broad_phase_static( const DynamicSurface& surface ) { double grid_scale = surface.get_average_edge_length(); { unsigned int num_vertices = surface.m_positions.size(); std::vector<Vec3d> vertex_xmins(num_vertices), vertex_xmaxs(num_vertices); for(unsigned int i = 0; i < num_vertices; i++) { surface.vertex_static_bounds(i, vertex_xmins[i], vertex_xmaxs[i]); } build_acceleration_grid( m_vertex_grid, vertex_xmins, vertex_xmaxs, grid_scale, surface.m_proximity_epsilon ); } { unsigned int num_edges = surface.m_mesh.m_edges.size(); std::vector<Vec3d> edge_xmins(num_edges), edge_xmaxs(num_edges); for(unsigned int i = 0; i < num_edges; i++) { surface.edge_static_bounds(i, edge_xmins[i], edge_xmaxs[i]); } if (num_edges) build_acceleration_grid( m_edge_grid, edge_xmins, edge_xmaxs, grid_scale, surface.m_proximity_epsilon ); } { unsigned int num_triangles = surface.m_mesh.m_tris.size(); std::vector<Vec3d> tri_xmins(num_triangles), tri_xmaxs(num_triangles); for(unsigned int i = 0; i < num_triangles; i++) { surface.triangle_static_bounds(i, tri_xmins[i], tri_xmaxs[i]); } if (num_triangles) build_acceleration_grid( m_triangle_grid, tri_xmins, tri_xmaxs, grid_scale, surface.m_proximity_epsilon ); } } // -------------------------------------------------------- /// /// Rebuild acceleration grids according to the given triangle mesh /// // -------------------------------------------------------- void BroadPhaseGrid::update_broad_phase_continuous( const DynamicSurface& surface ) { double grid_scale = surface.get_average_edge_length(); { unsigned int num_vertices = surface.m_positions.size(); std::vector<Vec3d> vertex_xmins(num_vertices), vertex_xmaxs(num_vertices); for(unsigned int i = 0; i < num_vertices; i++) { surface.vertex_continuous_bounds(i, vertex_xmins[i], vertex_xmaxs[i]); } build_acceleration_grid( m_vertex_grid, vertex_xmins, vertex_xmaxs, grid_scale, surface.m_proximity_epsilon ); } { unsigned int num_edges = surface.m_mesh.m_edges.size(); std::vector<Vec3d> edge_xmins(num_edges), edge_xmaxs(num_edges); for(unsigned int i = 0; i < num_edges; i++) { surface.edge_continuous_bounds(i, edge_xmins[i], edge_xmaxs[i]); } if (num_edges) build_acceleration_grid( m_edge_grid, edge_xmins, edge_xmaxs, grid_scale, surface.m_proximity_epsilon ); } { unsigned int num_triangles = surface.m_mesh.m_tris.size(); std::vector<Vec3d> tri_xmins(num_triangles), tri_xmaxs(num_triangles); for(unsigned int i = 0; i < num_triangles; i++) { surface.triangle_continuous_bounds(i, tri_xmins[i], tri_xmaxs[i]); } if (num_triangles) build_acceleration_grid( m_triangle_grid, tri_xmins, tri_xmaxs, grid_scale, surface.m_proximity_epsilon ); } } #endif
34
116
0.531008
[ "mesh", "vector" ]
a8fc4c03c8b86c9a720ced447fc3dc4747f3a4e7
1,586
tcc
C++
raftinc/container.tcc
mr-j0nes/RaftLib
19b2b5401365ba13788044bfbcca0820f48b650a
[ "Apache-2.0" ]
2
2019-08-27T11:08:18.000Z
2021-09-06T12:05:23.000Z
raftinc/container.tcc
Myicefrog/RaftLib
5ff105293bc851ed73bdfd8966b15d0cadb45eb0
[ "Apache-2.0" ]
null
null
null
raftinc/container.tcc
Myicefrog/RaftLib
5ff105293bc851ed73bdfd8966b15d0cadb45eb0
[ "Apache-2.0" ]
1
2021-07-31T15:07:06.000Z
2021-07-31T15:07:06.000Z
/** * container.tcc - * @author: Jonathan Beard * @version: Sat Jan 24 14:53:50 2015 * * Copyright 2015 Jonathan Beard * * 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 _CONTAINER_TCC_ #define _CONTAINER_TCC_ 1 #include <vector> #include <mutex> #include <cassert> template < class T > container { public: container() = default; virtual ~conainer() = default; void add( T * const ptr ) { assert( ptr != nullptr ); mutex.lock(); list.push_back( ptr ); mutex.unlock(); } template < std::function< bool ( T* ) > FUNCTION > void remove() { mutex.lock(); for( auto it( list.begin() ); it != list.end(); ++it ) { if( FUNCTION( (*it) ) ) { /** reset list to next item while removing, keep going **/ it = list.remove( it ); } } mutex.unlock(); return; } virtual ItemIterator begin(); virtual ItemIterator end(); private: std::vector< T* > list; std::mutex mutex; }; #endif /* END _CONTAINER_TCC_ */
24.030303
75
0.619168
[ "vector" ]
a8ffa321d14af9ab05d403278c770cc22cd294ae
1,981
hpp
C++
src/ngraph/descriptor/layout/dense_tensor_view_layout.hpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
src/ngraph/descriptor/layout/dense_tensor_view_layout.hpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
src/ngraph/descriptor/layout/dense_tensor_view_layout.hpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include <cstddef> #include <vector> #include "ngraph/descriptor/layout/tensor_view_layout.hpp" namespace ngraph { namespace descriptor { class TensorView; namespace layout { /// \brief The standard strided layout, used for row-major and column-major, their permutations and slices. /// /// The linearized offset of an index I is dot(I, strides) + offset. class DenseTensorViewLayout : public TensorViewLayout { public: ~DenseTensorViewLayout() override {} DenseTensorViewLayout(const TensorView& tensor_view); virtual size_t get_size() override { return m_size; } size_t get_offset() const { return m_offset; } virtual size_t get_index_offset(const std::vector<size_t>& indices) override; const Strides& get_strides() const override { return m_strides; } virtual bool operator==(const TensorViewLayout& other) const override; protected: Strides m_strides; size_t m_offset{0}; size_t m_size; }; } } }
35.375
119
0.587077
[ "vector" ]
d1015120b6ca8f61701fef76a48b74af15a990fa
4,318
cxx
C++
Modules/Loadable/DoubleArrays/qSlicerDoubleArraysModule.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Modules/Loadable/DoubleArrays/qSlicerDoubleArraysModule.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Modules/Loadable/DoubleArrays/qSlicerDoubleArraysModule.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
/*============================================================================== Program: 3D Slicer Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. ==============================================================================*/ // Qt includes #include <QtPlugin> // Slice includes #include <qSlicerCoreApplication.h> #include <qSlicerCoreIOManager.h> #include <qSlicerNodeWriter.h> // DoubleArrays Logic includes #include <vtkSlicerDoubleArraysLogic.h> // DoubleArrays includes #include "qSlicerDoubleArraysModule.h" #include "qSlicerDoubleArraysReader.h" //----------------------------------------------------------------------------- Q_EXPORT_PLUGIN2(qSlicerDoubleArraysModule, qSlicerDoubleArraysModule); //----------------------------------------------------------------------------- /// \ingroup Slicer_QtModules_ExtensionTemplate class qSlicerDoubleArraysModulePrivate { public: qSlicerDoubleArraysModulePrivate(); }; //----------------------------------------------------------------------------- // qSlicerDoubleArraysModulePrivate methods //----------------------------------------------------------------------------- qSlicerDoubleArraysModulePrivate::qSlicerDoubleArraysModulePrivate() { } //----------------------------------------------------------------------------- // qSlicerDoubleArraysModule methods //----------------------------------------------------------------------------- qSlicerDoubleArraysModule::qSlicerDoubleArraysModule(QObject* _parent) : Superclass(_parent) , d_ptr(new qSlicerDoubleArraysModulePrivate) { } //----------------------------------------------------------------------------- qSlicerDoubleArraysModule::~qSlicerDoubleArraysModule() { } //----------------------------------------------------------------------------- QString qSlicerDoubleArraysModule::helpText()const { return "This module provides support for double array nodes"; } //----------------------------------------------------------------------------- QString qSlicerDoubleArraysModule::acknowledgementText()const { return "This work was was partially funded by NIH grant 3P41RR013218-12S1"; } //----------------------------------------------------------------------------- QStringList qSlicerDoubleArraysModule::contributors()const { QStringList moduleContributors; moduleContributors << QString("Julien Finet (Kitware)"); return moduleContributors; } //----------------------------------------------------------------------------- QStringList qSlicerDoubleArraysModule::categories() const { return QStringList() << "Developer Tools"; } //----------------------------------------------------------------------------- QStringList qSlicerDoubleArraysModule::dependencies() const { return QStringList(); } //----------------------------------------------------------------------------- void qSlicerDoubleArraysModule::setup() { this->Superclass::setup(); vtkSlicerDoubleArraysLogic* doubleArraysLogic = vtkSlicerDoubleArraysLogic::SafeDownCast(this->logic()); qSlicerCoreIOManager* ioManager = qSlicerCoreApplication::application()->coreIOManager(); ioManager->registerIO(new qSlicerDoubleArraysReader(doubleArraysLogic,this)); ioManager->registerIO(new qSlicerNodeWriter( "Double Arrays", QString("DoubleArrayFile"), QStringList() << "vtkMRMLDoubleArrayNode", true, this)); } //----------------------------------------------------------------------------- bool qSlicerDoubleArraysModule::isHidden() const { return true; } //----------------------------------------------------------------------------- qSlicerAbstractModuleRepresentation * qSlicerDoubleArraysModule::createWidgetRepresentation() { return 0; } //----------------------------------------------------------------------------- vtkMRMLAbstractLogic* qSlicerDoubleArraysModule::createLogic() { return vtkSlicerDoubleArraysLogic::New(); }
32.961832
93
0.531728
[ "3d" ]
d10669901c15eb629a4759e7868d184c519cf532
9,220
cpp
C++
src/GLUL/GUI/Text.cpp
RippeR37/GLUL
2e5cd72192d039d281c5df09a816901f6fea28f9
[ "MIT" ]
43
2015-09-15T18:07:23.000Z
2021-03-24T02:19:39.000Z
src/GLUL/GUI/Text.cpp
RippeR37/Utility-Library
2e5cd72192d039d281c5df09a816901f6fea28f9
[ "MIT" ]
46
2015-01-09T18:03:40.000Z
2015-09-09T22:05:39.000Z
src/GLUL/GUI/Text.cpp
RippeR37/GLUL
2e5cd72192d039d281c5df09a816901f6fea28f9
[ "MIT" ]
4
2017-01-27T21:35:44.000Z
2021-01-09T17:04:32.000Z
#include <GLUL/GL++/Context.h> #include <GLUL/GUI/Text.h> #include <GLUL/Logger.h> #include <cctype> namespace GLUL { namespace GUI { Text::Text(Container& parent) : Text(&parent) { } Text::Text(Container* const parent) : Component(parent) { setFont(nullptr); setColor(glm::vec4(1.0f)); setScale(1.0f); _glInitialized = false; } Text::~Text() { } const Text& Text::render() const { if(isVisible() && getAlpha() > 0.0f) { if(_font == nullptr) { GLUL::Log::Stream("_Library").logError("[GUI] Attempt to render render text '" + _text + "' without font"); return *this; } if(!isValid()) validate(); // Render using font if(_text != "") { _font->getTexture().bind(); getProgram().use(); getProgram()["glyphAtlas"].setSampler(0); getProgram()["fontColor"].setVec(getColor()); _vao.bind(); _vao.drawArrays(); _vao.unbind(); getProgram().unbind(); _font->getTexture().unbind(); } } return *this; } Text& Text::update(double deltaTime) { if(!isValid()) validate(); (void) deltaTime; // Nothing to update here return *this; } const Text& Text::validate() const { Text* thisConstless = const_cast<Text*>(this); if(_text != "" && _font != nullptr) { // (Re)build VBO GL::VertexBuffer::Data vertexData; std::vector<glm::vec4> vertices = getVertices(); vertexData.data = vertices.data(); vertexData.size = vertices.size() * sizeof(glm::vec4); vertexData.pointers.push_back(GL::VertexAttrib(0, 4, GL_FLOAT, 0, nullptr)); _vbo.bind(); thisConstless->_vbo.setUsage(GL::VertexBuffer::Usage::DynamicDraw); thisConstless->_vbo.setData(vertexData); _vbo.unbind(); // Set vertices draw count thisConstless->_vao.setDrawCount(vertices.size()); // Initialize VAO if(_glInitialized == false) { thisConstless->_vao.setDrawTarget(GL::VertexArray::DrawTarget::Triangles); _vao.bind(); thisConstless->_vao.attachVBO(&_vbo); thisConstless->_vao.setAttribPointers(); _vao.unbind(); thisConstless->_glInitialized = true; } } thisConstless->setValid(); return *this; } const Font* Text::getFont() const { return _font; } const std::string& Text::getText() const { return _text; } const glm::vec4& Text::getColor() const { return _color; } float Text::getAlpha() const { return _color.a; } float Text::getScale() const { return _scale; } unsigned int Text::getFontHeight() const { unsigned int result = static_cast<unsigned int>((getFont() ? getFont()->getHeight() : 0) * getScale()); return result; } Text& Text::setEnabled(bool flag) { _isEnabled = flag; return *this; } Text& Text::setFocused(bool flag) { _isFocused = flag; return *this; } Text& Text::setVisible(bool flag) { if(_isVisible != flag) { _isVisible = flag; setInvalid(); } return *this; } Text& Text::setFont(const Font& font) { return setFont(&font); } Text& Text::setFont(const Font* font) { _font = font; validate(); return *this; } Text& Text::setText(const std::string& text) { _text = text; validate(); return *this; } Text& Text::setSize(const glm::vec2& size) { // [DEPRECATED] - size.x will not be used GLUL::Log::Stream("_Library").logWarning( "Use of deprecated functionality Text::setSize(const glm::vec2&) for text '" + getText() + "' - width will not be used" ); return setSize(static_cast<unsigned int>(size.y)); } Text& Text::setSize(unsigned int newHeight) { float oldFontHeight = static_cast<float>(getFont() ? getFont()->getHeight() : 1.0f); float newFontHeight = static_cast<float>(newHeight); return setScale(newFontHeight / oldFontHeight); } Text& Text::setScale(float scale) { _scale = scale; validate(); return *this; } Text& Text::setColor(const glm::vec3& color) { return setColor(glm::vec4(color, getAlpha())); } Text& Text::setColor(const glm::vec4& color) { _color = color; return *this; } Text& Text::setAlpha(float alpha) { return setColor(glm::vec4(getColor().r, getColor().g, getColor().b, alpha)); } Text& Text::setPosition(const glm::vec2& position) { Component::setPosition(position); return *this; } GL::Program& Text::getProgram() { static GL::Program program( GL::Shader("assets/shaders/GLUL/GUI/Text.vp", GL::Shader::Type::VertexShader), GL::Shader("assets/shaders/GLUL/GUI/Text.fp", GL::Shader::Type::FragmentShader) ); return program; } std::vector<glm::vec4> Text::getVertices() const { std::vector<glm::vec4> result; glm::vec2 posStart, posEnd; glm::vec2 texStart, texEnd; glm::vec2 baseLine; glm::vec2 posCursor; glm::vec2 bbTopRight; glm::vec2 bbBottomLeft; char character; bool isDrawn; baseLine = glm::vec2( getScreenPosition().x, GL::Context::Current->getViewportSize().y - getScreenPosition().y - getScale() * getFont()->getAscender() ); posCursor = bbTopRight = bbBottomLeft = baseLine; for(unsigned int i = 0; i < _text.size(); ++i) { character = getText()[i]; isDrawn = (std::isgraph(character) > 0); // Calculations - position posStart = posCursor + getScale() * glm::vec2( getFont()->getMetric(character).glyphPos.x, getFont()->getMetric(character).glyphPos.y - getFont()->getMetric(character).size.y ); posEnd = posStart + getScale() * getFont()->getMetric(character).size; // Bounding-rectangle update if(posStart.x < bbBottomLeft.x) bbBottomLeft.x = posStart.x; if(posStart.y < bbBottomLeft.y) bbBottomLeft.y = posStart.y; if(posEnd.x > bbTopRight.x) bbTopRight.x = posEnd.x; if(posEnd.y > bbTopRight.y) bbTopRight.y = posEnd.y; if(isDrawn) { // Calcuations - texture texStart = getFont()->getMetric(character).texPosStart; texEnd = getFont()->getMetric(character).texPosEnd; // Vertices if(getFont()->getMetric(character).size.x > 0 && getFont()->getMetric(character).size.y > 0) { result.emplace_back(posStart.x, posStart.y, texStart.x, texStart.y); result.emplace_back(posEnd.x, posStart.y, texEnd.x, texStart.y); result.emplace_back(posStart.x, posEnd.y, texStart.x, texEnd.y); result.emplace_back(posStart.x, posEnd.y, texStart.x, texEnd.y); result.emplace_back(posEnd.x, posStart.y, texEnd.x, texStart.y); result.emplace_back(posEnd.x, posEnd.y, texEnd.x, texEnd.y); } } switch(character) { case '\n': posCursor = glm::vec2(baseLine.x, posCursor.y - getFont()->getLineHeight()); break; case '\t': posCursor += getScale() * getFont()->getMetric(' ').advance * 4.0f; break; default: posCursor += getScale() * getFont()->getMetric(character).advance; break; } } const_cast<Text*>(this)->_size = bbTopRight - bbBottomLeft; return result; } } }
30.631229
127
0.482213
[ "render", "vector" ]
d107752577e69b7076173ed2468300d107377d40
5,888
cpp
C++
incubus/objects/gameplayobjectgenerator.cpp
oldnick85/incubus
128b18626b94289c0b2d5c01b56fe586cfef9519
[ "MIT" ]
null
null
null
incubus/objects/gameplayobjectgenerator.cpp
oldnick85/incubus
128b18626b94289c0b2d5c01b56fe586cfef9519
[ "MIT" ]
null
null
null
incubus/objects/gameplayobjectgenerator.cpp
oldnick85/incubus
128b18626b94289c0b2d5c01b56fe586cfef9519
[ "MIT" ]
null
null
null
#include "gameplayobjectgenerator.h" CGameplayObjectGenerator::CGameplayObjectGenerator(const sAllCores &cores, const IDispatcherPtr disp, ILoggerPtr log, sDispatcherMsgStatistic *msg_stat) : CLogged (log) , m_cores(cores) , m_disp(disp) , m_msg_stat(msg_stat) { } CObjectGameplayPtr CGameplayObjectGenerator::MakeObject(const sObjSpec &spec) { auto obj = CObjectGameplayPtr(new CObjectGameplay(Log(), m_disp, spec, m_msg_stat)); obj->SetCores(m_cores); sObjGpParam gp_param; sPhysicsParam ph_param; sShowParam sh_param; switch (spec.Class()) { case ocMob: MakeParam_Mob(gp_param, sh_param, ph_param); break; case ocConstruction: MakeParam_Construction(gp_param, sh_param, ph_param); break; case ocProjectile: MakeParam_Projectile(gp_param, sh_param, ph_param); break; case ocLoot: MakeParam_Loot(gp_param, sh_param, ph_param); break; default: assert(false); break; } switch (spec.Spec()) { case opHuman: MakeHumanParam(gp_param, sh_param, ph_param); break; case opZombie: MakeZombieParam(gp_param, sh_param, ph_param); break; case opWall: MakeWallParam(gp_param, sh_param, ph_param); break; case opBullet: MakeParam_Bullet(gp_param, sh_param, ph_param); break; case opPistol: MakeParam_Pistol(gp_param, sh_param, ph_param); break; default: assert(false); break; } obj->m_param = gp_param; obj->m_ph_param = ph_param; obj->m_sh_param = sh_param; return obj; } void CGameplayObjectGenerator::MakeParam_Mob(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); if (not ph_param.kinematic.position.placed) { ph_param.kinematic.position.x = (static_cast<double>(rand() % 1000) - 500.0)/1000.0; ph_param.kinematic.position.y = (static_cast<double>(rand() % 1000) - 500.0)/1000.0; } ph_param.kinematic.direction.vx = (static_cast<double>(rand() % 1000) - 500.0)/1000.0; ph_param.kinematic.direction.vy = (static_cast<double>(rand() % 1000) - 500.0)/1000.0; ph_param.kinematic.direction.Normalize(); ph_param.parts.body.type = ppHumanTorso; ph_param.parts.chassis.type = ppHumanLegs; ph_param.parts.ganglion.type = ppHumanHead; ph_param.parts.manipulator.type = ppHumanArms; sh_param.sh_height = sShowParam::enShowHeight::shStay; } void CGameplayObjectGenerator::MakeParam_Construction(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); ph_param.perseption.sight_distance = 0; ph_param.material.mass = 1.0E+100; ph_param.health.health_points_max = 0; sh_param.sh_height = sShowParam::enShowHeight::shStay; } void CGameplayObjectGenerator::MakeParam_Projectile(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); ph_param.perseption.sight_distance = 0.0; sh_param.sh_height = sShowParam::enShowHeight::shFly; sh_param.trace_ttl = 0.4; } void CGameplayObjectGenerator::MakeParam_Loot(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); ph_param.health.health_points_max = 0.0; ph_param.contained.can_be_contained = true; sh_param.sh_height = sShowParam::enShowHeight::shOnGround; } void CGameplayObjectGenerator::MakeZombieParam(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); ph_param.material.size = 0.3; ph_param.shape.Clear(); ph_param.shape.AddCircle({0,0}, ph_param.material.size); } void CGameplayObjectGenerator::MakeHumanParam(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); ph_param.material.size = 0.3; ph_param.shape.Clear(); ph_param.shape.AddCircle({0,0}, ph_param.material.size); } void CGameplayObjectGenerator::MakeWallParam(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); ph_param.shape.Clear(); ph_param.shape.AddLine({0.0, 0.0}, {5.0, 0.0}); } void CGameplayObjectGenerator::MakeParam_Bullet(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); ph_param.shape.Clear(); ph_param.shape.AddPoint({0,0}); ph_param.health.health_points = 1.0; ph_param.health.health_points_max = 1.0; ph_param.health.max_distance_move = 20.0; ph_param.material.mass = 0.051; } void CGameplayObjectGenerator::MakeParam_Pistol(sObjGpParam &param, sShowParam &sh_param, sPhysicsParam &ph_param) { log_debug1("%s %s; %s; %s;", __PRETTY_FUNCTION__, param.print().c_str(), sh_param.print().c_str(), ph_param.print().c_str()); ph_param.shape.Clear(); ph_param.shape.AddLine({0.0, 0.0}, {0.15, 0.0}); ph_param.material.mass = 0.75; }
43.940299
152
0.684443
[ "shape" ]
d1080a6b9c1550dae73a3b69d19909b7d5d49c25
16,462
cpp
C++
src/cpp/preprocessor.cpp
srbehera/Nebula
3dba4c0aef5d0c1660748ee9bd8e1e4e74b933c3
[ "MIT" ]
11
2021-01-28T12:08:36.000Z
2022-03-21T01:42:08.000Z
src/cpp/preprocessor.cpp
srbehera/Nebula
3dba4c0aef5d0c1660748ee9bd8e1e4e74b933c3
[ "MIT" ]
6
2021-07-19T08:11:23.000Z
2021-09-17T21:05:35.000Z
src/cpp/preprocessor.cpp
srbehera/Nebula
3dba4c0aef5d0c1660748ee9bd8e1e4e74b933c3
[ "MIT" ]
3
2021-08-02T05:10:06.000Z
2021-11-17T03:20:28.000Z
#include <omp.h> #include <errno.h> #include <iomanip> #include "preprocessor.hpp" #include "inner.hpp" #include "logger.hpp" #include "junction.hpp" #include "bed_utils.hpp" using namespace std ; void Preprocessor::run() { auto c = Configuration::getInstance() ; cout << "Preprocessing.." << endl ; load_chromosomes(c->reference) ; auto inner_kmer_extractor = InnerKmerExtractor(c->threads) ; inner_kmer_extractor.run() ; auto junction_kmer_extractor = JunctionKmerExtractor(c->threads) ; junction_kmer_extractor.run() ; merge_genotyping_kmers(inner_kmer_extractor.inner_kmers, junction_kmer_extractor.junction_kmers) ; scan_reference(c->threads) ; filter_kmers() ; dump_kmers(c->workdir) ; } // ============================================================================= \\ // ============================================================================= \\ // ================================ FASTA Files ================================ \\ // ============================================================================= \\ // ============================================================================= \\ void Preprocessor::scan_reference(int threads) { cout << "--------------------------------------------------------- " << endl ; cout << "Scanning reference genome.." << endl ; threads = min(threads, int(chromosome_seqs.size())) ; for (int t = 0; t < threads - 1; t++) { cout << endl ; } int m = 0 ; int n = chromosomes.size() ; vector<unordered_map<uint64_t, Kmer>> batches(chromosomes.size()) ; while (m < n) { int p = m ; #pragma omp parallel for num_threads(threads) for (int i = 0; i < threads; i++) { if (m + i < n) { batches[i + m] = scan_chromosome(chromosomes[m + i], threads) ; } } m += threads ; if (m >= chromosomes.size()) { m = n ; } } cout << "--------------------------------------------------------- " << endl ; for (int i = 0; i < chromosomes.size(); i++) { cout << "Merging " << std::left << std::setw(6) << chromosomes[i] << ", " << std::setw(9) << batches[i].size() << " matches.." << endl ; for(auto it = batches[i].begin(); it != batches[i].end(); it++) { kmers[it->first].count += it->second.count ; kmers[it->first].loci.insert(kmers[it->first].loci.end(), it->second.loci.begin(), it->second.loci.end()) ; } batches[i].clear() ; } cout << "Reference scan completed." << endl ; } unordered_map<uint64_t, Kmer> Preprocessor::scan_chromosome(string chrom, int threads) { unordered_map<uint64_t, Kmer> _kmers ; uint64_t k = 0 ; uint64_t left = 0 ; uint64_t right = 0 ; uint64_t l = strlen(chromosome_seqs[chrom]) ; //cout << "Scanning " << chrom << " with " << l << " bases.." << endl ; KmerIterator it(chromosome_seqs[chrom], 234, l - 500, 234, ITER_MODE_REF) ; int n = 0 ; while (it) { auto k = it->kmer ; if (kmers.find(k) != kmers.end()) { if (_kmers.find(k) == _kmers.end()) { _kmers[k] = Kmer() ; _kmers[k].count = 0 ; } if (_kmers[k].count >= 4) { it++ ; continue ; } Locus locus({get_chromosome_index(chrom), uint32_t(it.position), LOCUS_TYPE_REF, it->left, it->right, uint16_t(it->gc / 5), false}) ; _kmers[k].loci.push_back(locus) ; _kmers[k].count ++ ; n++ ; } else { uint64_t rc = encoded_reverse_complement(k) ; if (kmers.find(rc) != kmers.end()) { if (_kmers.find(rc) == _kmers.end()) { _kmers[rc] = Kmer() ; _kmers[rc].count = 0 ; } if (_kmers[rc].count >= 4) { it++ ; continue ; } Locus locus({get_chromosome_index(chrom), uint32_t(it.position), LOCUS_TYPE_REF, it->left, it->right, uint16_t(it->gc / 5), false}) ; _kmers[rc].loci.push_back(locus) ; _kmers[rc].count ++ ; n++ ; } } it++ ; if (it.position % 10000000 == 0) { cout_mutex.lock() ; int index = get_chromosome_index(chrom) ; for (int j = 0; j < (threads - 1) - index; j++) { cout << "\x1b[A" ; } cout << "\r"<< std::left << std::setw(6) << chrom << " progress " << std::fixed << std::setprecision(3) << float(it.position) / float(l) << "%, loci: " << std::left << std::setw(9) << n ; for (int j = 0; j < (threads - 1) - index; j++) { cout << endl ; } cout_mutex.unlock() ; //cout << chrom << " progress " << float(it.position) / float(l) << "%, loci: " << n << endl ; } } return _kmers ; } // ============================================================================= \\ // ================================= Filtering ================================= \\ // ============================================================================= \\ void Preprocessor::merge_genotyping_kmers(unordered_map<uint64_t, Kmer> inner_kmers, unordered_map<uint64_t, Kmer> junction_kmers) { auto c = Configuration::getInstance() ; cout << "--------------------------------------------------------- " << endl ; cout << "Merging inner and junction kmers.." << endl ; std::vector<uint64_t> remove ; for (auto junction_kmer = junction_kmers.begin(); junction_kmer != junction_kmers.end(); junction_kmer++) { if (inner_kmers.find(junction_kmer->first) != inner_kmers.end()) { remove.push_back(junction_kmer->first) ; } } int m = 0 ; std::ofstream j ; j.open(c->workdir + "/common.json") ; j << "{\n" ; for (auto kmer = remove.begin(); kmer != remove.end(); kmer++) { if (m != 0) { j << ",\n" ; } m++ ; j << "\"" << decode_kmer(*kmer) << "\":" ; j << nlohmann::json(inner_kmers.find(*kmer)->second).dump(4) ; inner_kmers.erase(*kmer) ; junction_kmers.erase(*kmer) ; } j << "\n}\n" ; j.close() ; cout << "Filtered " << m << " common kmers." << endl ; kmers.insert(inner_kmers.begin(), inner_kmers.end()) ; kmers.insert(junction_kmers.begin(), junction_kmers.end()) ; } // ============================================================================= \\ // ================================= Filtering ================================= \\ // ============================================================================= \\ vector<uint64_t> find_interest_masks(Kmer& k) { std::vector<uint64_t> interset_masks ; for (auto locus = k.loci.begin(); locus != k.loci.end(); locus++) { if (locus->type != LOCUS_TYPE_REF) { // these will be junction if (locus->left != 0) { interset_masks.push_back(locus->left) ; } if (locus->right != 0) { interset_masks.push_back(locus->right) ; } } // these will be inner and breakpoint loci from deletions + inner breakpoint from insertions else { for (auto track = k.tracks.begin(); track != k.tracks.end(); track++) { if (locus->chrom == track->first.chrom) { if (locus->position >= track->first.begin - 32 && locus->position <= track->first.end) { if (locus->left != 0) { interset_masks.push_back(locus->left) ; } if (locus->right != 0) { interset_masks.push_back(locus->right) ; } locus->type = LOCUS_TYPE_INNER ; } } } } } bool found = false ; for (auto locus = k.loci.begin(); locus != k.loci.end(); locus++) { if (locus->type != LOCUS_TYPE_REF) { found = true ; } } if (not found) { print_kmer(k) ; } assert(found) ; return interset_masks ; } void Preprocessor::filter_kmers() { auto c = Configuration::getInstance() ; int l = 0 ; int n = 0 ; int r = 0 ; int p = 0 ; int threads = min(c->threads, int(kmers.bucket_count())) ; vector<vector<uint64_t>> filters(threads) ; cout << "Filtering " << kmers.size() << " kmers using " << threads << " threads on " << kmers.bucket_count() << " buckets.." << endl ; #pragma omp parallel for num_threads(threads) for (size_t bucket = 0; bucket < kmers.bucket_count(); bucket++) { //cout << bucket << " " << n << endl ; for (auto kmer = kmers.begin(bucket); kmer != kmers.end(bucket); kmer++) { n++ ; Kmer& k = kmer->second ; // filter based on ref count if (k.count > 3) { int t = omp_get_thread_num() ; filters[t].push_back(kmer->first) ; r += 1 ; //cout << "filtered based on ref count" << endl ; continue ; } std::vector<Locus> loci(k.loci) ; std::vector<uint64_t> interset_masks = find_interest_masks(k) ; bool found = false ; for (auto locus = k.loci.begin(); locus != k.loci.end(); locus++) { if (locus->type != LOCUS_TYPE_REF) { found = true ; } } if (not found) { print_kmer(k) ; } assert(found) ; // number of loci before filtering int l_1 = k.loci.size() ; auto locus = k.loci.begin() ; while (locus != k.loci.end()) { if (locus->type == LOCUS_TYPE_REF) { bool found = false ; for (auto m = interset_masks.begin(); m != interset_masks.end(); m++) { if (locus->left != 0) { if (is_canonical_subsequence(locus->left, *m)) { found = true ; break ; } } if (locus->right != 0) { if (is_canonical_subsequence(locus->right, *m)) { found = true ; break ; } } } // doesn't have any shared masks, filter if (not found) { k.filtered_loci.push_back(*locus) ; locus = k.loci.erase(locus) ; continue ; } } locus++ ; } // number of loci after filtering int l_2 = k.loci.size() ; //cout << l_2 << " remaining" << endl ; // loci with less than two masks exist if (k.type == KMER_TYPE_JUNCTION) { auto a = find_if(k.loci.begin(), k.loci.end(), [](Locus l) { return l.left == 0 || l.right == 0 ; }) ; //non-junction loci exists auto b = find_if(k.loci.begin(), k.loci.end(), [](Locus l) { return l.type == LOCUS_TYPE_REF ; }) ; // won't happen for inner kmers if (a != k.loci.end()) { // junction loci exist wtih less than two masks if (l_1 != l_2) { // some ref loci were filtered if (b == k.loci.end()) { // all ref loci were filtered // because ref loci will have masks, count them instead and subtract from total. May overcount. // Counting with one mask will undercount k.loci = loci ; auto locus = k.loci.begin() ; // count non-junction loci only while (locus != k.loci.end()) { if (locus->type == LOCUS_TYPE_JUNCTION) { k.junction_loci.push_back(*locus) ; locus = k.loci.erase(locus) ; } else { locus++ ; } } k.inverse = true ; } else { // some ref loci remain int t = omp_get_thread_num() ; filters[t].push_back(kmer->first) ; l += 1 ; continue ; } } else { // no ref loci was filtered, so we need to count every loci } } } } if (n - p > 10000) { p = n ; cout << "Progress " << std::left << std::setw(6) << std::fixed << std::setprecision(3) << float(n) / kmers.size() << "%..\r" << flush ; } } cout << endl ; cout << "Removing filtered kmers.." << endl ; int f = 0 ; std::ofstream j ; j.open(c->workdir + "/filtered.json") ; j << "{\n" ; //TODO: this is not necessary for (auto it = filters.begin(); it != filters.end(); it++) { for (auto k: *it) { if (f != 0) { j << ",\n" ; } f++ ; j << "\"" << decode_kmer(k) << "\":" ; j << nlohmann::json(kmers.find(k)->second).dump(4) ; kmers.erase(kmers.find(k)) ; } } cout << "Removed " << f << " kmers." << endl ; j << "\n}\n" ; j.close() ; cout << "Remaining " << kmers.size() << endl ; } // ============================================================================= \\ // ============================================================================= \\ // ============================================================================= \\ // ============================================================================= \\ // ============================================================================= \\ void Preprocessor::dump_kmers(string path) { auto c = Configuration::getInstance() ; cout << "Verifying and dumping kmers.." << endl ; vector<int> counters ; int num_batches = 100 ; vector<mutex> locks(num_batches) ; vector<ofstream> output_files ; // this is for internal testing //ofstream test(path + "/kmers.txt") ; //for (auto kmer = kmers.begin(); kmer != kmers.end(); kmer++) { // assert(kmer->second.weight == 1.0) ; // test << decode_kmer(kmer->first) << endl ; //} //test.close() ; for (int i = 0; i < num_batches; i++) { string p = path + "/kmers_batch_" + std::to_string(i) + ".json" ; output_files.emplace_back(ofstream {p}) ; output_files[i] << "{\n" ; counters.push_back(0) ; } //TODO: check if correctly parallel //#pragma omp parallel for num_threads(c->threads) for (size_t bucket = 0; bucket < kmers.bucket_count(); bucket++) { int t = bucket % num_batches ; locks[t].lock() ; for (auto kmer = kmers.begin(bucket); kmer != kmers.end(bucket); kmer++) { bool found = false ; for (auto locus = kmer->second.loci.begin(); locus != kmer->second.loci.end(); locus++) { if (locus->type != LOCUS_TYPE_REF) { found = true ; } } if (!found) { assert(kmer->second.inverse) ; } if (kmer->second.inverse) { assert(kmer->second.type == KMER_TYPE_JUNCTION) ; } if (counters[t] != 0) { output_files[t] << ",\n" ; } counters[t] += 1 ; output_files[t] << "\"" << decode_kmer(kmer->first) << "\":" ; output_files[t] << nlohmann::json(kmer->second).dump(4) ; } locks[t].unlock() ; } for (int i = 0; i < num_batches; i++) { output_files[i] << "\n}\n" ; } }
40.950249
199
0.422063
[ "vector" ]
d10882634556b7cf0a15be4f7bc55957732e98fc
15,721
cpp
C++
src/selfie_perception/src/obstacles_generator.cpp
KNR-Selfie/selfie_carolocup2020
5d6331962e4752c9e9c4fcc88ebd3093e4d96b85
[ "BSD-3-Clause" ]
10
2019-08-17T14:50:13.000Z
2021-07-19T17:21:13.000Z
src/selfie_perception/src/obstacles_generator.cpp
KNR-Selfie/selfie_carolocup2020
5d6331962e4752c9e9c4fcc88ebd3093e4d96b85
[ "BSD-3-Clause" ]
16
2019-05-27T18:50:09.000Z
2020-02-11T00:23:50.000Z
src/selfie_perception/src/obstacles_generator.cpp
KNR-Selfie/selfie_carolocup2020
5d6331962e4752c9e9c4fcc88ebd3093e4d96b85
[ "BSD-3-Clause" ]
3
2020-01-21T15:03:24.000Z
2021-05-02T06:40:50.000Z
#include <selfie_perception/obstacles_generator.h> ObstaclesGenerator::ObstaclesGenerator(const ros::NodeHandle &nh, const ros::NodeHandle &pnh) : nh_(nh), pnh_(pnh), transformListener_(nh_), max_range_(1.0), min_range_(0.03), obstacles_frame_("laser"), visualization_frame_("base_link"), output_frame_("base_link"), visualize_(true), lidar_offset_(0), segment_threshold_(0.03), min_segment_size_(0.04), max_segment_size_(0.5), min_to_divide_(0.03), upside_down_(false), dr_server_CB_(boost::bind(&ObstaclesGenerator::reconfigureCB, this, _1, _2)) { obstacles_pub_ = nh_.advertise<selfie_msgs::PolygonArray>("obstacles", 10); } ObstaclesGenerator::~ObstaclesGenerator() { obstacle_array_.polygons.clear(); line_array_.clear(); } bool ObstaclesGenerator::init() { scan_sub_ = nh_.subscribe("/scan", 10, &ObstaclesGenerator::laserScanCallback, this); pnh_.getParam("max_range", max_range_); pnh_.getParam("min_range", min_range_); pnh_.getParam("visualize", visualize_); pnh_.getParam("obstacles_frame", obstacles_frame_); pnh_.getParam("visualization_frame", visualization_frame_); pnh_.getParam("output_frame", output_frame_); pnh_.getParam("segment_threshold", segment_threshold_); pnh_.getParam("min_segment_size", min_segment_size_); pnh_.getParam("max_segment_size", max_segment_size_); pnh_.getParam("min_to_divide", min_to_divide_); pnh_.getParam("lidar_offset", lidar_offset_); pnh_.getParam("upside_down", upside_down_); dr_server_.setCallback(dr_server_CB_); if (visualize_) { visualization_lines_pub_ = nh_.advertise<visualization_msgs::Marker>("visualization_lines", 1); visualization_obstacles_pub_ = nh_.advertise<visualization_msgs::Marker>("visualization_obstacles", 1); } printInfoParams(); initializeTransform(); return true; } void ObstaclesGenerator::laserScanCallback(const sensor_msgs::LaserScan &msg) { scan = msg; divideIntoSegments(); if(segments_.empty()) { obstacle_array_.polygons.clear(); obstacle_array_.header.stamp = ros::Time::now(); obstacle_array_.header.frame_id = output_frame_; obstacles_pub_.publish(obstacle_array_); line_array_.clear(); } else { generateLines(); generateObstacles(); } if (visualize_) { visualizeLines(); visualizeObstacles(); } } void ObstaclesGenerator::generateLines() { line_array_.clear(); for(int i = 0; i < segments_.size(); ++i) { float max = 0; Point p_max; float A = getA(segments_[i][0], segments_[i][segments_[i].size() - 1]); float C = segments_[i][0].y - (A * segments_[i][0].x); for(int j = 0; j < segments_[i].size(); ++j) { float distance = std::abs(A * segments_[i][j].x - segments_[i][j].y + C) / sqrtf(A * A + 1); if(distance > max) { max = distance; p_max = segments_[i][j]; } } if(max > min_to_divide_) { Line l; l.start_point = segments_[i][0]; l.end_point = p_max; l.slope = getSlope(l.start_point, l.end_point); l.a = getA(l.start_point, l.end_point); l.b = l.start_point.y - (l.a * l.start_point.x); line_array_.push_back(l); l.start_point = p_max; l.end_point = segments_[i][segments_[i].size() - 1]; l.slope = getSlope(l.start_point, l.end_point); l.a = getA(l.start_point, l.end_point); l.b = l.start_point.y - (l.a * l.start_point.x); line_array_.push_back(l); } else { Line l; l.start_point = segments_[i][0]; l.end_point = segments_[i][segments_[i].size() - 1]; l.slope = getSlope(l.start_point, l.end_point); l.a = getA(l.start_point, l.end_point); l.b = l.start_point.y - (l.a * l.start_point.x); line_array_.push_back(l); } } } Point ObstaclesGenerator::getXY(float angle, float range) { Point p; p.x = range * cos(angle); p.y = range * sin(angle); return p; } float ObstaclesGenerator::getSlope(Point &p1, Point &p2) { return atan((p2.y - p1.y) / (p2.x - p1.x)); } float ObstaclesGenerator::getDistance(Point &p1, Point &p2) { float dx = p2.x - p1.x; float dy = p2.y - p1.y; return std::sqrt(dx * dx + dy * dy); } float ObstaclesGenerator::getA(Point &p1, Point &p2) { return (p2.y - p1.y) / (p2.x - p1.x); } void ObstaclesGenerator::visualizeLines() { visualization_msgs::Marker marker; marker.header.frame_id = visualization_frame_; marker.header.stamp = ros::Time::now(); marker.ns = "line"; marker.type = visualization_msgs::Marker::LINE_LIST; marker.action = visualization_msgs::Marker::ADD; marker.id = 0; marker.lifetime = ros::Duration(); marker.color.r = 1.0f; marker.color.g = 0.0f; marker.color.b = 0.0f; marker.color.a = 1.0f; marker.scale.x = 0.01; marker.scale.y = 0.01; geometry_msgs::Point marker_point; marker_point.z = 0; if (!line_array_.empty()) { for (int i = 0; i < line_array_.size(); i++) { marker_point.x = line_array_[i].start_point.x + lidar_offset_; marker_point.y = line_array_[i].start_point.y * 1; marker.points.push_back(marker_point); marker_point.x = line_array_[i].end_point.x + lidar_offset_; marker_point.y = line_array_[i].end_point.y * 1; marker.points.push_back(marker_point); } } visualization_lines_pub_.publish(marker); } void ObstaclesGenerator::printInfoParams() { ROS_INFO("max_range: %.3f", max_range_); ROS_INFO("min_range: %.3f\n", min_range_); ROS_INFO("visualize: %d", visualize_); ROS_INFO("obstacles_frame: %s", obstacles_frame_.c_str()); ROS_INFO("visualization_frame: %s\n", visualization_frame_.c_str()); ROS_INFO("segment_threshold: %.3f", segment_threshold_); ROS_INFO("min_segment_size: %.3f", min_segment_size_); ROS_INFO("max_segment_size: %.3f", max_segment_size_); ROS_INFO("min_to_divide: %.3f\n", min_to_divide_); ROS_INFO("lidar_offset: %.3f", lidar_offset_); ROS_INFO("upside_down: %d", upside_down_); } void ObstaclesGenerator::generateObstacles() { obstacle_array_.polygons.clear(); obstacle_array_.header.stamp = ros::Time::now(); obstacle_array_.header.frame_id = output_frame_; if (!line_array_.empty()) { float distance = 0; float max_distance = 0.16; float slope_diff = 0; geometry_msgs::Point32 p; p.z = 0; geometry_msgs::Polygon obstacle; bool obstacle_generated = false; for (int i = 0; i < line_array_.size(); i++) { obstacle_generated = false; if (i != line_array_.size() - 1) { distance = getDistance(line_array_[i].end_point, line_array_[i + 1].start_point); slope_diff = std::abs(line_array_[i].slope - line_array_[i + 1].slope); if (distance < max_distance && slope_diff > M_PI / 4.2) { p.x = ((line_array_[i + 1].b - line_array_[i].b) / (line_array_[i].a - line_array_[i + 1].a)) + lidar_offset_; p.y = (((line_array_[i + 1].b * line_array_[i].a) - (line_array_[i].b * line_array_[i + 1].a)) / (line_array_[i].a - line_array_[i + 1].a)); obstacle.points.push_back(p); p.x = line_array_[i].start_point.x + lidar_offset_; p.y = line_array_[i].start_point.y; obstacle.points.push_back(p); float b1 = line_array_[i].start_point.y - line_array_[i + 1].a * line_array_[i].start_point.x; float b2 = line_array_[i + 1].end_point.y - line_array_[i].a * line_array_[i + 1].end_point.x; p.x = ((b1 - b2) / (line_array_[i].a - line_array_[i + 1].a)) + lidar_offset_; p.y = ((b1 * line_array_[i].a - b2 * line_array_[i + 1].a) / (line_array_[i].a - line_array_[i + 1].a)); obstacle.points.push_back(p); p.x = line_array_[i + 1].end_point.x + lidar_offset_; p.y = line_array_[i + 1].end_point.y; obstacle.points.push_back(p); i++; obstacle_generated = true; } } if (!obstacle_generated) { float obstacle_nominal_length_ = getDistance(line_array_[i].start_point, line_array_[i].end_point); p.x = line_array_[i].start_point.x + lidar_offset_; p.y = line_array_[i].start_point.y; obstacle.points.push_back(p); p.x = line_array_[i].end_point.x + lidar_offset_; p.y = line_array_[i].end_point.y; obstacle.points.push_back(p); float add_x = obstacle_nominal_length_ * sin(line_array_[i].slope); float add_y = obstacle_nominal_length_ * cos(line_array_[i].slope); float sx = (line_array_[i].end_point.x + line_array_[i].start_point.x) / 2; float sy = (line_array_[i].end_point.y + line_array_[i].start_point.y) / 2; if (line_array_[i].slope > -1 * M_PI / 4 && line_array_[i].slope < M_PI / 4) { if (sy > 0) { add_x *= -1; add_y *= -1; } } else if ((sx > 0 && line_array_[i].slope < 0) || (sx < 0 && line_array_[i].slope > 0)) { add_x *= -1; add_y *= -1; } p.x = line_array_[i].end_point.x + add_x + lidar_offset_; p.y = (line_array_[i].end_point.y - add_y); obstacle.points.push_back(p); p.x = line_array_[i].start_point.x + add_x + lidar_offset_; p.y = (line_array_[i].start_point.y - add_y); obstacle.points.push_back(p); } obstacle_array_.polygons.push_back(obstacle); obstacle.points.clear(); } } convertToOutputFrame(); // obstacle_array_ obstacles_pub_.publish(obstacle_array_); } void ObstaclesGenerator::visualizeObstacles() { visualization_msgs::Marker marker; marker.header.frame_id = visualization_frame_; marker.header.stamp = ros::Time::now(); marker.ns = "obstacles"; marker.type = visualization_msgs::Marker::LINE_LIST; marker.action = visualization_msgs::Marker::ADD; marker.id = 0; marker.lifetime = ros::Duration(); marker.color.r = 0.0f; marker.color.g = 1.0f; marker.color.b = 0.0f; marker.color.a = 1.0f; marker.scale.x = 0.006; marker.scale.y = 0.006; geometry_msgs::Point marker_point; marker_point.z = 0; if (!obstacle_array_.polygons.empty()) { for (int i = 0; i < obstacle_array_.polygons.size(); i++) { marker_point.x = obstacle_array_.polygons[i].points[0].x; marker_point.y = obstacle_array_.polygons[i].points[0].y; marker.points.push_back(marker_point); marker_point.x = obstacle_array_.polygons[i].points[1].x; marker_point.y = obstacle_array_.polygons[i].points[1].y; marker.points.push_back(marker_point); marker_point.x = obstacle_array_.polygons[i].points[1].x; marker_point.y = obstacle_array_.polygons[i].points[1].y; marker.points.push_back(marker_point); marker_point.x = obstacle_array_.polygons[i].points[2].x; marker_point.y = obstacle_array_.polygons[i].points[2].y; marker.points.push_back(marker_point); marker_point.x = obstacle_array_.polygons[i].points[2].x; marker_point.y = obstacle_array_.polygons[i].points[2].y; marker.points.push_back(marker_point); marker_point.x = obstacle_array_.polygons[i].points[3].x; marker_point.y = obstacle_array_.polygons[i].points[3].y; marker.points.push_back(marker_point); marker_point.x = obstacle_array_.polygons[i].points[3].x; marker_point.y = obstacle_array_.polygons[i].points[3].y; marker.points.push_back(marker_point); marker_point.x = obstacle_array_.polygons[i].points[0].x; marker_point.y = obstacle_array_.polygons[i].points[0].y; marker.points.push_back(marker_point); } } visualization_obstacles_pub_.publish(marker); } void ObstaclesGenerator::divideIntoSegments() { segments_.clear(); std::vector <Point> segment; Point p = getXY(scan.angle_min, scan.ranges[0]); segment.push_back(p); int act_angle_index = 1; bool segment_end = false; for (float act_angle = scan.angle_min + scan.angle_increment; act_angle <= scan.angle_max; act_angle += scan.angle_increment) { if (scan.ranges[act_angle_index] <= max_range_ && scan.ranges[act_angle_index] >= min_range_) { if(std::abs(scan.ranges[act_angle_index] - scan.ranges[act_angle_index - 1]) < segment_threshold_) { p = getXY(act_angle, scan.ranges[act_angle_index]); segment.push_back(p); } else segment_end = true; } else segment_end = true; if(segment_end) { if(!segment.empty()) { float segment_size = getDistance(segment[0], segment[segment.size() - 1]); if(segment_size > min_segment_size_ && segment_size < max_segment_size_) { segments_.push_back(segment); segment.clear(); } else segment.clear(); } segment_end = false; } ++act_angle_index; } } void ObstaclesGenerator::convertToOutputFrame() { if(output_frame_ == obstacles_frame_) return; for(std::vector<geometry_msgs::Polygon>::iterator plgit = obstacle_array_.polygons.begin();plgit!= obstacle_array_.polygons.end();++plgit) { std::for_each(plgit->points.begin(), plgit->points.end(), std::bind(&ObstaclesGenerator::transformPoint,this, std::placeholders::_1)); } } void ObstaclesGenerator::initializeTransform() { ROS_INFO("Waiting for any transform form %s to %s\n",output_frame_.c_str(), obstacles_frame_.c_str()); transformListener_.waitForTransform(output_frame_, obstacles_frame_, ros::Time(0), ros::Duration(30), ros::Duration(0.0001)); ROS_INFO("Transform from %s to %s found\n",output_frame_.c_str(), obstacles_frame_.c_str()); transformListener_.lookupTransform(output_frame_, obstacles_frame_, ros::Time(0), transform_); } void ObstaclesGenerator::transformPoint(geometry_msgs::Point32 &pt32) { tf::Point tfpt; geometry_msgs::Point pt; pt.x = static_cast<double>(pt32.x); pt.y = static_cast<double>(pt32.y); pt.z = static_cast<double>(pt32.z); tf::pointMsgToTF(pt, tfpt); tfpt = transform_ * tfpt; tf::pointTFToMsg(tfpt, pt); pt32.x = static_cast<float>(pt.x); pt32.y = static_cast<float>(pt.y); pt32.z = static_cast<float>(pt.z); } void ObstaclesGenerator::convertUpsideDown() { for(int i = 0; i < obstacle_array_.polygons.size(); ++i) { obstacle_array_.polygons[i].points[0].y *= -1; obstacle_array_.polygons[i].points[1].y *= -1; obstacle_array_.polygons[i].points[2].y *= -1; obstacle_array_.polygons[i].points[3].y *= -1; } } void ObstaclesGenerator::reconfigureCB(selfie_perception::DetectObstaclesConfig& config, uint32_t level) { if(max_range_ != (float)config.max_range) { max_range_ = config.max_range; ROS_INFO("max_range_ new value: %f", max_range_); } if(max_segment_size_ != (float)config.max_segment_size) { max_segment_size_ = config.max_segment_size; ROS_INFO("max_segment_size_ new value: %f", max_segment_size_); } if(min_range_ != (float)config.min_range) { min_range_ = config.min_range; ROS_INFO("min_range_ new value: %f", min_range_); } if(min_segment_size_ != (float)config.min_segment_size) { min_segment_size_ = config.min_segment_size; ROS_INFO("min_segment_size_ new value: %f", min_segment_size_); } if(min_to_divide_ != (float)config.min_to_divide) { min_to_divide_ = config.min_to_divide; ROS_INFO("min_to_divide new value: %f", min_to_divide_); } if(segment_threshold_ != (float)config.segment_threshold) { segment_threshold_ = config.segment_threshold; ROS_INFO("segment_threshold new value: %f", segment_threshold_); } }
31.568273
150
0.657465
[ "vector", "transform" ]
d1121d36d28b641a8ed802d5c9fa3ea52b3cddd7
25,123
cpp
C++
src/hard.cpp
miuho/Hadoop-YARN
4ef10c656169763422f3815ebc9599eeb1a28689
[ "MIT" ]
1
2018-09-16T18:41:50.000Z
2018-09-16T18:41:50.000Z
src/schedpolserver.cpp
miuho/Hadoop-YARN
4ef10c656169763422f3815ebc9599eeb1a28689
[ "MIT" ]
null
null
null
src/schedpolserver.cpp
miuho/Hadoop-YARN
4ef10c656169763422f3815ebc9599eeb1a28689
[ "MIT" ]
null
null
null
#include "TetrischedService.h" #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/server/TSimpleServer.h> #include <thrift/transport/TServerSocket.h> #include <thrift/transport/TBufferTransports.h> #include "YARNTetrischedService.h" #include <thrift/transport/TSocket.h> #include <thrift/transport/TTransportUtils.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <time.h> #include <ctype.h> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstring> #include <vector> #include <queue> #include <set> #include <unordered_map> #include <mutex> #define NONE 1 #define HARD 2 #define SOFT 3 #define MAX_WAIT_TIME 1200 using namespace ::apache::thrift; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::transport; using namespace ::apache::thrift::server; //using boost::shared_ptr; using namespace std; using namespace alsched; struct Job_S { JobID jobId; job_t::type jobType; int32_t k; int32_t priority; double duration; double slowDuration; double chosen_duration; time_t added_time; int32_t *machines; }; class TetrischedServiceHandler : virtual public TetrischedServiceIf { private: int free_machines; int mode; // 1 = none, 2 = hard, 3 = soft vector<vector<int32_t>> free_racks; vector<vector<int32_t>> used_racks; unordered_map<int32_t, time_t> free_times; set<Job_S *> jobs; mutex mtx; Job_S *get_random_job(void) { // find the earliest added job (fifo) int earliest_time = INT_MAX; Job_S *earliest_job = NULL; for (std::set<Job_S *>::iterator it = jobs.begin(); it != jobs.end(); ++it) { Job_S *job = *it; if (job->added_time < earliest_time) { earliest_time = job->added_time; earliest_job = job; } } // check if possible to allocate at all if (free_machines < earliest_job->k) return NULL; // randomly allocate machines srand (time(NULL)); int j = 0; while (j < earliest_job->k) { int rand_i = rand() % free_racks.size(); if (free_racks[rand_i].empty()) continue; used_racks[rand_i].push_back(free_racks[rand_i].back()); (earliest_job->machines)[j] = free_racks[rand_i].back(); // overwrite each check free_racks[rand_i].pop_back(); j++; } return earliest_job; } time_t get_waiting_time_gpu(time_t cur_time, int32_t k) { if (k > (int32_t)(free_racks[0].size() + used_racks[0].size())) { cout << "Invalid GPU rack\n"; return cur_time; } // compute the minimum waiting time for gpu rack int32_t require = k - free_racks[0].size(); vector<time_t> times; for (int32_t j = 0; j < (int32_t)used_racks[0].size(); j++) { time_t t = free_times[used_racks[0][j]]; time_t diff = (t > cur_time) ? (t - cur_time) : 0; times.push_back(diff); } // sort the waiting time sort(times.begin(), times.end()); time_t rack_min = times[require - 1]; return rack_min; } time_t get_waiting_time_mpi(time_t cur_time, int32_t k) { time_t global_rack_min = cur_time; // traverse all racks for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { // skips those small racks if (k > (int32_t)(free_racks[i].size() + used_racks[i].size())) continue; // compute the minimum waiting time for this rack int32_t require = k - free_racks[i].size(); if (require <= 0) { cout << "ERROR: Found full rack to allocate\n"; continue; } vector<time_t> times; for (int32_t j = 0; j < (int32_t)used_racks[i].size(); j++) { time_t t = free_times[used_racks[i][j]]; time_t diff = (t > cur_time) ? (t - cur_time) : 0; times.push_back(diff); } // sort the waiting time sort(times.begin(), times.end()); time_t rack_min = times[require - 1]; if (rack_min < global_rack_min) global_rack_min = rack_min; } return global_rack_min; } int get_utility(Job_S *job, bool preferred) { int utility = 1200; int waited_time = (int)(job->added_time - time(NULL)); if (preferred) utility -= (waited_time + job->duration); else utility -= (waited_time + job->slowDuration); return (utility < 0) ? 0 : utility; } Job_S *get_max_utility_job(time_t cur_time) { int max_utility = -1; Job_S *max_utility_job = NULL; cout << "Traverse all jobs\n"; for (std::set<Job_S *>::iterator it = jobs.begin(); it != jobs.end(); ++it) { Job_S *job = *it; // check if possible to allocate at all if (free_machines < job->k) continue; bool preferred = false; if (job->jobType == 0) { // JOB_MPI cout << "Looking at MPI job " << job->jobId << "\n"; // check for available non-gpu racks to place all k containers for (int32_t i = 1; i < (int32_t)free_racks.size(); i++) { if ((int32_t)free_racks[i].size() >= job->k) { preferred = true; cout << "Found full rack: "; for (int32_t j = 0; j < job->k; j++) { //used_racks[i].push_back(free_racks[i].back()); //(job->machines)[j] = free_racks[i].back(); // overwrite each check //cout << j << ":" << free_racks[i].back() << ","; //free_racks[i].pop_back(); (job->machines)[j] = free_racks[i][j]; cout << free_racks[i][j] << ","; } cout << "\n"; // fast duration job->chosen_duration = job->duration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } break; } } // check if gpu rack is available if (!preferred) { // try to place k containers into gpu machines if ((int32_t)free_racks[0].size() >= job->k) { preferred = true; cout << "Finding in GPU rack: "; for (int i = 0; i < job->k; i++) { //used_racks[0].push_back(free_racks[0].back()); //(job->machines)[i] = free_racks[0].back(); // overwrite each check //cout << i << ":" << free_racks[0].back() << ","; //free_racks[0].pop_back(); (job->machines)[i] = free_racks[0][i]; cout << free_racks[0][i] << ","; } cout << "\n"; // fast duration job->chosen_duration = job->duration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } } } // no availble full rack if (!preferred && mode == SOFT) { cout << "Cannot find full rack\n"; if ((cur_time + get_waiting_time_mpi(cur_time, job->k) + job->duration) < (cur_time + job->slowDuration)) { // wait for free rack //cout << "Delay for free rack\n"; continue; } cout << "Finding in other racks: "; int32_t m = 0; for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { //while(!free_racks[i].empty()) { for (int32_t j = 0; j < (int32_t)free_racks[i].size(); j++) { //used_racks[i].push_back(free_racks[i].back()); //(job->machines)[m] = free_racks[i].back(); // overwrite each check //cout << m << ":" << free_racks[i].back() << ","; //free_racks[i].pop_back(); (job->machines)[m] = free_racks[i][j]; cout << free_racks[i][j] << ","; m++; if (m >= job->k) break; } if (m >= job->k) break; } cout << "\n"; // slow duration job->chosen_duration = job->slowDuration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } } } else if (job->jobType == 2) { // JOB_GPU cout << "Looking at GPU job " << job->jobId << "\n"; // try to place k containers into gpu machines if ((int32_t)free_racks[0].size() >= job->k) { preferred = true; cout << "Finding in GPU rack: "; for (int i = 0; i < job->k; i++) { //used_racks[0].push_back(free_racks[0].back()); //(job->machines)[i] = free_racks[0].back(); // overwrite each check //cout << i << ":" << free_racks[0].back() << ","; //free_racks[0].pop_back(); (job->machines)[i] = free_racks[0][i]; cout << free_racks[0][i] << ","; } cout << "\n"; // fast duration job->chosen_duration = job->duration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } } // not enough gpu machines if (!preferred && mode == SOFT) { if ((cur_time + get_waiting_time_gpu(cur_time, job->k) + job->duration) < (cur_time + job->slowDuration)) { // wait for free gpu rack //cout << "Delay for free gpu rack\n"; continue; } cout << "Finding in other racks: "; int32_t m = 0; for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { //while(!free_racks[i].empty()) { for (int32_t j = 0; j < (int32_t)free_racks[i].size(); j++) { //used_racks[i].push_back(free_racks[i].back()); //(job->machines)[m] = free_racks[i].back(); // overwrite each check //cout << m << ":" << free_racks[i].back() << ","; //free_racks[i].pop_back(); (job->machines)[m] = free_racks[i][j]; cout << free_racks[i][j] << ","; m++; if (m >= job->k) break; } if (m >= job->k) break; } cout << "\n"; // slow duration job->chosen_duration = job->slowDuration; int cur_utility = get_utility(job, preferred); if (cur_utility > max_utility) { max_utility = cur_utility; max_utility_job = job; } } } else { cout << "Invalid jobType\n"; } } if (max_utility_job != NULL) { for (int32_t i = 0; i < max_utility_job->k; i++) { int32_t machine = (max_utility_job->machines)[i]; int32_t j = 0; for (int32_t k = 0; k < (int32_t)free_racks.size(); k++) { j += (int32_t)(free_racks[k].size() + used_racks[k].size()); if (machine < j) { vector<int32_t>::iterator it2 = find(free_racks[k].begin(), free_racks[k].end(), machine); if (it2 == free_racks[k].end()) cout << "ERROR: Trying to allocate resource that is already allocated\n"; else { free_racks[k].erase(it2); used_racks[k].push_back(machine); } break; } } } } return max_utility_job; } void TryToAllocate() { cout << "TryToAllocate\n"; // remove jobs that waited too long time_t cur_time = time(NULL); for (std::set<Job_S *>::iterator it = jobs.begin(); it != jobs.end(); ) { Job_S *job = *it; cout << "job " << job->jobId << " waited for " << (cur_time - job->added_time) << " seconds\n"; // max allowable waiting time in job list < already waited time in job list if ((MAX_WAIT_TIME - job->duration) < (cur_time - job->added_time)) { cout << "Removed timeout job: " << job->jobId << "\n"; it = jobs.erase(it); delete [] (job->machines); delete job; } else { ++it; } } int yarnport = 9090; boost::shared_ptr<TTransport> socket(new TSocket("localhost", yarnport)); boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); YARNTetrischedServiceClient client(protocol); set<int32_t> machines; // try to allocate some nodes try { transport->open(); // keep allocating resources for as many jobs as possible while (!jobs.empty()) { cout << "Begin to find a job...\n"; cur_time = time(NULL); machines.clear(); Job_S *head = NULL; if (mode == NONE) head = get_random_job(); else head = get_max_utility_job(cur_time); // not enough resources to allocate to head if (head == NULL) { cout << "Not enough resources\n"; break; } cout << "Got resources\n"; cout << "Handling job " << head->jobId << "\n"; // allocate resources cout << "Prepare to allocate slaves: "; for (int i = 0; i < (head->k); i++) { int32_t machine = (head->machines)[i]; cout << machine << ", "; machines.insert(machine); } cout << "\n"; free_machines -= (head->k); // allocate machines client.AllocResources(head->jobId, machines); cout << "Successfully handled job " << head->jobId << "\n"; cout << "k: " << head->k << " chosen_duration: " << head->chosen_duration << "\n"; // store free time for (std::set<int32_t>::iterator it = machines.begin(); it != machines.end(); ++it) free_times[*it] = cur_time + (head->chosen_duration); // free job info delete [] (head->machines); jobs.erase(jobs.find(head)); delete head; } transport->close(); } catch (TException& tx) { printf("ERROR calling YARN : %s\n", tx.what()); // recover printf("Recover: \n"); for (std::set<int32_t>::iterator it = machines.begin(); it != machines.end(); ++it) { int32_t j = 0; for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { j += (int32_t)(free_racks[i].size() + used_racks[i].size()); if (*it < j) { vector<int32_t>::iterator it2 = find(used_racks[i].begin(), used_racks[i].end(), *it); if (it2 == used_racks[i].end()) cout << "ERROR: Trying to free resource that isnt allocated\n"; else { used_racks[i].erase(it2); free_racks[i].push_back(*it); free_machines++; } break; } } cout << *it << ", "; } cout << "\n"; } } public: TetrischedServiceHandler(char *config_file) { // Your initialization goes here printf("init\n"); free_machines = 0; mode = 0; // 1 = none, 2 = hard, 3 = soft if (config_file != NULL) { ifstream in(config_file); if (!in) printf("ERROR: cannot find config file\n"); else { string line; string topology = ""; while (getline(in, line)) { if (line.empty()) continue; else { size_t found = line.find("simtype"); if (found != string::npos) { string tmp = line.substr(found + 8); found = tmp.find("\""); if (found != string::npos) { tmp = tmp.substr(found + 1); found = tmp.find("\""); if (found != string::npos) { tmp = tmp.substr(0, found); cout << tmp << "\n"; if (!tmp.compare("none")) mode = NONE; else if (!tmp.compare("hard")) mode = HARD; else if (!tmp.compare("soft")) mode = SOFT; else cout << "Invalid simtype\n"; cout << "mode: " << mode << "\n"; } } } found = line.find("rack_cap"); if (found != string::npos) { string tmp = line.substr(found); topology.append(tmp); if (tmp.find("]") != string::npos) break; while (getline(in, line)) { if (line.empty()) continue; else { topology.append(line); if (line.find("]") != string::npos) break; } } } } } in.close(); if (!mode) { printf("No specified policy: using HARD as default\n"); mode = HARD; // default is hard } if (topology == "" || topology.find("[") == string::npos || topology.find("]") == string::npos || topology.find("[") > topology.find("]")) { printf("ERROR: invalid config file\n"); return; } topology = topology.substr(topology.find("["), topology.find("]")); cout << topology << "\n"; for (unsigned int i = 0; i < topology.length(); i++) { char c = topology.at(i); if (isdigit(c)) { int num = c - '0'; vector<int32_t> tmp1; used_racks.push_back(tmp1); vector<int32_t> tmp2; // all slaves in a rack are initially free for (int i = free_machines; i < (free_machines + num); i++) { tmp2.push_back(i); cout << i << ","; } cout << "\n"; free_racks.push_back(tmp2); free_machines += num; } } } } else { printf("ERROR: no input config file\n"); } } void AddJob(const JobID jobId, const job_t::type jobType, const int32_t k, const int32_t priority, const double duration, const double slowDuration) { mtx.lock(); cout << "AddJob\n"; cout << "jobId: " << jobId << ", jobType: " << jobType << ", k: " << k << ", priority: " << priority << ", duration: " << duration << ", slowDuration: " << slowDuration << "\n"; // create Job_S structure to store job info Job_S *job = new Job_S; job->jobId = jobId; job->jobType = jobType; job->k = k; job->priority = priority; job->duration = duration; job->slowDuration = slowDuration; job->added_time = time(NULL); job->machines = new int32_t[k]; jobs.insert(job); TryToAllocate(); mtx.unlock(); } void FreeResources(const std::set<int32_t> & machines) { mtx.lock(); cout << "FreeResources\n"; // free resources cout << "Free slaves: "; for (std::set<int32_t>::iterator it = machines.begin(); it != machines.end(); ++it) { int32_t j = 0; for (int32_t i = 0; i < (int32_t)free_racks.size(); i++) { j += (int32_t)(free_racks[i].size() + used_racks[i].size()); if (*it < j) { vector<int32_t>::iterator it2 = find(used_racks[i].begin(), used_racks[i].end(), *it); if (it2 == used_racks[i].end()) cout << "ERROR: Trying to free resource that isnt allocated\n"; else { used_racks[i].erase(it2); free_racks[i].push_back(*it); free_machines++; } break; } } cout << *it << ", "; } cout << "\n"; TryToAllocate(); mtx.unlock(); } }; int main(int argc, char **argv) { //create a listening server socket int alschedport = 9091; char *config_file = NULL; if (argc == 2) config_file = argv[1]; else if (argc == 3) config_file = argv[2]; else printf("ERROR: no config file\n"); boost::shared_ptr<TetrischedServiceHandler> handler(new TetrischedServiceHandler(config_file)); boost::shared_ptr<TProcessor> processor(new TetrischedServiceProcessor(handler)); boost::shared_ptr<TServerTransport> serverTransport(new TServerSocket(alschedport)); boost::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory()); boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory()); TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory); server.serve(); return 0; }
41.388797
152
0.429049
[ "vector" ]
d115fc166b8c3cef0f1996ae2408c7c5bedb6c97
6,585
cpp
C++
code/WPILib/CInterfaces/CJoystick.cpp
trc492/Frc2011Logomotion
c0cf25c21acdf2eb965e60291955f9e3080eb319
[ "MIT" ]
null
null
null
code/WPILib/CInterfaces/CJoystick.cpp
trc492/Frc2011Logomotion
c0cf25c21acdf2eb965e60291955f9e3080eb319
[ "MIT" ]
null
null
null
code/WPILib/CInterfaces/CJoystick.cpp
trc492/Frc2011Logomotion
c0cf25c21acdf2eb965e60291955f9e3080eb319
[ "MIT" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ /*----------------------------------------------------------------------------*/ #include "Joystick.h" #include "CJoystick.h" static Joystick *joysticks[4]; static bool initialized = false; /** * Get the joystick associated with a port. * An internal function that will return the joystick object associated with a given * joystick port number. On the first call, all four joysticks are preallocated. * * @param port The joystick (USB) port number */ static Joystick *getJoystick(UINT32 port) { if (!initialized) { for (int i = 0; i < 4; i++) { joysticks[i] = new Joystick(i+1); } initialized = true; } if (port < 1 || port > 4) return NULL; return joysticks[port - 1]; } /** * Get the channel currently associated with the specified axis. * * @param port The USB port for this joystick. * @param axis The axis to look up the channel for. * @return The channel fr the axis. */ UINT32 GetAxisChannel(UINT32 port, AxisType axis) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetAxisChannel((Joystick::AxisType) axis); } /** * Set the channel associated with a specified axis. * * @param port The USB port for this joystick. * @param axis The axis to set the channel for. * @param channel The channel to set the axis to. */ void SetAxisChannel(UINT32 port, AxisType axis, UINT32 channel) { Joystick *stick = getJoystick(port); if (stick == NULL) return; stick->SetAxisChannel((Joystick::AxisType) axis, channel); } /** * Get the X value of the joystick. * This depends on the mapping of the joystick connected to the current port. * * @param port The USB port for this joystick. */ float GetX(UINT32 port, JoystickHand hand) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetX((Joystick::JoystickHand) hand); } /** * Get the Y value of the joystick. * This depends on the mapping of the joystick connected to the current port. * * @param port The USB port for this joystick. */ float GetY(UINT32 port, JoystickHand hand) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetY((Joystick::JoystickHand) hand); } /** * Get the Z value of the current joystick. * This depends on the mapping of the joystick connected to the current port. * * @param port The USB port for this joystick. */ float GetZ(UINT32 port) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetZ(); } /** * Get the twist value of the current joystick. * This depends on the mapping of the joystick connected to the current port. * * @param port The USB port for this joystick. */ float GetTwist(UINT32 port) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetTwist(); } /** * Get the throttle value of the current joystick. * This depends on the mapping of the joystick connected to the current port. * * @param port The USB port for this joystick. */ float GetThrottle(UINT32 port) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetThrottle(); } /** * For the current joystick, return the axis determined by the argument. * * This is for cases where the joystick axis is returned programatically, otherwise one of the * previous functions would be preferable (for example GetX()). * * @param port The USB port for this joystick. * @param axis The axis to read. * @return The value of the axis. */ float GetAxis(UINT32 port, AxisType axis) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetAxis((Joystick::AxisType) axis); } /** * Get the value of the axis. * * @param port The USB port for this joystick. * @param axis The axis to read [1-6]. * @return The value of the axis. */ float GetRawAxis(UINT32 port, UINT32 axis) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetRawAxis(axis); } /** * Read the state of the trigger on the joystick. * * Look up which button has been assigned to the trigger and read its state. * * @param port The USB port for this joystick. * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. * @return The state of the trigger. */ bool GetTrigger(UINT32 port, JoystickHand hand) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetTrigger((Joystick::JoystickHand) hand); } /** * Read the state of the top button on the joystick. * * Look up which button has been assigned to the top and read its state. * * @param port The USB port for this joystick. * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. * @return The state of the top button. */ bool GetTop(UINT32 port, JoystickHand hand) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetTop((Joystick::JoystickHand) hand); } /** * This is not supported for the Joystick. * This method is only here to complete the GenericHID interface. * * @param port The USB port for this joystick. */ bool GetBumper(UINT32 port, JoystickHand hand) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetBumper((Joystick::JoystickHand) hand); } /** * Get buttons based on an enumerated type. * * The button type will be looked up in the list of buttons and then read. * * @param port The USB port for this joystick. * @param button The type of button to read. * @return The state of the button. */ bool GetButton(UINT32 port, ButtonType button) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetButton((Joystick::ButtonType) button); } /** * Get the button value for buttons 1 through 12. * * The buttons are returned in a single 16 bit value with one bit representing the state * of each button. The appropriate button is returned as a boolean value. * * @param port The USB port for this joystick. * @param button The button number to be read. * @return The state of the button. **/ bool GetRawButton(UINT32 port, UINT32 button) { Joystick *stick = getJoystick(port); if (stick == NULL) return 0; return stick->GetRawButton(button); }
27.668067
118
0.689749
[ "object" ]
d11e13c4f58da8a9210661eee846b9a034780d60
7,716
hpp
C++
core/commands/output/get_all_partitions.hpp
wickedb/LSOracle
ec2df3a3c9c1cc3b1c2dd7ca4dc7a52285781110
[ "MIT" ]
19
2020-12-09T21:09:29.000Z
2021-12-14T08:40:01.000Z
core/commands/output/get_all_partitions.hpp
wickedb/LSOracle
ec2df3a3c9c1cc3b1c2dd7ca4dc7a52285781110
[ "MIT" ]
28
2021-02-18T22:09:38.000Z
2022-03-09T08:08:14.000Z
core/commands/output/get_all_partitions.hpp
wickedb/LSOracle
ec2df3a3c9c1cc3b1c2dd7ca4dc7a52285781110
[ "MIT" ]
15
2021-02-26T17:10:24.000Z
2022-03-26T12:41:45.000Z
/* LSOracle: A learning based Oracle for Logic Synthesis * MIT License * Copyright 2019 Laboratory for Nano Integrated Systems (LNIS) * * 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 <alice/alice.hpp> #include <mockturtle/mockturtle.hpp> #include <stdio.h> #include <fstream> #include <sys/stat.h> #include <stdlib.h> #include <filesystem> namespace alice { class get_all_partitions_command : public alice::command { public: explicit get_all_partitions_command(const environment::ptr &env) : command(env, "Exports every partition to Verilog files") { opts.add_option("--directory,directory", dir, "Directory to write Verilog files to")->required(); // add_flag("--cone,-c", "Writes out every cone of every partition"); // add_flag("--verilog,-v", "Writes every partition or cone to a verilog file"); add_flag("--mig,-m", "Write out all of the partitions of the sored MIG network"); } protected: void execute() { mockturtle::mig_npn_resynthesis resyn_mig; mockturtle::xag_npn_resynthesis<mockturtle::aig_network> resyn_aig; if (is_set("mig")) { if (!store<mig_ntk>().empty()) { auto ntk = *store<mig_ntk>().current(); env->out() << "\n"; if (!store<part_man_mig_ntk>().empty()) { auto partitions = *store<part_man_mig_ntk>().current(); for (int i = 0; i < partitions.get_part_num(); i++) { std::vector<mockturtle::mig_network> parts; std::vector<std::string> filenames; int partition = i; auto part_outputs = partitions.get_part_outputs(i); env->out() << "Partition " << i << ":\n"; env->out() << "Number of Logic Cones = " << part_outputs.size() << "\n"; mkdir(dir.c_str(), 0777); oracle::partition_view<mig_names> part = partitions.create_part(ntk, partition); auto part_ntk = mockturtle::node_resynthesis<mockturtle::mig_network>(part, resyn_mig); std::string filename = dir + "/" + ntk._storage->_network_name + "_" + std::to_string(partition) + ".v";; filenames.push_back(filename); parts.push_back(part_ntk); assert(parts.size() == filenames.size()); for (int j = 0; j < parts.size(); j++) { mockturtle::write_verilog(parts.at(j), filenames.at(j)); } env->out() << "\n"; } } else { env->err() << "Partitions have not been mapped\n"; } } else { env->err() << "There is no MIG network stored\n"; } } else { if (!store<aig_ntk>().empty()) { auto ntk = *store<aig_ntk>().current(); env->out() << "\n"; if (!store<part_man_aig_ntk>().empty()) { mockturtle::write_verilog_params ps; auto partitions = *store<part_man_aig_ntk>().current(); mockturtle::node_map<std::string, aig_names> node_names(ntk); mockturtle::node_map<std::string, aig_names> input_names(ntk); std::string toplevel_module = std::filesystem::path( ntk._storage->_network_name).filename(); std::string toplevel_file = dir + "/" + toplevel_module + ".v"; for (int i = 0; i < partitions.get_part_num(); i++) { std::vector<mockturtle::aig_network> parts; std::vector<std::string> filenames; int partition = i; auto part_outputs = partitions.get_part_outputs(i); env->out() << "Partition " << i << ":\n"; env->out() << "Number of Logic Cones = " << part_outputs.size() << "\n"; mkdir(dir.c_str(), 0777); oracle::partition_view<aig_names> part = partitions.create_part(ntk, partition); auto part_ntk = mockturtle::node_resynthesis<aig_names>(part, resyn_aig); std::string modulename = std::filesystem::path(ntk._storage->_network_name + "_" + std::to_string(partition)).filename(); std::string filename = dir + "/" + modulename + ".v"; filenames.push_back(filename); parts.push_back(part_ntk); if (part_ntk.num_pos() == 0) continue; assert(parts.size() == filenames.size()); for (int j = 0; j < parts.size(); j++) { ps.module_name = modulename; mockturtle::write_verilog(parts.at(j), filenames.at(j), ps); } if (i == 0) //to do: write_toplevel_verilog has been removed along with the rest of the duplicate write_verilog method because it was not // compatible with the newest version of mockturtle. We'll want it back, but for now I'm disabling this feature oracle::write_toplevel_verilog(ntk, partitions, toplevel_file, node_names, input_names, toplevel_module); //to do: see above, but for call_submodule oracle::call_submodule(ntk, part_ntk, toplevel_file, modulename, i, part, node_names, input_names); env->out() << "\n"; } std::ofstream os(toplevel_file.c_str(), std::ofstream::app); os << "endmodule\n" << std::flush; os.close(); } else { env->err() << "Partitions have not been mapped\n"; } } else { env->err() << "There is no AIG network stored\n"; } } } private: std::string dir{}; }; ALICE_ADD_COMMAND(get_all_partitions, "Output"); }
46.203593
153
0.518403
[ "vector" ]
d120f59d7e4f289b178b38bf4f7c803ecf91019e
1,333
cpp
C++
leetcode/322.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
leetcode/322.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
leetcode/322.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
// // Created by 赖於领 on 2021/9/14. // #include <string> #include <iostream> #include <vector> using namespace std; //零钱兑换 class Solution { public: int coinChange(vector<int> &coins, int amount) { if (amount == 0) { return 0; } sort(coins.begin(), coins.end()); if (coins[0] > amount) { return -1; } vector<int> _min(amount + 1, INT_MAX); int n = coins.size(); _min[0] = 0; _min[*coins.begin()] = 1; for (int i = *coins.begin() + 1; i <= amount; ++i) { for (int j = 0; j < n; ++j) { if (coins[j] > i) { break; } if (_min[i - coins[j]] == INT_MAX) { continue; } _min[i] = min(_min[i], _min[i - coins[j]] + 1); } } if (_min[amount] == INT_MAX) { return -1; } else { return _min[amount]; } } }; int main() { Solution *solution = new Solution(); // vector<int> aa = {1, 2, 5}; // cout << solution->coinChange(aa, 11) << endl; // vector<int> aa = {2}; // cout << solution->coinChange(aa, 1) << endl; vector<int> aa = {474,83,404,3}; cout << solution->coinChange(aa, 264) << endl; return 0; }
22.982759
63
0.43886
[ "vector" ]
d122998a661ff41d405b9bdd41afa1ece60bf46b
19,154
hh
C++
EnergyPlus/IceThermalStorage.hh
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
EnergyPlus/IceThermalStorage.hh
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
1
2020-07-08T13:32:09.000Z
2020-07-08T13:32:09.000Z
EnergyPlus/IceThermalStorage.hh
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
// EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois, // 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), Oak Ridge // National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other // contributors. All rights reserved. // // NOTICE: This Software was developed under funding from the U.S. Department of Energy and the // U.S. Government consequently retains certain rights. 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, distribute copies to the public, prepare // derivative works, and perform publicly and display publicly, and to permit others to do so. // // 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, // the University of Illinois, 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. // // (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form // without changes from the version obtained under this License, or (ii) Licensee makes a // reference solely to the software portion of its product, Licensee must refer to the // software as "EnergyPlus version X" software, where "X" is the version number Licensee // obtained under this License and may not use a different name for the software. Except as // specifically required in this Section (4), Licensee shall not use in a company name, a // product name, in advertising, publicity, or other promotional activities any name, trade // name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly // similar designation, without the U.S. Department of Energy's prior written consent. // // 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. #ifndef IceThermalStorage_hh_INCLUDED #define IceThermalStorage_hh_INCLUDED // ObjexxFCL Headers #include <ObjexxFCL/Array1D.hh> // EnergyPlus Headers #include <DataGlobals.hh> #include <EnergyPlus.hh> namespace EnergyPlus { namespace IceThermalStorage { // Using/Aliasing // Data // MODULE PARAMETER DEFINITIONS extern std::string const cIceStorageSimple; extern std::string const cIceStorageDetailed; extern int const IceStorageType_Simple; extern int const IceStorageType_Detailed; extern int const CurveType_QuadraticLinear; extern int const CurveType_CubicLinear; extern int const DetIceInsideMelt; // Inside melt system--charge starting with bare coil extern int const DetIceOutsideMelt; // Outside melt system--charge from existing ice layer on coil // ITS parameter extern Real64 const FreezTemp; // Water freezing Temperature, 0[C] extern Real64 const FreezTempIP; // Water freezing Temperature, 32[F] extern Real64 const TimeInterval; // Time Interval (1 hr) [s] extern int const ITSType_IceOnCoilInternal; extern int const ITSType_IceOnCoilExternal; // Conversion parameter extern Real64 const EpsLimitForX; // 0.02 ! See Dion's code as eps1 extern Real64 const EpsLimitForDisCharge; // 0.20 ! See Dion's code as eps2 extern Real64 const EpsLimitForCharge; // 0.20 ! See Dion's code as eps3 // variable used by simple model extern Real64 const Delta; extern Real64 const PLRmin; extern Real64 const Pa; extern Real64 const Pb; extern Real64 const Pc; extern Real64 const Tref; // F extern Real64 const Tcharge; // F extern Real64 const Tdischarge; // F // Parameter used by the Detailed Ice Storage Model extern Real64 const DeltaTofMin; // Minimum allowed outlet side temperature difference [C] // This is (Tout - Tfreezing) extern Real64 const DeltaTifMin; // Minimum allowed inlet side temperature difference [C] // This is (Tin - Tfreezing) // DERIVED TYPE DEFINITIONS // TYPE ITSSetCap is used for information of ITS plant in Loop, Brach, and Components. // TYPE ITSSetCapData // LOGICAL :: ITSFlag = .FALSE. // INTEGER :: LoopNum =0 // INTEGER :: BranchNum =0 // INTEGER :: CompNum =0 // END TYPE ITSSetCapData // TYPE (ITSSetCapData), SAVE :: ITSSetCap=ITSSetCapData(.FALSE.,0,0,0) // MODULE VARIABLE DECLARATIONS: extern bool ResetXForITSFlag; // Input data extern Real64 ITSNomCap; // Design nominal capacity of Ice Thermal Storage [J] (user input in GJ) extern int InletNodeNum; // Node number on the inlet side of the plant extern int OutletNodeNum; // Node number on the inlet side of the plant // ITS numbers and FoundOrNot extern int IceNum; extern int NumIceStorages; extern bool IceStorageNotFound; extern int NumDetIceStorages; extern int TotalIceStorages; // ITS UAice and HLoss extern Real64 UAIceCh; // Charging Ice Thermal Storage overall heat transfer coefficient [W/C] extern Real64 UAIceDisCh; // Discharging Ice Thermal Storage overall heat transfer coefficient [W/C] extern Real64 HLoss; // ITS Heat Loss // ITS State extern Real64 XCurIceFrac; // Current Fraction of Ice Thermal Storage remaining [fraction] extern Real64 U; // Adjusted input U after reading U Schedule [fraction] extern Real64 Urate; // Final Urate adjusted Urate based on Error protection (I) [fraction] by HOUR // ITS status information extern Real64 ITSMassFlowRate; // ITS water mass flow rate [kg/s] extern Real64 ITSInletTemp; // ITS inlet water temperature [C] extern Real64 ITSOutletTemp; // ITS outlet water temperature [C] extern Real64 ITSOutletSetPointTemp; // ITS outlet water temperature setpoint [C] extern Real64 ITSCoolingRate; // ITS Discharge(-)/Charge(+) rate [W] extern Real64 ITSCoolingEnergy; extern Real64 ChillerOutletTemp; // Chiller outlet brine temperature [C] extern Array1D_bool CheckEquipName; // SUBROUTINE SPECIFICATIONS FOR MODULE // General routine // Types struct IceStorageMapping { // Members // Input data std::string Name; // User identifier std::string StorageType; int StorageType_Num; int LocalEqNum; // Default Constructor IceStorageMapping() : StorageType_Num(0), LocalEqNum(0) { } }; struct IceStorageSpecs { // Members // Input data std::string Name; // User identifier std::string ITSType; // Ice Thermal Storage Type int ITSType_Num; // Storage Type as number (IceOnCoilInternal,IceOnCoilExternal) int MapNum; // Number to Map structure int UratePtr; // Charging/Discharging SchedulePtr: u value schedule Real64 ITSNomCap; // Design nominal capacity of Ice Thermal Storage [J] (user input in GJ) int PltInletNodeNum; // Node number on the inlet side of the plant int PltOutletNodeNum; // Node number on the outlet side of the plant // loop topology variables int LoopNum; int LoopSideNum; int BranchNum; int CompNum; Real64 DesignMassFlowRate; // Default Constructor IceStorageSpecs() : ITSType_Num(0), MapNum(0), UratePtr(0), ITSNomCap(0.0), PltInletNodeNum(0), PltOutletNodeNum(0), LoopNum(0), LoopSideNum(0), BranchNum(0), CompNum(0), DesignMassFlowRate(0.0) { } }; struct DetailedIceStorageData { // Members // Input data std::string Name; // User identifier std::string ScheduleName; // User identifier int ScheduleIndex; // Plant inlet node number for ice storage unit Real64 NomCapacity; // Design storage capacity of Ice Thermal Storage system [W-hr] // (User input for this parameter in GJ--need to convert to W-hr) int PlantInNodeNum; // Plant inlet node number for ice storage unit int PlantOutNodeNum; // Plant outlet node number for ice storage unit int PlantLoopNum; int PlantLoopSideNum; int PlantBranchNum; int PlantCompNum; Real64 DesignMassFlowRate; int MapNum; // Number to Map structure std::string DischargeCurveName; // Curve name for discharging (used to find the curve index) int DischargeCurveNum; // Curve index for discharging int DischargeCurveTypeNum; // Integer version of discharging curve type std::string ChargeCurveName; // Curve name for charging (used to find the curve index) int ChargeCurveNum; // Curve index for charging int ChargeCurveTypeNum; // Integer version of charging curve type Real64 CurveFitTimeStep; // Time step used to generate performance data [hours] Real64 DischargeParaElecLoad; // Parasitic electric load duing discharging [dimensionless] // (This is multiplied by the tank capacity to obtain elec consump) Real64 ChargeParaElecLoad; // Parasitic electric load duing charging [dimensionless] // (This is multiplied by the tank capacity to obtain elec consump) Real64 TankLossCoeff; // Fraction of total storage capacity lost per hour [1/hours] Real64 FreezingTemp; // Freezing/melting temperature of ice storage unit [C] // Reporting data Real64 CompLoad; // load requested by plant [W] Real64 IceFracChange; // Change in fraction of ice stored during the time step [fraction] Real64 IceFracRemaining; // Fraction of ice remaining in storage [fraction] std::string ThawProcessIndicator; // User input determining whether system is inside or outside melt int ThawProcessIndex; // Conversion of thaw process indicator to integer index Real64 IceFracOnCoil; // Fraction of ice on the coil (affects charging) [fraction] Real64 DischargingRate; // Rate at which energy is being added (thawing) to ice unit [W] Real64 DischargingEnergy; // Total energy added to the ice storage unit [J] Real64 ChargingRate; // Rate at which energy is removed (freezing) to ice unit [W] Real64 ChargingEnergy; // Total energy removed from ice storage unit [J] Real64 MassFlowRate; // Total mass flow rate to component [kg/s] Real64 BypassMassFlowRate; // Mass flow rate that bypasses the ice unit locally [kg/s] Real64 TankMassFlowRate; // Mass flow rate through the ice storage unit [kg/s] Real64 InletTemp; // Component inlet temperature (same as bypass temperature) [C] Real64 OutletTemp; // Component outlet temperature (blended) [C] Real64 TankOutletTemp; // Ice storage unit outlet temperature [C] Real64 ParasiticElecRate; // Parasitic electrical energy rate consumed by ice storage [W] Real64 ParasiticElecEnergy; // Total parasitic electrical energy consumed by ice storage [J] int DischargeIterErrors; // Number of max iterations exceeded errors during discharging int DischargeErrorCount; // Index for error counting routine int ChargeIterErrors; // Number of max iterations exceeded errors during charging int ChargeErrorCount; // Index for error counting routine // Default Constructor DetailedIceStorageData() : ScheduleIndex(0), NomCapacity(0.0), PlantInNodeNum(0), PlantOutNodeNum(0), PlantLoopNum(0), PlantLoopSideNum(0), PlantBranchNum(0), PlantCompNum(0), DesignMassFlowRate(0.0), MapNum(0), DischargeCurveNum(0), ChargeCurveNum(0), CurveFitTimeStep(1.0), DischargeParaElecLoad(0.0), ChargeParaElecLoad(0.0), TankLossCoeff(0.0), FreezingTemp(0.0), CompLoad(0.0), IceFracChange(0.0), IceFracRemaining(1.0), ThawProcessIndex(0), IceFracOnCoil(1.0), DischargingRate(0.0), DischargingEnergy(0.0), ChargingRate(0.0), ChargingEnergy(0.0), MassFlowRate(0.0), BypassMassFlowRate(0.0), TankMassFlowRate(0.0), InletTemp(0.0), OutletTemp(0.0), TankOutletTemp(0.0), ParasiticElecRate(0.0), ParasiticElecEnergy(0.0), DischargeIterErrors(0), DischargeErrorCount(0), ChargeIterErrors(0), ChargeErrorCount(0) { } }; struct ReportVars { // Members Real64 MyLoad; // load requested by plant [W] Real64 U; // [fraction] Real64 Urate; // [fraction] Real64 IceFracRemain; // Fraction of ice remaining in storage [fraction] Real64 ITSCoolingRate; // [W] Real64 ITSCoolingEnergy; // [J] Real64 ITSChargingRate; // [W] Real64 ITSChargingEnergy; // [J] Real64 ITSmdot; // [kg/s] Real64 ITSInletTemp; // [C] Real64 ITSOutletTemp; // [C] // Default Constructor ReportVars() : MyLoad(0.0), U(0.0), Urate(0.0), IceFracRemain(0.0), ITSCoolingRate(0.0), ITSCoolingEnergy(0.0), ITSChargingRate(0.0), ITSChargingEnergy(0.0), ITSmdot(0.0), ITSInletTemp(0.0), ITSOutletTemp(0.0) { } }; // Object Data extern Array1D<IceStorageSpecs> IceStorage; // dimension to number of machines extern Array1D<ReportVars> IceStorageReport; // dimension to number of machines extern Array1D<DetailedIceStorageData> DetIceStor; // Derived type for detailed ice storage model extern Array1D<IceStorageMapping> IceStorageTypeMap; // Functions void SimIceStorage(std::string const &IceStorageType, std::string const &IceStorageName, int &CompIndex, bool const RunFlag, bool const FirstIteration, bool const InitLoopEquip, Real64 &MyLoad); void SimDetailedIceStorage(); //****************************************************************************** void GetIceStorageInput(); //****************************************************************************** void InitDetailedIceStorage(); void InitSimpleIceStorage(); //****************************************************************************** void CalcIceStorageCapacity(int const IceStorageType, Real64 &MaxCap, Real64 &MinCap, Real64 &OptCap); //****************************************************************************** void CalcIceStorageDormant(int const IceStorageType, // BY ZG int &IceNum); //****************************************************************************** void CalcIceStorageCharge(int const IceStorageType, // BY ZG int &IceNum); //****************************************************************************** void CalcQiceChargeMaxByChiller(int &IceNum, Real64 &QiceMaxByChiller); //****************************************************************************** void CalcQiceChargeMaxByITS(int &IceNum, Real64 const ChillerOutletTemp, // [degC] Real64 &QiceMaxByITS // [W] ); //****************************************************************************** void CalcIceStorageDischarge(int const IceStorageType, // by ZG int const IceNum, // ice storage number Real64 const MyLoad, // operating load bool const RunFlag, // TRUE when ice storage operating bool const FirstIteration, // TRUE when first iteration of timestep Real64 const MaxCap // Max possible discharge rate (positive value) ); //****************************************************************************** void CalcQiceDischageMax(Real64 &QiceMin); //****************************************************************************** void CalcUAIce(int const IceNum, Real64 const XCurIceFrac, Real64 &UAIceCh, Real64 &UAIceDisCh, Real64 &HLoss); Real64 CalcDetIceStorLMTDstar(Real64 const Tin, // ice storage unit inlet temperature Real64 const Tout, // ice storage unit outlet (setpoint) temperature Real64 const Tfr // freezing temperature ); // ***************************************************************************** Real64 TempSItoIP(Real64 const Temp); // ***************************************************************************** Real64 TempIPtoSI(Real64 const Temp); // ***************************************************************************** void UpdateNode(Real64 const MyLoad, bool const RunFlag, int const Num); // ***************************************************************************** void RecordOutput(int const IceNum, Real64 const MyLoad, bool const RunFlag); // ***************************************************************************** void UpdateIceFractions(); void UpdateDetailedIceStorage(); void ReportDetailedIceStorage(); } // namespace IceThermalStorage } // namespace EnergyPlus #endif
49.112821
145
0.621646
[ "object", "model" ]
d12f5ac2e61dfbfc62e5dc46141859156ba1f461
3,207
cc
C++
test/cpp/end2end/delegating_channel_test.cc
echo80313/grpc
93cdc8b77e7b3fe4a3afec1c9c7e29b3f02ec3cf
[ "Apache-2.0" ]
null
null
null
test/cpp/end2end/delegating_channel_test.cc
echo80313/grpc
93cdc8b77e7b3fe4a3afec1c9c7e29b3f02ec3cf
[ "Apache-2.0" ]
4
2022-02-27T18:59:37.000Z
2022-02-27T18:59:53.000Z
test/cpp/end2end/delegating_channel_test.cc
echo80313/grpc
93cdc8b77e7b3fe4a3afec1c9c7e29b3f02ec3cf
[ "Apache-2.0" ]
null
null
null
/* * * 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 <memory> #include <vector> #include <gtest/gtest.h> #include <grpcpp/channel.h> #include <grpcpp/client_context.h> #include <grpcpp/create_channel.h> #include <grpcpp/generic/generic_stub.h> #include <grpcpp/impl/codegen/delegating_channel.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_interceptor.h> #include "src/proto/grpc/testing/echo.grpc.pb.h" #include "test/core/util/port.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" namespace grpc { namespace testing { namespace { class TestChannel : public experimental::DelegatingChannel { public: explicit TestChannel( const std::shared_ptr<ChannelInterface>& delegate_channel) : experimental::DelegatingChannel(delegate_channel) {} // Always returns GRPC_CHANNEL_READY grpc_connectivity_state GetState(bool /*try_to_connect*/) override { return GRPC_CHANNEL_READY; } }; class DelegatingChannelTest : public ::testing::Test { protected: DelegatingChannelTest() { int port = grpc_pick_unused_port_or_die(); ServerBuilder builder; server_address_ = "localhost:" + std::to_string(port); builder.AddListeningPort(server_address_, InsecureServerCredentials()); builder.RegisterService(&service_); server_ = builder.BuildAndStart(); } ~DelegatingChannelTest() override { server_->Shutdown(); } std::string server_address_; TestServiceImpl service_; std::unique_ptr<Server> server_; }; TEST_F(DelegatingChannelTest, SimpleTest) { auto channel = CreateChannel(server_address_, InsecureChannelCredentials()); std::shared_ptr<TestChannel> test_channel = std::make_shared<TestChannel>(channel); // gRPC channel should be in idle state at this point but our test channel // will return ready. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE); EXPECT_EQ(test_channel->GetState(false), GRPC_CHANNEL_READY); auto stub = grpc::testing::EchoTestService::NewStub(test_channel); ClientContext ctx; EchoRequest req; req.set_message("Hello"); EchoResponse resp; Status s = stub->Echo(&ctx, req, &resp); EXPECT_EQ(s.ok(), true); EXPECT_EQ(resp.message(), "Hello"); } } // namespace } // namespace testing } // namespace grpc int main(int argc, char** argv) { grpc::testing::TestEnvironment env(&argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
31.441176
78
0.746492
[ "vector" ]
d131871166670fd05dc37efa65fa732ae4e56432
3,478
cpp
C++
src/DropedItem.cpp
Kirthos/Aerria
ec9eb6c78690838ba5a3509369e2c4d8428b4dc2
[ "MIT" ]
null
null
null
src/DropedItem.cpp
Kirthos/Aerria
ec9eb6c78690838ba5a3509369e2c4d8428b4dc2
[ "MIT" ]
null
null
null
src/DropedItem.cpp
Kirthos/Aerria
ec9eb6c78690838ba5a3509369e2c4d8428b4dc2
[ "MIT" ]
null
null
null
#include "../include/DropedItem.hpp" #include "../include/World.hpp" DropedItem::DropedItem(World* t_world, GlobalSys* t_ressourceBox, Item t_matchingItem) : Entity(t_world,t_ressourceBox) { m_matchingItem = t_matchingItem; distanceItemRepere = 10; m_attractSpeed = 5; m_sprite.setTexture(*t_ressourceBox->requestTexture("tileset.png",sf::IntRect(32*m_matchingItem.getID(),0,32,32))); m_sprite.setScale(0.5,0.5); m_hitbox.setTaille(sf::Vector2f(0,0)); m_world = t_world; distanceAttract = 200; m_speed = 15; m_veille = false; m_isAttract = false; m_temp = false; } DropedItem::DropedItem(World* t_world, GlobalSys* t_ressourceBox) : Entity(t_world,t_ressourceBox) { distanceItemRepere = 10; m_attractSpeed = 5; m_sprite.setScale(0.5,0.5); m_hitbox.setTaille(sf::Vector2f(0,0)); m_world = t_world; distanceAttract = 200; m_speed = 15; } void DropedItem::update() { if(m_alive) { if(m_toucheSol) m_veille = true; if(m_world->getPerso()->getClicked()) m_veille = false; if(!m_veille) processGravity(); attract(); if(!m_veille) { Move(); m_sprite.setPosition(m_pos.x,m_pos.y); if(m_lifeTime.getElapsedTime().asSeconds()>180) { m_alive = false; } } } } void DropedItem::render() { sf::RenderWindow& mWindow = Window::getWindow(); if(m_alive) mWindow.draw(m_sprite); } Item DropedItem::pickUp() { return m_matchingItem; } void DropedItem::Move() { m_pos.x += m_deplacement.x; if(m_toucheSol) { m_pos.y += m_deplacement.y; if(!checkCollisionSol() || m_pos.y > m_world->getLevel()->getHauteur()*32-200 || m_pos.y < 116) { m_pos.y -= m_deplacement.y; m_deplacement.y = 0; m_toucheSol = true; } else { m_toucheSol = false; } } else { m_pos.y += m_deplacement.y; if(!m_isAttract) { if(!checkCollisionSol() || m_pos.y > m_world->getLevel()->getHauteur()*32-200 || m_pos.y < 116) { m_pos.y -= m_deplacement.y; m_deplacement.y = 0; m_toucheSol = true; } else { m_toucheSol = false; } } } } void DropedItem::attract() { sf::Vector2f t_attractTarget = m_world->getPerso()->getPosition(); t_attractTarget.x +=32; t_attractTarget.y +=48; if(abs(t_attractTarget.x - m_pos.x)<distanceAttract && abs(t_attractTarget.y - m_pos.y)<distanceAttract) { m_veille = false; m_isAttract = true; if(t_attractTarget.x < m_pos.x) m_deplacement.x = -m_speed; else m_deplacement.x = m_speed; if(t_attractTarget.y < m_pos.y) m_deplacement.y = -m_speed; else m_deplacement.y = m_speed; if(abs(t_attractTarget.x - m_pos.x)<m_speed && abs(t_attractTarget.y - m_pos.y)<m_speed) { m_world->getPerso()->getInventory().addItem(pickUp()); m_alive = false; } } else { m_deplacement.x = 0; m_isAttract = false; } } void DropedItem::setItem(Item t_matchingItem) { m_matchingItem = t_matchingItem; }
25.955224
119
0.557217
[ "render" ]
d133e12db1901cb33a1fe78d2deb052c0127b38e
13,845
cc
C++
arc/keymaster/keymaster_server.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
arc/keymaster/keymaster_server.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
arc/keymaster/keymaster_server.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "arc/keymaster/keymaster_server.h" #include <utility> #include <base/bind.h> #include <base/threading/platform_thread.h> #include <base/threading/thread_task_runner_handle.h> #include <keymaster/android_keymaster_messages.h> #include "arc/keymaster/conversion.h" // The implementations of |arc::mojom::KeymasterServer| methods below have the // following overall pattern: // // * Generate an std::unique_ptr to a Keymaster request data structure from the // arguments received from Mojo, usually through the helpers in conversion.h. // // * Execute the operation in |backend->keymaster()|, posting this task to a // background thread. This produces a Keymaster response data structure. // // * Post the response to a callback that runs on the original thread (in this // case, the Mojo thread where the request started). // // * Convert the Keymaster response to the Mojo return values, and run the // result callback. // namespace arc { namespace keymaster { namespace { constexpr size_t kOperationTableSize = 16; } // namespace KeymasterServer::Backend::Backend() : context_(new context::ArcKeymasterContext()), keymaster_(context_, kOperationTableSize) {} KeymasterServer::Backend::~Backend() = default; KeymasterServer::KeymasterServer() : backend_thread_("BackendKeymasterThread") { CHECK(backend_thread_.Start()) << "Failed to start keymaster thread"; } KeymasterServer::~KeymasterServer() = default; void KeymasterServer::SetSystemVersion(uint32_t os_version, uint32_t os_patchlevel) { backend_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce( [](context::ArcKeymasterContext* context, uint32_t os_version, uint32_t os_patchlevel) { // |context| is guaranteed valid here because it's owned // by |backend_|, which outlives the |backend_thread_| // this runs on. context->SetSystemVersion(os_version, os_patchlevel); }, backend_.context(), os_version, os_patchlevel)); } template <typename KmMember, typename KmRequest, typename KmResponse> void KeymasterServer::RunKeymasterRequest( const base::Location& location, KmMember member, std::unique_ptr<KmRequest> request, base::OnceCallback<void(std::unique_ptr<KmResponse>)> callback) { // Post the Keymaster operation to a background thread while capturing the // current task runner. backend_thread_.task_runner()->PostTask( location, base::BindOnce( [](const base::Location& location, scoped_refptr<base::TaskRunner> original_task_runner, ::keymaster::AndroidKeymaster* keymaster, KmMember member, std::unique_ptr<KmRequest> request, base::OnceCallback<void(std::unique_ptr<KmResponse>)> callback) { // Prepare a Keymaster response data structure. auto response = std::make_unique<KmResponse>(); // Execute the operation. (*keymaster.*member)(*request, response.get()); // Post |callback| to the |original_task_runner| given |response|. original_task_runner->PostTask( location, base::BindOnce(std::move(callback), std::move(response))); }, location, base::ThreadTaskRunnerHandle::Get(), backend_.keymaster(), member, std::move(request), std::move(callback))); } void KeymasterServer::AddRngEntropy(const std::vector<uint8_t>& data, AddRngEntropyCallback callback) { // Convert input |data| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = std::make_unique<::keymaster::AddEntropyRequest>(); ConvertToMessage(data, &km_request->random_data); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::AddRngEntropy, std::move(km_request), base::BindOnce( [](AddRngEntropyCallback callback, std::unique_ptr<::keymaster::AddEntropyResponse> km_response) { // Run callback. std::move(callback).Run(km_response->error); }, std::move(callback))); } void KeymasterServer::GetKeyCharacteristics( ::arc::mojom::GetKeyCharacteristicsRequestPtr request, GetKeyCharacteristicsCallback callback) { // Convert input |request| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = MakeGetKeyCharacteristicsRequest(request); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::GetKeyCharacteristics, std::move(km_request), base::BindOnce( [](GetKeyCharacteristicsCallback callback, std::unique_ptr<::keymaster::GetKeyCharacteristicsResponse> km_response) { // Prepare mojo response. auto response = MakeGetKeyCharacteristicsResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::GenerateKey( std::vector<mojom::KeyParameterPtr> key_params, GenerateKeyCallback callback) { // Convert input |key_params| into |km_request|. All data is deep copied to // avoid use-after-free. auto km_request = MakeGenerateKeyRequest(key_params); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::GenerateKey, std::move(km_request), base::BindOnce( [](GenerateKeyCallback callback, std::unique_ptr<::keymaster::GenerateKeyResponse> km_response) { // Prepare mojo response. auto response = MakeGenerateKeyResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::ImportKey(arc::mojom::ImportKeyRequestPtr request, ImportKeyCallback callback) { // Convert input |request| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = MakeImportKeyRequest(request); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::ImportKey, std::move(km_request), base::BindOnce( [](ImportKeyCallback callback, std::unique_ptr<::keymaster::ImportKeyResponse> km_response) { // Prepare mojo response. auto response = MakeImportKeyResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::ExportKey(arc::mojom::ExportKeyRequestPtr request, ExportKeyCallback callback) { // Convert input |request| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = MakeExportKeyRequest(request); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::ExportKey, std::move(km_request), base::BindOnce( [](ExportKeyCallback callback, std::unique_ptr<::keymaster::ExportKeyResponse> km_response) { // Prepare mojo response. auto response = MakeExportKeyResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::AttestKey(arc::mojom::AttestKeyRequestPtr request, AttestKeyCallback callback) { // Convert input |request| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = MakeAttestKeyRequest(request); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::AttestKey, std::move(km_request), base::BindOnce( [](AttestKeyCallback callback, std::unique_ptr<::keymaster::AttestKeyResponse> km_response) { // Prepare mojo response. auto response = MakeAttestKeyResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::UpgradeKey(arc::mojom::UpgradeKeyRequestPtr request, UpgradeKeyCallback callback) { // Convert input |request| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = MakeUpgradeKeyRequest(request); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::UpgradeKey, std::move(km_request), base::BindOnce( [](UpgradeKeyCallback callback, std::unique_ptr<::keymaster::UpgradeKeyResponse> km_response) { // Prepare mojo response. auto response = MakeUpgradeKeyResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::DeleteKey(const std::vector<uint8_t>& key_blob, DeleteKeyCallback callback) { // Convert input |key_blob| into |km_request|. All data is deep copied to // avoid use-after-free. auto km_request = std::make_unique<::keymaster::DeleteKeyRequest>(); km_request->SetKeyMaterial(key_blob.data(), key_blob.size()); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::DeleteKey, std::move(km_request), base::BindOnce( [](DeleteKeyCallback callback, std::unique_ptr<::keymaster::DeleteKeyResponse> km_response) { // Run callback. std::move(callback).Run(km_response->error); }, std::move(callback))); } void KeymasterServer::DeleteAllKeys(DeleteAllKeysCallback callback) { // Prepare keymaster request. auto km_request = std::make_unique<::keymaster::DeleteAllKeysRequest>(); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::DeleteAllKeys, std::move(km_request), base::BindOnce( [](DeleteAllKeysCallback callback, std::unique_ptr<::keymaster::DeleteAllKeysResponse> km_response) { // Run callback. std::move(callback).Run(km_response->error); }, std::move(callback))); } void KeymasterServer::Begin(arc::mojom::BeginRequestPtr request, BeginCallback callback) { // Convert input |request| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = MakeBeginOperationRequest(request); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::BeginOperation, std::move(km_request), base::BindOnce( [](BeginCallback callback, std::unique_ptr<::keymaster::BeginOperationResponse> km_response) { // Prepare mojo response. auto response = MakeBeginResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::Update(arc::mojom::UpdateRequestPtr request, UpdateCallback callback) { // Convert input |request| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = MakeUpdateOperationRequest(request); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::UpdateOperation, std::move(km_request), base::BindOnce( [](UpdateCallback callback, std::unique_ptr<::keymaster::UpdateOperationResponse> km_response) { // Prepare mojo response. auto response = MakeUpdateResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::Finish(arc::mojom::FinishRequestPtr request, FinishCallback callback) { // Convert input |request| into |km_request|. All data is deep copied to avoid // use-after-free. auto km_request = MakeFinishOperationRequest(request); // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::FinishOperation, std::move(km_request), base::BindOnce( [](FinishCallback callback, std::unique_ptr<::keymaster::FinishOperationResponse> km_response) { // Prepare mojo response. auto response = MakeFinishResult(*km_response); // Run callback. std::move(callback).Run(std::move(response)); }, std::move(callback))); } void KeymasterServer::Abort(uint64_t op_handle, AbortCallback callback) { // Prepare keymaster request. auto km_request = std::make_unique<::keymaster::AbortOperationRequest>(); km_request->op_handle = op_handle; // Call keymaster. RunKeymasterRequest( FROM_HERE, &::keymaster::AndroidKeymaster::AbortOperation, std::move(km_request), base::BindOnce( [](AbortCallback callback, std::unique_ptr<::keymaster::AbortOperationResponse> km_response) { // Run callback. std::move(callback).Run(km_response->error); }, std::move(callback))); } } // namespace keymaster } // namespace arc
37.827869
80
0.64507
[ "vector" ]
d13481e8f7fbbb89ba55a86999035683870af70f
3,263
hpp
C++
include/utils.hpp
bradleypowers/PlannerPDF
e154f305441c8891a5abe2522bdea107fe309234
[ "MIT" ]
38
2021-04-01T03:08:31.000Z
2022-03-30T21:48:48.000Z
include/utils.hpp
bradleypowers/PlannerPDF
e154f305441c8891a5abe2522bdea107fe309234
[ "MIT" ]
5
2021-09-14T21:02:23.000Z
2021-09-14T21:15:14.000Z
include/utils.hpp
bradleypowers/PlannerPDF
e154f305441c8891a5abe2522bdea107fe309234
[ "MIT" ]
8
2021-04-01T09:34:47.000Z
2021-09-14T19:03:00.000Z
// The MIT License (MIT) // // Copyright (c) 2015, 2016, 2017 Howard Hinnant // Copyright (c) 2016 Adrian Colomitchi // Copyright (c) 2017 Florian Dang // Copyright (c) 2017 Paul Thompson // Copyright (c) 2018, 2019 Tomasz Kamiński // Copyright (c) 2019 Jiangang Zhuang // // 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. // // Our apologies. When the previous paragraph was written, lowercase had not // yet been invented (that would involve another several millennia of // evolution). We did not mean to shout. #ifndef UTILS_HPP #define UTILS_HPP #include "hpdf.h" #include <iostream> #include <memory> enum PlannerTypes { PlannerTypes_Base, PlannerTypes_Day, PlannerTypes_Week, PlannerTypes_Month, PlannerTypes_Year, PlannerTypes_Main, }; const std::int64_t Remarkable_width_px = 1872; const std::int64_t Remarkable_height_px = 1404; // const std::int64_t Remarkable_width_px = 1404; // const std::int64_t Remarkable_height_px = 1872; const std::int64_t Remarkable_margin_width_px = 120; HPDF_REAL GetCenteredTextYPosition(HPDF_Page& page, std::string text, HPDF_REAL y_start, HPDF_REAL y_end); HPDF_REAL GetCenteredTextXPosition(HPDF_Page& page, std::string text, HPDF_REAL x_start, HPDF_REAL x_end); /** * @brief * A helper function to call the instance specific create thumbnail function * This is a little hacky and error prone as it relies on the caller to provide * the instance type. This might be helped by transitioning to std::any in the * base class to store the child objects instead of shared_ptrs to PlannerBase. * */ class PlannerBase; void CreateThumbnailCaller(HPDF_Doc& doc, HPDF_Page& page, HPDF_REAL x_start, HPDF_REAL y_start, HPDF_REAL x_stop, HPDF_REAL y_stop, PlannerTypes type, PlannerTypes object_type, std::shared_ptr<PlannerBase> object); #endif // UTILS_HPP
40.7875
80
0.671162
[ "object" ]
d134c151a9316967c6327b2288721348467f1bab
26,382
cpp
C++
src/tfr_mission_control/src/tfr_mission_control/mission_control.cpp
TrickfireRobotics/NasaRMC2019
b06e84970a541ee766b9a1fc8155092049595f87
[ "BSD-2-Clause" ]
11
2019-02-19T21:31:24.000Z
2021-06-10T04:59:25.000Z
src/tfr_mission_control/src/tfr_mission_control/mission_control.cpp
TrickfireRobotics/NasaRMC2019
b06e84970a541ee766b9a1fc8155092049595f87
[ "BSD-2-Clause" ]
3
2019-07-19T19:12:29.000Z
2021-03-27T21:26:12.000Z
src/tfr_mission_control/src/tfr_mission_control/mission_control.cpp
TrickfireRobotics/NasaRMC2019
b06e84970a541ee766b9a1fc8155092049595f87
[ "BSD-2-Clause" ]
15
2019-02-19T21:40:05.000Z
2021-06-27T22:06:52.000Z
#include "tfr_mission_control/mission_control.h" #include <pluginlib/class_list_macros.h> namespace tfr_mission_control { /* ========================================================================== */ /* Constructor/Destructor */ /* ========================================================================== */ /* * First thing to get called, NOTE ros::init called by superclass * Not needed here * */ MissionControl::MissionControl() : rqt_gui_cpp::Plugin(), widget(nullptr), autonomy{"autonomous_action_server",true}, teleop{"teleop_action_server",true}, arm_client{"move_arm", true}, teleopEnabled{false}, teleopActive{false} { setObjectName("MissionControl"); } /* NOTE: I think these QObjects have reference counting and are held by * smart pointers under the hood. (I never ever see any qt programmers * implement destructors or free memory on QObjects in any tutorial, example * code or forum). However I do not know for sure, so I do it here to make * myself feel better, and it doesn't seem to complain. * */ MissionControl::~MissionControl() { delete countdownClock; delete widget; } /* ========================================================================== */ /* Initialize/Shutdown */ /* ========================================================================== */ /* * Actually sets up all of the components on the screen and registers * application context. Some of this code is boilerplate generated by that * "catkin_creat_rqt" script, and it looked complicated, so I just took it * at face value. I'll mark those sections with a //boilerplate annotation. * */ void MissionControl::initPlugin(qt_gui_cpp::PluginContext& context) { //boilerplate widget = new QWidget(); ui.setupUi(widget); if (context.serialNumber() > 1) { widget->setWindowTitle(widget->windowTitle() + " (" + QString::number(context.serialNumber()) + ")"); } //sets our window active, and makes sure we handle keyboard events widget->setFocusPolicy(Qt::StrongFocus); widget->installEventFilter(this); //boilerplate context.addWidget(widget); countdownClock = new QTimer(this); //mission clock, runs repeatedly // Since rqt creates a Nodelet for the ROS side of things, we can // use getNodeHandle() and similar functions instead of creating // a NodeHandle member. // getMTNodeHandle() gives us a multithreaded NodeHandle. com = getMTNodeHandle().subscribe("/com", 5, &MissionControl::updateStatus, this); joySub = getMTNodeHandle().subscribe<sensor_msgs::Joy>("/joy", 5, &MissionControl::joyCallback, this); inputReadTimer = getMTNodeHandle().createTimer(ros::Duration(0.1), &MissionControl::inputReadTimerCallback, this); /* Sets up all the signal/slot connections. * * For those unfamilair with qt this is the backbone of event driven * programming in qt. Signals get generated when an event of interest * happens: button pressed/released, timer expires... You can attach * signals to 0 or many slots. Slots are functions that get put into an * application level queue and processed when time allows. This allows * for thread safety. * * Signals can pass data, however slots they attach to must be able to * recieve that data, so signatures need to match. Sometimes you don't * want to do this, so you can get around it with lambdas (which I end * up doing below) * * Qt might or might not run different ui objects on many different * threads, and rqt will be running on a diffent thread. So in general, * if you need to have synchronous state passing, do it through the * signal/slot system, and you should be fine. * */ connect(ui.start_button, &QPushButton::clicked,this, &MissionControl::startMission); connect(ui.clock_button, &QPushButton::clicked,this, &MissionControl::startManual); connect(ui.autonomy_button, &QPushButton::clicked, this, &MissionControl::goAutonomousMode); connect(ui.teleop_button, &QPushButton::clicked, this, &MissionControl::goTeleopMode); //Control connect(ui.control_enable_button,&QPushButton::clicked, [this] () {toggleControl(true);}); connect(ui.control_disable_button,&QPushButton::clicked, [this] () {toggleControl(false);}); /* Joystick * Note, Joystick is not linked to E-stop. setJoystick needs to be replaced with toggleJoystick * * */ connect(ui.joy_enable_button,&QPushButton::clicked, [this]() {setJoystick(true);}); connect(ui.joy_disable_button,&QPushButton::clicked, [this]() {setJoystick(false);}); //PID connect(ui.arm_pid_enable_button,&QPushButton::clicked, [this] () {setArmPID(true);}); connect(ui.arm_pid_disable_button,&QPushButton::clicked, [this] () {setArmPID(false);}); connect(countdownClock, &QTimer::timeout, this, &MissionControl::renderClock); connect(this, &MissionControl::emitStatus, ui.status_log, &QPlainTextEdit::appendPlainText, Qt::QueuedConnection); connect(ui.status_log, &QPlainTextEdit::textChanged, this, &MissionControl::renderStatus); /* NOTE Remember how I said parameters of signals/slots need to match * up. I want to be able to process teleop commands by passing the code * into the perform teleop command. I could write a bunch of functors, * to make the parameters match up but that could get tedious, luckily * qt5 did a little phenagling which allows us to use lambdas instead. * */ connect(ui.reset_starting_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::RESET_STARTING);}); connect(ui.reset_dumping_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::RESET_DUMPING);}); connect(ui.dump_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::DUMP);}); connect(ui.dig_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::DIG);}); /* for commands which do the turntable/drivebase we want to kill the * motors after release*/ // arm buttons //lower arm connect(ui.lower_arm_extend_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::LOWER_ARM_EXTEND);}); connect(ui.lower_arm_retract_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::LOWER_ARM_RETRACT);}); //upper arm connect(ui.upper_arm_extend_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::UPPER_ARM_EXTEND);}); connect(ui.upper_arm_retract_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::UPPER_ARM_RETRACT);}); //scoop connect(ui.scoop_extend_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::SCOOP_EXTEND);}); connect(ui.scoop_retract_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::SCOOP_RETRACT);}); // raise arm to straight, neutral position above robot connect(ui.raise_arm_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::RAISE_ARM);}); //turntable connect(ui.cw_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::CLOCKWISE);}); connect(ui.ccw_button,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::COUNTERCLOCKWISE);}); //reset encoders connect(ui.set_encoders,&QPushButton::clicked, [this] () {performTeleop(tfr_utilities::TeleopCode::RESET_ENCODER_COUNTS_TO_START);}); //drivebase //forward connect(ui.forward_button,&QPushButton::pressed, [this] () {performTeleop(tfr_utilities::TeleopCode::FORWARD);}); connect(ui.forward_button,&QPushButton::released, [this] () {performTeleop(tfr_utilities::TeleopCode::STOP_DRIVEBASE);}); //backward connect(ui.backward_button,&QPushButton::pressed, [this] () {performTeleop(tfr_utilities::TeleopCode::BACKWARD);}); connect(ui.backward_button,&QPushButton::released, [this] () {performTeleop(tfr_utilities::TeleopCode::STOP_DRIVEBASE);}); //left connect(ui.left_button,&QPushButton::pressed, [this] () {performTeleop(tfr_utilities::TeleopCode::LEFT);}); connect(ui.left_button,&QPushButton::released, [this] () {performTeleop(tfr_utilities::TeleopCode::STOP_DRIVEBASE);}); //right connect(ui.right_button,&QPushButton::pressed, [this] () {performTeleop(tfr_utilities::TeleopCode::RIGHT);}); connect(ui.right_button,&QPushButton::released, [this] () {performTeleop(tfr_utilities::TeleopCode::STOP_DRIVEBASE);}); // Set up the action servers. ROS_INFO("Mission Control: connecting autonomy"); autonomy.waitForServer(); ROS_INFO("Mission Control: connected autonomy"); ROS_INFO("Mission Control: connecting teleop"); teleop.waitForServer(); ROS_INFO("Mission Control: connected teleop"); } /* * This get's called before the destructor, and apparently we need to * deallocate our ros objects manually here according to the documentation. * Publishers and subscribers especially * */ void MissionControl::shutdownPlugin() { // Using a Qt plugin means we must manually kill ROS entities. inputReadTimer.stop(); com.shutdown(); joySub.shutdown(); autonomy.cancelAllGoals(); autonomy.stopTrackingGoal(); teleop.cancelAllGoals(); teleop.stopTrackingGoal(); } /* ========================================================================== */ /* Methods */ /* ========================================================================== */ /* * Startup utility to reset the turntable * */ void MissionControl::resetTurntable() { ROS_INFO("Mission Control: Resetting turntable"); toggleMotors(false); std_srvs::Empty::Request req; std_srvs::Empty::Response res; while(!ros::service::call("/zero_turntable", req, res)) { ros::Duration{INPUT_READ_RATE}.sleep(); } performTeleop(tfr_utilities::TeleopCode::DRIVING_POSITION); toggleMotors(true); } /* greys/ungreys all teleop buttons, and tell's system whether to process teleop or * not * */ void MissionControl::setTeleop(bool value) { ui.left_button->setEnabled(value); ui.right_button->setEnabled(value); ui.forward_button->setEnabled(value); ui.backward_button->setEnabled(value); ui.autonomy_button->setEnabled(value); ui.dump_button->setEnabled(value); ui.dig_button->setEnabled(value); ui.lower_arm_extend_button->setEnabled(value); ui.lower_arm_retract_button->setEnabled(value); ui.upper_arm_extend_button->setEnabled(value); ui.upper_arm_retract_button->setEnabled(value); ui.scoop_extend_button->setEnabled(value); ui.scoop_retract_button->setEnabled(value); teleopEnabled = value; } /* * Toggles the autonomy stop button * */ void MissionControl::setAutonomy(bool value) { ui.teleop_button->setEnabled(value); } /* * Toggles the control buttons * */ void MissionControl::setControl(bool value) { ui.control_enable_button->setEnabled(!value); ui.control_disable_button->setEnabled(value); } void MissionControl::setJoystick(bool value) { ui.joy_enable_button->setEnabled(!value); ui.joy_disable_button->setEnabled(value); } void MissionControl::setArmPID(bool value){ ros::param::set("/write_arm_values", value); ui.arm_pid_enable_button->setEnabled(!value); ui.arm_pid_disable_button->setEnabled(value); } /* * Utility for stopping all motors * */ void MissionControl::softwareStop() { //performTeleop(tfr_utilities::TeleopCode::STOP_DRIVEBASE); teleop.waitForResult(); } /* ========================================================================== */ /* Events */ /* ========================================================================== */ /* * Key press/release events should not directly trigger teleop commands. * Instead, we keep track of the key states and use key events to change * those key state variables. Separate callbacks can periodically check * all the key states and perform teleop (on a different thread). * * No matter how many times the keys get pressed down (from unintentional * key bouncing), teleop will still be performed at a fixed rate. * * When writing callbacks for quick, repeated events like key presses, * it is important that the callback returns as fast as possible. * */ bool MissionControl::eventFilter(QObject* obj, QEvent* event) { bool keyPress = event->type() == QEvent::KeyPress; if (teleopEnabled && (keyPress || event->type() == QEvent::KeyRelease)) { const Qt::Key key = static_cast<Qt::Key>( static_cast<QKeyEvent*>(event)->key()); return processKey(key, keyPress); } else { // The event was not a key press/release, so pass it on to // something else. return QObject::eventFilter(obj, event); } } // This function returns a bool so its use inside of eventFilter() will // allow the filter to consume or pass on a key event. bool MissionControl::processKey(const Qt::Key key, const bool keyPress) { TeleopCommand command; // It might look tedious, but a switch statement for this few keys // is more efficient than using an STL data structure to track keys. switch (key) { // driving controls case (Qt::Key_W): command = driveForward; break; case (Qt::Key_S): command = driveBackward; break; case (Qt::Key_A): command = driveLeft; break; case (Qt::Key_D): command = driveRight; break; case (Qt::Key_Shift): command = driveStop; break; // lower arm controls case (Qt::Key_U): command = lowerArmExtend; break; case (Qt::Key_J): command = lowerArmRetract; break; // upper arm controls case (Qt::Key_I): command = upperArmExtend; break; case (Qt::Key_K): command = upperArmRetract; break; // scoop controls case (Qt::Key_O): command = scoopExtend; break; case (Qt::Key_L): command = scoopRetract; break; // turntable controls case (Qt::Key_P): command = clockwise; break; case (Qt::Key_Semicolon): command = ctrClockwise; break; // dumping controls case (Qt::Key_Y): command = dump; break; case (Qt::Key_H): command = resetDumping; break; default: // If we aren't using a key, don't consume its event. return false; } // Lock the mutex to "claim" the control bools. std::lock_guard<std::mutex> controlLock(teleopStateMutex); teleopState[command] = keyPress; // Consume the key event, so nothing else can use it. return true; } // MissionControl::processKey() /* ========================================================================== */ /* Callbacks */ /* ========================================================================== */ /* * Callback for our status subscriber this happens in the "ros" thread so I * need to communicate to the GUI in a safe signal/slot combination. * * This triggers our custom emitStatus signal, which triggers the built in * text update in the text box, a seperate timer event is constantly * scrolling the window on a set fast interval. * */ void MissionControl::updateStatus(const tfr_msgs::SystemStatusConstPtr &status) { const std::string statusStr = getStatusMessage( static_cast<StatusCode>(status->status_code), status->data); // The status message must be wrapped in a signal-safe "Q" object. QString statusMsg = QString::fromStdString(statusStr); emit emitStatus(statusMsg); } /* * Callback for incoming joystick messages. * Use only with the Microsoft Xbox 360 Wired Controller for Linux. * * Arm control scheme: * https://en.wikipedia.org/wiki/Excavator_controls#ISO_controls * */ void MissionControl::joyCallback(const sensor_msgs::Joy::ConstPtr& joy) { using namespace JoyIndices; using namespace JoyBounds; if(!teleopEnabled) { return; } // Lock the mutex to "claim" the control bools. std::lock_guard<std::mutex> controlLock(teleopStateMutex); // Driving teleopState[driveStop] = joy->buttons[BUTTON_LB]; teleopState[driveForward] = joy->axes[AXIS_DPAD_Y] > MIN_DPAD; teleopState[driveBackward] = joy->axes[AXIS_DPAD_Y] < -1 * MIN_DPAD; teleopState[driveLeft] = joy->axes[AXIS_DPAD_X] > MIN_DPAD; teleopState[driveRight] = joy->axes[AXIS_DPAD_X] < -1 * MIN_DPAD; // Lower arm teleopState[lowerArmExtend] = joy->axes[AXIS_RIGHT_Y] < -1 * MIN_RIGHT; teleopState[lowerArmRetract] = joy->axes[AXIS_RIGHT_Y] > MIN_RIGHT; // Upper arm teleopState[upperArmExtend] = joy->axes[AXIS_LEFT_Y] > MIN_LEFT; teleopState[upperArmRetract] = joy->axes[AXIS_LEFT_Y] < -1 * MIN_LEFT; // Scoop teleopState[scoopExtend] = joy->axes[AXIS_RIGHT_X] < -1 * MIN_RIGHT; teleopState[scoopRetract] = joy->axes[AXIS_RIGHT_X] > MIN_RIGHT; // Turntable teleopState[ctrClockwise] = joy->axes[AXIS_LEFT_X] > MIN_LEFT; teleopState[clockwise] = joy->axes[AXIS_LEFT_X] < -1 * MIN_LEFT; // Dumping teleopState[dump] = joy->buttons[BUTTON_X]; teleopState[resetDumping] = joy->buttons[BUTTON_Y]; } /* * This callback periodically reads the input control variables * and sends the respective control commands over teleop. * */ void MissionControl::inputReadTimerCallback(const ros::TimerEvent& event) { if(!teleopEnabled) { return; } tfr_utilities::TeleopCode code; // Using unique_lock instead of lock_guard so we can control when // to unlock, because we want to unlock the booleans before // performing teleop. std::unique_lock<std::mutex> controlLock(teleopStateMutex); // Using the inequality operator != is like doing A XOR B, so that // only one can be active at a time. If you try to go forward // and backward at the same time, this results in no action. // These if blocks are organized by highest to lowest priority. if(teleopState[driveStop]) { code = tfr_utilities::TeleopCode::STOP_DRIVEBASE; } else if(teleopState[lowerArmExtend] != teleopState[lowerArmRetract]) { // Ternary operators are sometimes cleaner than if/else blocks. code = teleopState[lowerArmExtend] ? tfr_utilities::TeleopCode::LOWER_ARM_EXTEND : tfr_utilities::TeleopCode::LOWER_ARM_RETRACT; } else if(teleopState[upperArmExtend] != teleopState[upperArmRetract]) { code = teleopState[upperArmExtend] ? tfr_utilities::TeleopCode::UPPER_ARM_EXTEND : tfr_utilities::TeleopCode::UPPER_ARM_RETRACT; } else if(teleopState[scoopExtend] != teleopState[scoopRetract]) { code = teleopState[scoopExtend] ? tfr_utilities::TeleopCode::SCOOP_EXTEND : tfr_utilities::TeleopCode::SCOOP_RETRACT; } else if(teleopState[clockwise] != teleopState[ctrClockwise]) { code = teleopState[clockwise] ? tfr_utilities::TeleopCode::CLOCKWISE : tfr_utilities::TeleopCode::COUNTERCLOCKWISE; } else if(teleopState[dump] != teleopState[resetDumping]) { code = teleopState[dump] ? tfr_utilities::TeleopCode::DUMP : tfr_utilities::TeleopCode::RESET_DUMPING; } else if(teleopState[driveLeft] != teleopState[driveRight]) { code = teleopState[driveLeft] ? tfr_utilities::TeleopCode::LEFT : tfr_utilities::TeleopCode::RIGHT; } else if(teleopState[driveForward] != teleopState[driveBackward]) { code = teleopState[driveForward] ? tfr_utilities::TeleopCode::FORWARD : tfr_utilities::TeleopCode::BACKWARD; } else if(teleopActive) { // Teleop was active, but there is no command to send. // Render it inactive and stop the drivebase, because // a key/joystick was released. controlLock.unlock(); teleopActive = false; performTeleop(tfr_utilities::TeleopCode::STOP_DRIVEBASE); return; } else { // If there is no action and teleop is inactive, leave early. return; } controlLock.unlock(); if(code != tfr_utilities::TeleopCode::STOP_DRIVEBASE) { teleopActive = true; } performTeleop(code); } // inputReadTimerCallback() /* ========================================================================== */ /* Slots */ /* ========================================================================== */ //self explanitory, starts the time service in executive void MissionControl::startTimeService() { std_srvs::Empty start; ros::service::call("start_mission", start); //start updating the gui mission clock countdownClock->start(500); } //starts mission in autonomous mode void MissionControl::startMission() { startTimeService(); goAutonomousMode(); toggleControl(true); toggleMotors(true); } //starts mission is teleop mode void MissionControl::startManual() { startTimeService(); goTeleopMode(); //toggleControl(true); //toggleMotors(true); } //triggers state change into autonomous mode from teleop void MissionControl::goAutonomousMode() { resetTurntable(); softwareStop(); setAutonomy(true); tfr_msgs::EmptyGoal goal{}; while (!teleop.getState().isDone()) teleop.cancelAllGoals(); autonomy.sendGoal(goal); setTeleop(false); widget->setFocus(); } //triggers state change into teleop from autonomy void MissionControl::goTeleopMode() { setAutonomy(false); while (!autonomy.getState().isDone()) autonomy.cancelAllGoals(); //resetTurntable(); setTeleop(true); softwareStop(); widget->setFocus(); } // Performs a teleop command asynchronously. void MissionControl::performTeleop(const tfr_utilities::TeleopCode& code) { tfr_msgs::TeleopGoal goal; goal.code = static_cast<uint8_t>(code); teleop.sendGoal(goal); } //toggles control for estop (on/off) void MissionControl::toggleControl(bool state) { std_srvs::SetBool request; request.request.data = state; while(!ros::service::call("toggle_control", request)); setControl(state); } //toggles control for estop (on/off) void MissionControl::toggleMotors(bool state) { std_srvs::SetBool request; request.request.data = state; while(!ros::service::call("toggle_motors", request)); } //self explanitory void MissionControl::renderClock() { tfr_msgs::DurationSrv remaining_time; ros::service::call("time_remaining", remaining_time); ui.time_display->display(remaining_time.response.duration.toSec()); } //scrolls the status window void MissionControl::renderStatus() { ui.status_log->verticalScrollBar()->setValue(ui.status_log->verticalScrollBar()->maximum()); } } // namespace PLUGINLIB_EXPORT_CLASS(tfr_mission_control::MissionControl, rqt_gui_cpp::Plugin)
39.376119
103
0.584944
[ "render", "object" ]
d14236b85b0af9dd88ab0f797ccb9b500b50e1e6
2,930
cc
C++
chrome/test/webdriver/commands/session_with_id.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
chrome/test/webdriver/commands/session_with_id.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
chrome/test/webdriver/commands/session_with_id.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2011 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/test/webdriver/commands/session_with_id.h" #include <sstream> #include <string> #include "base/values.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_constants.h" #include "chrome/test/webdriver/commands/response.h" #include "chrome/test/webdriver/webdriver_session.h" namespace webdriver { SessionWithID::SessionWithID(const std::vector<std::string>& path_segments, const DictionaryValue* const parameters) : WebDriverCommand(path_segments, parameters) {} SessionWithID::~SessionWithID() {} bool SessionWithID::DoesGet() { return true; } bool SessionWithID::DoesDelete() { return true; } void SessionWithID::ExecuteGet(Response* const response) { DictionaryValue *temp_value = new DictionaryValue(); // Standard capabilities defined at // http://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object temp_value->SetString("browserName", "chrome"); temp_value->SetString("version", session_->GetBrowserVersion()); #if defined(OS_WIN) temp_value->SetString("platform", "windows"); #elif defined(OS_MACOSX) temp_value->SetString("platform", "mac"); #elif defined(OS_CHROMEOS) temp_value->SetString("platform", "chromeos"); #elif defined(OS_LINUX) temp_value->SetString("platform", "linux"); #else temp_value->SetString("platform", "unknown"); #endif temp_value->SetBoolean("javascriptEnabled", true); temp_value->SetBoolean("takesScreenshot", true); temp_value->SetBoolean("handlesAlerts", true); temp_value->SetBoolean("databaseEnabled", false); temp_value->SetBoolean("locationContextEnabled", false); temp_value->SetBoolean("applicationCacheEnabled", false); temp_value->SetBoolean("browserConnectionEnabled", false); temp_value->SetBoolean("cssSelectorsEnabled", true); temp_value->SetBoolean("webStorageEnabled", false); temp_value->SetBoolean("rotatable", false); temp_value->SetBoolean("acceptSslCerts", false); // Even when ChromeDriver does not OS-events, the input simulation produces // the same effect for most purposes (except IME). temp_value->SetBoolean("nativeEvents", true); // Custom non-standard session info. temp_value->SetWithoutPathExpansion( "chrome.chromedriverVersion", Value::CreateStringValue(chrome::kChromeVersion)); temp_value->SetWithoutPathExpansion( "chrome.nativeEvents", Value::CreateBooleanValue(session_->capabilities().native_events)); response->SetValue(temp_value); } void SessionWithID::ExecuteDelete(Response* const response) { // Session manages its own lifetime, so do not call delete. session_->Terminate(); } bool SessionWithID::ShouldRunPreAndPostCommandHandlers() { return false; } } // namespace webdriver
33.295455
85
0.752218
[ "vector" ]
d14723b58bb0ee9ce1d073d7957888ec6d871515
15,678
cpp
C++
src/datetime.cpp
jeremydumais/Jed-CPP-DateTime-library
c2f26ef058d5d638b1eed2083b7c821f0ff2fe9b
[ "MIT" ]
13
2020-03-12T08:10:58.000Z
2022-03-16T05:38:56.000Z
src/datetime.cpp
jeremydumais/Jed-CPP-DateTime-library
c2f26ef058d5d638b1eed2083b7c821f0ff2fe9b
[ "MIT" ]
null
null
null
src/datetime.cpp
jeremydumais/Jed-CPP-DateTime-library
c2f26ef058d5d638b1eed2083b7c821f0ff2fe9b
[ "MIT" ]
4
2021-03-20T14:17:34.000Z
2021-08-14T14:55:38.000Z
#include "datetime.h" using namespace std; namespace jed_utils { //Default constructor get current date and time datetime::datetime() : timeInfo(new tm()) { time_t rawtime; time (&rawtime); struct tm *tm_now = localtime(&rawtime); _copy_from(tm_now); } datetime::datetime(int year, int month, int day, int hour, int minute, int second, period day_period) { //Check out of range limit if (month < 1 || month > 12) { throw invalid_argument("month must be between 1 and 12"); } if (day < 1) { throw invalid_argument("day is out of range"); } if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 31) { throw invalid_argument("day is out of range"); } if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) { throw invalid_argument("day is out of range"); } if (month == 2 && this->_is_leapyear(year) && day > 29) { throw invalid_argument("day is out of range"); } if (month == 2 && !this->_is_leapyear(year) && day > 28) { throw invalid_argument("day is out of range"); } if (day_period == period::undefined) { if (hour < 0 || hour > 23) { throw invalid_argument("hour must be between 0 and 23"); } } else { if (day_period != period::AM && day_period != period::PM) { throw invalid_argument("the selected period is out of range"); } if (hour < 1 || hour > 12) { throw invalid_argument("hour must be between 1 and 12"); } //Adjust to 24 hour format if (hour == 12 && day_period == period::AM) { hour = 0; } else if (day_period == period::PM && hour < 12) { hour = hour + 12; } } if (minute < 0 || minute > 59) { throw invalid_argument("minute must be between 0 and 59"); } if (second < 0 || second > 59) { throw invalid_argument("second must be between 0 and 59"); } timeInfo = new tm(); timeInfo->tm_year = year - 1900; timeInfo->tm_mon = month - 1; timeInfo->tm_mday = day; timeInfo->tm_hour = hour; timeInfo->tm_min = minute; timeInfo->tm_sec = second; timeInfo->tm_isdst = -1; mktime(timeInfo); } //Copy constructor datetime::datetime(const datetime& other) { timeInfo = new tm(); _copy_from(other.timeInfo); } //Copy assignment datetime& datetime::operator=(const datetime& other) { if (this != &other) { _copy_from(other.timeInfo); } return *this; } datetime::~datetime() { delete timeInfo; } //Move constructor datetime::datetime(datetime&& other) noexcept : timeInfo(other.timeInfo) { // Release the data pointer from the source object so that the destructor // does not free the memory multiple times. other.timeInfo = nullptr; } //Move assignement operator datetime& datetime::operator=(datetime&& other) noexcept { if (this != &other) { delete timeInfo; // Copy the data pointer and its length from the source object. timeInfo = other.timeInfo; // Release the data pointer from the source object so that // the destructor does not free the memory multiple times. other.timeInfo = nullptr; } return *this; } bool datetime::_is_leapyear(int year) const { return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); } string datetime::to_string() const { char retVal[128] = ""; sprintf(static_cast<char *>(retVal), "%d-%02d-%02d %02d:%02d:%02d", get_year(), get_month(), get_day(), get_hour(), get_minute(), get_second()); return string(static_cast<char *>(retVal)); } string datetime::to_string(const string& format) const { string retVal; if (strcmp(format.c_str(), "") == 0) { throw invalid_argument("format"); } string pattern_temp; for (unsigned int index_char = 0; index_char < format.length(); index_char++) { bool is_letter = false; //Check if the character is a valid pattern char if ((format[index_char] >= 'a' && format[index_char] <= 'z') || (format[index_char] >= 'A' && format[index_char] <= 'Z')) { is_letter = true; if (pattern_temp.length() == 0) { pattern_temp += format[index_char]; } //Check if the pattern has not changed else if (format[index_char] == pattern_temp[pattern_temp.length() - 1]) { pattern_temp += format[index_char]; } } //Check if the pattern has not changed if (pattern_temp.length() > 0 && (format[index_char] != pattern_temp[pattern_temp.length() - 1] || index_char == format.length() - 1)) { //int *ptr_date_section = nullptr; char value_converted[20] = ""; if (pattern_temp == "yyyy") { sprintf(static_cast<char *>(value_converted), "%04d", this->get_year()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "yy") { sprintf(static_cast<char *>(value_converted), "%02d", this->get_year() % 100); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "MM") { sprintf(static_cast<char *>(value_converted), "%02d", this->get_month()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "M") { sprintf(static_cast<char *>(value_converted), "%01d", this->get_month()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "dd") { sprintf(static_cast<char *>(value_converted), "%02d", this->get_day()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "d") { sprintf(static_cast<char *>(value_converted), "%01d", this->get_day()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "HH") { sprintf(static_cast<char *>(value_converted), "%02d", this->get_hour()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "H") { sprintf(static_cast<char *>(value_converted), "%01d", this->get_hour()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "hh") { int instance_hour = this->get_hour(); if (instance_hour == 0) { retVal += "12"; } else if (instance_hour > 12) { sprintf(static_cast<char *>(value_converted), "%02d", instance_hour - 12); retVal += static_cast<char *>(value_converted); } else { sprintf(static_cast<char *>(value_converted), "%02d", instance_hour); retVal += static_cast<char *>(value_converted); } } else if (pattern_temp == "h") { int instance_hour = this->get_hour(); if (instance_hour == 0) { retVal += "12"; } else if (instance_hour > 12) { sprintf(static_cast<char *>(value_converted), "%01d", instance_hour - 12); retVal += static_cast<char *>(value_converted); } else { sprintf(static_cast<char *>(value_converted), "%01d", instance_hour); retVal += static_cast<char *>(value_converted); } } else if (pattern_temp == "mm") { sprintf(static_cast<char *>(value_converted), "%02d", this->get_minute()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "m") { sprintf(static_cast<char *>(value_converted), "%01d", this->get_minute()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "ss") { sprintf(static_cast<char *>(value_converted), "%02d", this->get_second()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "s") { sprintf(static_cast<char *>(value_converted), "%01d", this->get_second()); retVal += static_cast<char *>(value_converted); } else if (pattern_temp == "tt") { if (this->get_hour() >= 12) { retVal += "PM"; } else { retVal += "AM"; } } pattern_temp = ""; } if (!is_letter) { retVal += format[index_char]; } else if (pattern_temp.length() == 0) { pattern_temp += format[index_char]; } } return string(retVal); } string datetime::to_shortdate_string() const { char retVal[128] = ""; sprintf(static_cast<char *>(retVal), "%d-%02d-%02d", get_year(), get_month(), get_day()); return string(static_cast<char *>(retVal)); } int datetime::get_year() const { return timeInfo->tm_year + 1900; } int datetime::get_month() const { return timeInfo->tm_mon + 1; } int datetime::get_day() const { return timeInfo->tm_mday; } int datetime::get_hour() const { return timeInfo->tm_hour; } int datetime::get_minute() const { return timeInfo->tm_min; } int datetime::get_second() const { return timeInfo->tm_sec; } weekday datetime::get_weekday() const { return static_cast<weekday>(timeInfo->tm_wday); } void datetime::add_years(int nb_years) { timeInfo->tm_year += nb_years; } void datetime::add_months(int nb_months) { //Get number of year auto nb_year = static_cast<int>(ceil(nb_months / 12)); int nb_months_final = nb_months % 12; if (timeInfo->tm_mon + nb_months_final > 11) { // tm_mon is from 0 to 11 nb_year++; nb_months_final = (timeInfo->tm_mon + nb_months_final) - 12; timeInfo->tm_mon = nb_months_final; } else { timeInfo->tm_mon += nb_months_final; } timeInfo->tm_year += nb_year; } void datetime::add_days(int nb_days) { add_seconds(nb_days * ONE_DAY); } void datetime::add_hours(int nb_hours) { add_seconds(nb_hours * ONE_HOUR); } void datetime::add_minutes(int nb_minutes) { add_seconds(nb_minutes * ONE_MINUTE); } void datetime::add_seconds(int nb_seconds) { struct tm *tm_new_time; //errno_t err; time_t new_seconds = mktime(timeInfo) + nb_seconds; delete timeInfo; tm_new_time = localtime(&new_seconds); timeInfo = new tm(); _copy_from(tm_new_time); } bool datetime::is_leapyear() { return _is_leapyear(get_year()); } bool datetime::is_leapyear(int year) { datetime dateTemp(year, 1, 1); return dateTemp.is_leapyear(); } void datetime::_copy_from(const tm * otm) { timeInfo->tm_year = otm->tm_year; timeInfo->tm_mon = otm->tm_mon; timeInfo->tm_mday = otm->tm_mday; timeInfo->tm_hour = otm->tm_hour; timeInfo->tm_min = otm->tm_min; timeInfo->tm_sec = otm->tm_sec; timeInfo->tm_isdst = otm->tm_isdst; timeInfo->tm_wday = otm->tm_wday; timeInfo->tm_yday = otm->tm_yday; } datetime datetime::parse(const string& format, const string& value) { int year = 1970, month = 1, day = 1, hour = 0, minute = 0, second = 0; if (strcmp(format.c_str(), "") == 0) { throw invalid_argument("format"); } string pattern_temp; int pattern_firstindex = 0; bool is_letter = false; period day_period = period::undefined; for (unsigned int index_char = 0; index_char < format.length(); index_char++) { //Check if the character is a valid pattern char if ((format[index_char] >= 'a' && format[index_char] <= 'z') || (format[index_char] >= 'A' && format[index_char] <= 'Z')) { is_letter = true; if (pattern_temp.length() == 0) { pattern_temp += format[index_char]; pattern_firstindex = index_char; } //Check if the pattern has not changed else if (format[index_char] == pattern_temp[pattern_temp.length() - 1]) { pattern_temp += format[index_char]; } } //Check if the pattern has not changed if (format[index_char] != pattern_temp[pattern_temp.length() - 1] || index_char == format.length() - 1) { if (pattern_firstindex + pattern_temp.length() <= value.length()) { //Ensure that the value if long enough int *ptr_date_section = nullptr; if (pattern_temp == "yyyy") { ptr_date_section = &year; } if (pattern_temp == "MM") { ptr_date_section = &month; } if (pattern_temp == "dd") { ptr_date_section = &day; } if (pattern_temp == "HH") { ptr_date_section = &hour; } if (pattern_temp == "hh") { ptr_date_section = &hour; day_period = period::AM; //Set default day period } if (pattern_temp == "mm") { ptr_date_section = &minute; } if (pattern_temp == "ss") { ptr_date_section = &second; } if (pattern_temp == "tt") { //Day period string period_str = value.substr(pattern_firstindex, pattern_temp.length()); if (strcmp(period_str.c_str(), "AM") == 0) { day_period = period::AM; } else if(strcmp(period_str.c_str(), "PM") == 0) { day_period = period::PM; } else { throw invalid_argument("invalid value for period"); } } if (ptr_date_section != nullptr) { *ptr_date_section = _parse_intvalue(pattern_temp, pattern_firstindex, pattern_temp.length(), value); } } pattern_temp = ""; } if (is_letter && pattern_temp.length() == 0) { pattern_temp += format[index_char]; pattern_firstindex = index_char; } } return datetime(year, month, day, hour, minute, second, day_period); } int datetime::_parse_intvalue(const string &pattern, int index, size_t mask_length, const string &parse_str) { long converted_value; int ret_val; char *end; const char *parse_str_chr; string value_parsed = parse_str.substr(index, mask_length); parse_str_chr = value_parsed.c_str(); converted_value = strtol(parse_str_chr, &end, 10); if (parse_str_chr == end) { throw runtime_error("Unable to parse the mask " + pattern); } ret_val = static_cast<int>(converted_value); return ret_val; } // Operators std::ostream& operator<<(std::ostream &os, const datetime &dt) { char retVal[128] = ""; sprintf(static_cast<char *>(retVal), "%d-%02d-%02d %02d:%02d:%02d", dt.timeInfo->tm_year + 1900, dt.timeInfo->tm_mon + 1, dt.timeInfo->tm_mday, dt.timeInfo->tm_hour, dt.timeInfo->tm_min, dt.timeInfo->tm_sec); os << static_cast<char *>(retVal); return os; } bool operator<(const datetime &mdt, const datetime &odt) { return mktime(mdt.timeInfo) < mktime(odt.timeInfo); } bool operator>(const datetime &mdt, const datetime &odt) { return mktime(odt.timeInfo) < mktime(mdt.timeInfo); } bool operator<=(const datetime &mdt, const datetime &odt) { return !(mktime(mdt.timeInfo) > mktime(odt.timeInfo)); } bool operator>=(const datetime &mdt, const datetime &odt) { return !(mktime(mdt.timeInfo) < mktime(odt.timeInfo)); } bool operator==(const datetime &mdt, const datetime &odt) { return mktime(mdt.timeInfo) == mktime(odt.timeInfo); } bool operator!=(const datetime &mdt, const datetime &odt) { return !(mktime(mdt.timeInfo) == mktime(odt.timeInfo)); } timespan operator-(const datetime &mdt, const datetime &odt) { int days = 0, hours = 0, minutes = 0, seconds = 0; //Transfer both dates in a number of days time_t time_mdt = mktime(mdt.timeInfo); time_t time_odt = mktime(odt.timeInfo); double difference = difftime(time_mdt, time_odt) / (60 * 60 * 24); days = static_cast<int>(difference); if (mdt >= odt) { hours = mdt.get_hour() - odt.get_hour(); seconds = mdt.get_second() - odt.get_second(); minutes = mdt.get_minute() - odt.get_minute(); } else { if (mdt.get_second() > odt.get_second()) { seconds = mdt.get_second() - odt.get_second() - 60; minutes += 1; } else { seconds = mdt.get_second() - odt.get_second(); } if (mdt.get_minute() > odt.get_minute()) { minutes += mdt.get_minute() - odt.get_minute() - 60; hours += 1; } else { minutes += mdt.get_minute() - odt.get_minute(); } if (mdt.get_hour() > odt.get_hour()) { hours += mdt.get_hour() - odt.get_hour() - 24; } else { hours += mdt.get_hour() - odt.get_hour(); } } timespan retVal(days, hours, minutes, seconds); return retVal; } } // namespace jed_utils
27.457093
139
0.631841
[ "object" ]
d14bfc3c7a9bef03aa787b87313ca3eb75e0b0f3
415
hpp
C++
Code/include/OE/Engine/MeshRenderer.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
21
2018-06-26T16:37:36.000Z
2022-01-11T01:19:42.000Z
Code/include/OE/Engine/MeshRenderer.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
null
null
null
Code/include/OE/Engine/MeshRenderer.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
3
2019-10-01T14:10:50.000Z
2021-11-19T20:30:18.000Z
#ifndef ENGINE_MESHRENDERER_HPP #define ENGINE_MESHRENDERER_HPP #include "OE/Engine/Component.hpp" #include "OE/Graphics/3D/Material.hpp" #include "OE/Graphics/API/Mesh.hpp" namespace OrbitEngine { namespace Engine { class MeshRenderer : public Component { NATIVE_REFLECTION public: MeshRenderer(); ~MeshRenderer(); private: Graphics::Mesh* m_Mesh; Graphics::Material* m_Material; }; } } #endif
17.291667
42
0.751807
[ "mesh", "3d" ]
d16094a9bf6f369d2c7827c1925cefe8c21f92ae
2,764
cpp
C++
src/Tests/testLBFGS.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
null
null
null
src/Tests/testLBFGS.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
null
null
null
src/Tests/testLBFGS.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
1
2018-10-20T00:43:36.000Z
2018-10-20T00:43:36.000Z
/* Conditional Random Fields for Object Localization * Master thesis source code * * Authors: * Andreas Christian Eilschou (jwb226@alumni.ku.dk) * Andreas Hjortgaard Danielsen (gxn961@alumni.ku.dk) * * Department of Computer Science * University of Copenhagen * Denmark * * Date: 27-08-2012 */ #include <cstdio> #include <iostream> #include <fstream> #include "DataManager.h" #include "ConditionalRandomField.h" #include "ObjectiveFunctions/LogLikelihood.h" #include "ObjectiveFunctions/LogLikelihoodGradient.h" #include "Learning/LBFGS.h" #include "Types.h" using namespace std; //int testLBFGS() { int main(int argc, char **argv) { // initialize data manager DataManager dataman; try { //dataman.loadImages("../pascal/USURF3K/", "subsets/train_width_height_bicycle.txt"); //dataman.loadBboxes("../pascal/Annotations/ess/bicycle_train_onlyboxes.ess"); dataman.loadImages("../cows-train/EUCSURF-3000/", "../subsets/cows_train10_width_height.txt"); dataman.loadBboxes("../cows-train/Annotations/TUcow_train10.ess"); } catch (int e) { if (e == FILE_NOT_FOUND) { fprintf(stderr, "There was a problem opening a file!\n"); return -1; } } // create conditional random field ConditionalRandomField crf(&dataman); //Weights w = dataman.getWeights(); int numWeights = 3000; Weights w(numWeights); // initialize weights between -1 and 1 for (int i=0; i<numWeights; i++) { w[i] = 0.5; } // set weights int stepSize = 32; crf.setStepSize(stepSize); crf.setWeights(w); // create log-likelihood objective function and gradient with regularization LogLikelihood loglik(&dataman, &crf); loglik.setLambda(2.0); LogLikelihoodGradient loglikgrad(&dataman, &crf); loglikgrad.setLambda(2.0); // train parameters with BFGS LBFGS lbfgs(&loglik, &loglikgrad); Weights w_new(numWeights, 0.0); printf("Learning parameters with LBFGS...\n"); try { w_new = lbfgs.learnWeights(w); } catch (int e) { if (e == ROUNDOFF_ERROR) { fprintf(stderr, "LBFGS::learnWeights threw a round-off error!\n"); return ROUNDOFF_ERROR; } if (e == DIM_ERROR) { fprintf(stderr, "LBFGS::learnWeights threw a dimensionality error!\n"); return DIM_ERROR; } if (e == NOT_A_NUMBER) { fprintf(stderr, "LBFGS::learnWeights threw a NAN error!\n"); return NOT_A_NUMBER; } } ofstream weight_file("lbfgs_weights_bicycle.txt"); if (!weight_file) { cerr << "Could not open file lbfgs_weights_bicycle.txt" << endl; } // store result in file for (int i=0; i<numWeights; i++) { weight_file << w_new[i] << endl; } weight_file.close(); cout << "Done!" << endl; return 0; }
24.678571
98
0.668596
[ "object" ]
d1625a638491c3389def35e6d30d2e6e012c66da
1,057
cpp
C++
LeetCode/0429. N-ary Tree Level Order Traversal/solution.cpp
InnoFang/oh-my-algorithms
f559dba371ce725a926725ad28d5e1c2facd0ab2
[ "Apache-2.0" ]
1
2017-03-31T15:24:01.000Z
2017-03-31T15:24:01.000Z
LeetCode/0429. N-ary Tree Level Order Traversal/solution.cpp
InnoFang/Algorithm-Library
1896b9d8b1fa4cd73879aaecf97bc32d13ae0169
[ "Apache-2.0" ]
null
null
null
LeetCode/0429. N-ary Tree Level Order Traversal/solution.cpp
InnoFang/Algorithm-Library
1896b9d8b1fa4cd73879aaecf97bc32d13ae0169
[ "Apache-2.0" ]
null
null
null
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ /** * 38 / 38 test cases passed. * Runtime: 24 ms * Memory Usage: 11.6 MB */ class Solution { public: vector<vector<int>> levelOrder(Node* root) { vector<vector<int>> ans; if (root == nullptr) return ans; queue<Node*> que; que.emplace(root); while (que.size()) { int layer = que.size(); vector<int> level; for (int i = 0; i < layer; ++ i) { auto node = que.front(); que.pop(); level.push_back(node->val); for (auto child : node->children) { if (child != nullptr) { que.emplace(child); } } } ans.push_back(level); } return ans; } };
21.14
51
0.449385
[ "vector" ]
d163be72d03122d7942977a47f3817b195df88dc
4,885
cpp
C++
omp_prog/optimal_split_graph/Graph.cpp
alexanderflegontov/OpenMPAnalyzer
609ad47699384b802b4d8307fab55b63e749f84c
[ "MIT" ]
null
null
null
omp_prog/optimal_split_graph/Graph.cpp
alexanderflegontov/OpenMPAnalyzer
609ad47699384b802b4d8307fab55b63e749f84c
[ "MIT" ]
null
null
null
omp_prog/optimal_split_graph/Graph.cpp
alexanderflegontov/OpenMPAnalyzer
609ad47699384b802b4d8307fab55b63e749f84c
[ "MIT" ]
null
null
null
#include "Graph.h" #define PART_A (1) #define PART_B (2) // Sorting of deficits according to the second element struct sort_def { bool operator()(const std::pair<int, int> &left, const std::pair<int, int> &right) { return left.second > right.second; } }; Graph::Graph(int size, int probty) { Graph::v_size = size; Graph::half = Graph::v_size / 2; Graph::e_size = 0; totalGain = 0; edge = new bool*[Graph::v_size]; part = new int[Graph::v_size]; gain = new int[Graph::half + 1]; // Create matrix for (int i(0); i < Graph::v_size; i++) { edge[i] = new bool[Graph::v_size]; for (int j(0); j < Graph::v_size; j++) edge[i][j] = false; } // Generate matrix int prob; for (int i(0); i < Graph::v_size; i++){ for (int j(i + 1); j < Graph::v_size; j++) { prob = rand() % 100; if (prob < probty) { edge[i][j] = true; edge[j][i] = true; Graph::e_size++; } } } } Graph::~Graph() { delete[] part; delete[] gain; for (int i(0); i < Graph::v_size; i++) delete[] edge[i]; delete edge; } void Graph::print_matrix() { cout << "Graph has " << e_size << " edges\n\n"; for (int i(0); i < Graph::v_size; i++) { for (int j(0); j < Graph::v_size; j++) cout << edge[i][j] << ' '; cout << endl; } cout << endl; } // Print current parts of splitting void Graph::print_parts() { for (int i(1); i < 3; i++){ cout << i << " part:\n"; for (int j(0); j < Graph::v_size; j++){ if (part[j] == i) cout << j << ' '; } cout << endl; } cout << endl; } // Print couples of deficits void Graph::print_defs() { if (!def_a.empty() && !def_b.empty()){ for (vector<pair<int, int> >::iterator it = def_a.begin(); it != def_a.end(); ++it) cout << it->first << ":" << it->second << " "; cout << endl; for (vector<pair<int, int> >::iterator it = def_b.begin(); it != def_b.end(); ++it) cout << it->first << ":" << it->second << " "; cout << endl << endl; } } void Graph::print_gains() { for (int i(1); i < Graph::v_size / 2 + 1; i++) cout << gain[i] << " "; cout << endl; } void Graph::create_parts(){ for (int i= 0; i < Graph::v_size; i++) part[i] = 0; int k = 0; do { for (int j(0); j < Graph::v_size; j++) { int ch = rand() % 100; if (ch > 50 && part[j] != PART_A) { part[j] = PART_A; k++; } if (k == Graph::half) break; } } while (k < Graph::half); for (int i(0); i < Graph::v_size; i++){ if (part[i] != PART_A) part[i] = PART_B; } } // Calculate deficits void Graph::def_calc() { for (int i(0); i <= Graph::half; i++) gain[i] = 0; def_a.clear(); def_b.clear(); int def; for (int i(0); i < Graph::v_size; i++) { def = 0; for (int j(0); j < Graph::v_size; j++) { if (edge[i][j]) { if (part[i] == part[j]) def--; else def++; } } if (part[i] == PART_A) def_a.push_back(std::make_pair(i, def)); else def_b.push_back(std::make_pair(i, def)); } } // Recalculate deficits after couple exchange void Graph::def_recalc() { for (vector<pair<int, int> >::iterator it = def_a.begin(); it != def_a.end(); ++it) it->second += 2 * edge[it->first][last_a] - 2 * edge[it->first][last_b]; for (vector<pair<int, int> >::iterator it = def_b.begin(); it != def_b.end(); ++it) it->second += 2 * edge[it->first][last_b] - 2 * edge[it->first][last_a]; } // Ordering deficiencies after couple exchange void Graph::def_balance() { std::sort(def_a.begin(), def_a.end(), sort_def()); std::sort(def_b.begin(), def_b.end(), sort_def()); } // Exchange of couple of vertexes bool Graph::exchange_pair(int stage) { int tgain; last_a = def_a.front().first; last_b = def_b.front().first; tgain = def_a.front().second + def_b.front().second - 2 * edge[last_a][last_b]; if (tgain > 0){ def_a.erase(def_a.begin()); def_b.erase(def_b.begin()); gain[stage] = gain[stage - 1] + tgain; totalGain += tgain; if (part[last_a] == PART_A){ part[last_a] = PART_B; part[last_b] = PART_A; } else{ part[last_a] = PART_A; part[last_b] = PART_B; } cout << "Vertexes " << last_a << " and " << last_b << " have been exchanged!" << endl; return true; } return false; } //Calculate total benefit after a series of couple exchanges int Graph::total_gain(){ return totalGain; } //Returns array with total gain and parts int* Graph::create_result(){ int* res = new int[Graph::v_size+1]; res[Graph::v_size] = this->cut_size(); for (int i(0); i < Graph::v_size; i++) res[i] = part[i]; return res; } int Graph::cut_size(){ int size = 0; for (int i(0); i < Graph::v_size; i++) for (int j(0); j < Graph::v_size; j++) { if (edge[i][j] && (part[i] != part[j])) size++; } return size / 2; }
22.827103
89
0.542886
[ "vector" ]
d1682e4dddec33d33038c53aad6af48f4388167d
352
cpp
C++
trunk/day55/solution.cpp
itsjacob/90pp
eca71e624d28d216feb06d615e587fc6792c36b6
[ "MIT" ]
null
null
null
trunk/day55/solution.cpp
itsjacob/90pp
eca71e624d28d216feb06d615e587fc6792c36b6
[ "MIT" ]
null
null
null
trunk/day55/solution.cpp
itsjacob/90pp
eca71e624d28d216feb06d615e587fc6792c36b6
[ "MIT" ]
null
null
null
class Solution { public: int rob(vector<int> &nums) { if (nums.size() == 1) return nums[0]; std::vector<int> dp(nums.size(), 0); dp[0] = nums[0]; dp[1] = std::max(nums[0], nums[1]); for (int ii = 2; ii < dp.size(); ii++) { dp[ii] = std::max(dp[ii - 1], dp[ii - 2] + nums[ii]); } return dp[nums.size() - 1]; } };
22
59
0.488636
[ "vector" ]
d16c1fb73cb3bfa7b3d9bfdb8bb98f12d2136d20
2,179
cc
C++
src/app/nit_entropy/main.cc
trimpim/genode-world
dfe284836e0a2fb3efed199660087d71386fc077
[ "MIT" ]
2
2018-06-25T13:04:26.000Z
2022-01-19T14:56:34.000Z
src/app/nit_entropy/main.cc
trimpim/genode-world
dfe284836e0a2fb3efed199660087d71386fc077
[ "MIT" ]
null
null
null
src/app/nit_entropy/main.cc
trimpim/genode-world
dfe284836e0a2fb3efed199660087d71386fc077
[ "MIT" ]
null
null
null
/* * \brief Entropy visualizer * \author Emery Hemingway * \date 2018-11-09 */ /* * Copyright (C) 2018 Genode Labs GmbH * * This file is part of the Genode OS framework, which is distributed * under the terms of the GNU Affero General Public License version 3. */ /* Genode includes */ #include <terminal_session/connection.h> #include <nitpicker_session/connection.h> #include <framebuffer_session/connection.h> #include <base/attached_dataspace.h> #include <base/heap.h> #include <base/log.h> #include <base/component.h> namespace Nit_entropy { using namespace Genode; typedef Surface_base::Point Point; typedef Surface_base::Area Area; typedef Surface_base::Rect Rect; struct Main; }; struct Nit_entropy::Main { enum { WIDTH = 256, HEIGHT = 256 }; Genode::Env &_env; Heap _heap { _env.ram(), _env.rm() }; Nitpicker::Connection _nitpicker { _env }; Framebuffer::Session &_fb = *_nitpicker.framebuffer(); Terminal::Connection _entropy { _env, "entropy" }; Dataspace_capability _fb_ds_cap() { using Framebuffer::Mode; Mode mode(WIDTH, HEIGHT, Mode::RGB565); _nitpicker.buffer(mode, false); return _fb.dataspace(); } Attached_dataspace _fb_ds { _env.rm(), _fb_ds_cap() }; Nitpicker::Session::View_handle _view = _nitpicker.create_view(); void _refresh() { _fb.refresh(0, 0, WIDTH, HEIGHT); } void _plot() { uint16_t *pixels = _fb_ds.local_addr<uint16_t>(); static uint8_t buf[HEIGHT]; size_t n = _entropy.read(buf, sizeof(buf)); if (n != sizeof(buf)) { Genode::error("read ", n, " bytes of entropy"); } for (int i = 0; i < HEIGHT; ++i) { uint16_t *row = &pixels[i*WIDTH]; row[buf[i]] = ~row[buf[i]]; } _refresh(); } Signal_handler<Main> _sync_handler { _env.ep(), *this, &Main::_plot }; Main(Env &env) : _env(env) { _nitpicker.enqueue<Nitpicker::Session::Command::Geometry>( _view, Rect(Point(0, 0), Area (WIDTH, HEIGHT))); _nitpicker.enqueue<Nitpicker::Session::Command::To_front>( _view, Nitpicker::Session::View_handle()); _nitpicker.execute(); _fb.sync_sigh(_sync_handler); } }; void Component::construct(Genode::Env &env) { static Nit_entropy::Main inst(env); }
22.234694
70
0.687471
[ "geometry" ]
ab6c1c86f71a8fa43e5601f01089a6d7fb8b9da4
1,408
cpp
C++
Spoj/ANARCO9A.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
Spoj/ANARCO9A.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
Spoj/ANARCO9A.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef priority_queue<int> maxHeap; typedef priority_queue<int, vector<int>, greater<int>> minHeap; #define endl "\n" #define int long long #define MOD 1000000007 #define ump unordered_map #define pb push_back #define mp make_pair #define pie acos(-1) bool test_cases; void init(bool k) { test_cases = k; ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } struct test_cases { void test_case(int cnt, string test) { stack<char> st; int n = test.length(); int ans = 0; for (int i = 0; i < n; i++) { char ch = test[i]; if (ch == '{') { st.push('{'); } else { if (st.empty()) { ans++; st.push('{'); } else { st.pop(); } } } cout << cnt << ". "; if (st.empty()) { cout << ans << endl; } else { cout << ans + st.size() / 2 << endl; } } }; int32_t main() { init(false); string tc; if (test_cases) { cin >> tc; } int cnt = 0; for (int i = 0; i == 0; i = 0) { cin >> tc; cnt++; if (tc[0] == '-') { return 0; } struct test_cases o; o.test_case(cnt, tc); } return 0; };
21.014925
63
0.440341
[ "vector" ]
ab72756ac18714f0e776c5277c0f9333b57d1700
214
cpp
C++
GameEngine/main.cpp
GPUWorks/OpenGL-Mini-CAD-2D
fedb903302f82a1d1ff0ca6776687a60a237008a
[ "MIT" ]
1
2021-08-10T02:48:57.000Z
2021-08-10T02:48:57.000Z
GameEngine/main.cpp
GPUWorks/OpenGL-Mini-CAD-2D
fedb903302f82a1d1ff0ca6776687a60a237008a
[ "MIT" ]
null
null
null
GameEngine/main.cpp
GPUWorks/OpenGL-Mini-CAD-2D
fedb903302f82a1d1ff0ca6776687a60a237008a
[ "MIT" ]
null
null
null
#include "GLEW\glew.h" #include "GL\glut.h" #include "MainLoop.h" //#include <vector> using namespace std; int main(int argc, char** argv) { MainLoop* ml = new MainLoop(argc, argv); return 0; }
14.266667
42
0.626168
[ "vector" ]
ab732895aaacdbe940a2cbd00c5fe3e7d27221cd
16,762
cpp
C++
src/CImageFilter.cpp
colinw7/CImageLib
d060f9ed408c0c1a806b610de0c7b77a4368f2eb
[ "MIT" ]
2
2021-04-04T14:08:02.000Z
2021-12-23T02:22:40.000Z
src/CImageFilter.cpp
colinw7/CImageLib
d060f9ed408c0c1a806b610de0c7b77a4368f2eb
[ "MIT" ]
null
null
null
src/CImageFilter.cpp
colinw7/CImageLib
d060f9ed408c0c1a806b610de0c7b77a4368f2eb
[ "MIT" ]
1
2020-09-05T19:20:10.000Z
2020-09-05T19:20:10.000Z
#include <CImageFilter.h> #include <CGaussianBlur.h> #include <CTurbulenceUtil.h> #include <cmath> void CImage:: unsharpMask(CImagePtr src, CImagePtr &dst, double strength) { return src->unsharpMask(dst, strength); } CImagePtr CImage:: unsharpMask(double strength) { CImagePtr dst = CImageMgrInst->createImage(); dst->setDataSize(size_); unsharpMask(dst, strength); return dst; } void CImage:: unsharpMask(CImagePtr &dst, double strength) { if (hasColormap()) { CImagePtr src = dup(); src->convertToRGB(); return src->unsharpMask(dst, strength); } //--- // 5x5 std::vector<double> kernel = {{ 0, 0, 1, 0, 0, 0, 8, 21, 8, 0, 1, 21, 59, 21, 1, 0, 8, 21, 8, 0, 0, 0, 1, 0, 0 }}; convolve(dst, 5, 5, kernel); double gstrength = 1.0 - strength; int wx1, wy1, wx2, wy2; getWindow(&wx1, &wy1, &wx2, &wy2); for (int y = wy1; y <= wy2; ++y) { for (int x = wx1; x <= wx2; ++x) { CRGBA rgba1, rgba2; getRGBAPixel(x, y, rgba1); dst->getRGBAPixel(x, y, rgba2); CRGBA rgba = rgba1*strength + rgba2*gstrength; rgba.clamp(); dst->setRGBAPixel(x, y, rgba); } } } //--- CImagePtr CImage:: sobel(bool feldman) { CImagePtr dst = CImageMgrInst->createImage(); dst->setDataSize(size_); sobel(dst, feldman); return dst; } void CImage:: sobel(CImagePtr &dst, bool feldman) { if (hasColormap()) { CImagePtr src = dup(); src->convertToRGB(); return src->sobel(dst, feldman); } //--- CImagePtr dst1 = CImageMgrInst->createImage(); CImagePtr dst2 = CImageMgrInst->createImage(); dst1->setDataSize(size_); dst2->setDataSize(size_); std::vector<double> kernel1, kernel2; if (! feldman) { // sobel 3x3 kernel1 = {{ -1, 0, 1, -2, 0, 2, -1, 0, 1 }}; kernel2 = {{ -1, -2, -1, 0, 0, 0, 1, 2, 1 }}; } else { // sobel-feldman 3x3 kernel1 = {{ 3, 10, 3, 0, 0, 0, -3, -10, -3 }}; kernel2 = {{ 3, 0, -3, 10, 0, -10, 3, 0, -3 }}; } convolve(dst1, 3, 3, kernel1); convolve(dst2, 3, 3, kernel2); int wx1, wy1, wx2, wy2; getWindow(&wx1, &wy1, &wx2, &wy2); for (int y = wy1; y <= wy2; ++y) { for (int x = wx1; x <= wx2; ++x) { CRGBA rgba1, rgba2; dst1->getRGBAPixel(x, y, rgba1); dst2->getRGBAPixel(x, y, rgba2); double r = std::min(hypot(rgba1.getRed (), rgba2.getRed ()), 1.0); //double g = std::min(hypot(rgba1.getGreen(), rgba2.getGreen()), 1.0); //double b = std::min(hypot(rgba1.getBlue (), rgba2.getBlue ()), 1.0); dst->setRGBAPixel(x, y, CRGBA(r, r, r)); } } } //--- CImagePtr CImage:: sobelGradient() { CImagePtr dst = CImageMgrInst->createImage(); dst->setDataSize(size_); sobelGradient(dst); return dst; } void CImage:: sobelGradient(CImagePtr &dst) { if (hasColormap()) { CImagePtr dst1 = dup(); dst1->convertToRGB(); return sobelGradient(dst1); } //--- int wx1, wy1, wx2, wy2; getWindow(&wx1, &wy1, &wx2, &wy2); for (int y = wy1; y <= wy2; ++y) { for (int x = wx1; x <= wx2; ++x) { double xgray, ygray, xf, yf; sobelPixelGradient(x, y, 1, 1, xgray, ygray, xf, yf); double l = hypot(xgray, ygray); double r = std::min(l, 1.0); dst->setRGBAPixel(x, y, CRGBA(r, r, r)); } } } void CImage:: sobelPixelGradient(int x, int y, int dx, int dy, double &xgray, double &ygray, double &xf, double &yf) { int w = getWidth (); int h = getHeight(); int wx1, wy1, wx2, wy2; getWindow(&wx1, &wy1, &wx2, &wy2); if (x < dx || x > w - dx - 1 || y < dy || y > h - dy - 1) { getGrayPixel(x, y, &xgray); ygray = xgray; xf = 1; yf = 1; return; } double gray1, gray2, gray3, gray4, gray5, gray6, gray7, gray8, gray9; bool left = (x < dx), right = (x > w - dx - 1); bool top = (y < dy), bottom = (y > h - dy - 1); if (top && left) { getGrayPixel(x - dx, y - dy, &gray1); getGrayPixel(x , y - dy, &gray2); getGrayPixel(x - dx, y , &gray3); getGrayPixel(x , y , &gray4); xgray = -2*gray1 +2*gray2 -1*gray3 +1*gray4; ygray = -2*gray1 -1*gray2 +2*gray3 +1*gray4; xf = 2.0/(3*dx); yf = 2.0/(3*dy); } else if (top && right) { getGrayPixel(x , y - dy, &gray1); getGrayPixel(x + dx, y - dy, &gray2); getGrayPixel(x , y , &gray3); getGrayPixel(x + dx, y , &gray4); xgray = -2*gray1 +2*gray2 -1*gray3 +1*gray4; ygray = -1*gray1 -2*gray2 +1*gray3 +2*gray4; xf = 2.0/(3*dx); yf = 2.0/(3*dy); } else if (bottom && left) { getGrayPixel(x - dx, y , &gray1); getGrayPixel(x , y , &gray2); getGrayPixel(x - dx, y + dy, &gray3); getGrayPixel(x , y + dy, &gray4); xgray = -1*gray1 +1*gray2 -2*gray3 +2*gray4; ygray = -2*gray1 -1*gray2 +2*gray3 +1*gray4; xf = 2.0/(3*dx); yf = 2.0/(3*dy); } else if (bottom && right) { getGrayPixel(x , y , &gray1); getGrayPixel(x + dx, y , &gray2); getGrayPixel(x , y + dy, &gray3); getGrayPixel(x + dx, y + dy, &gray4); xgray = -1*gray1 +1*gray2 -2*gray3 +2*gray4; ygray = -1*gray1 -2*gray2 +1*gray3 +2*gray4; xf = 2.0/(3*dx); yf = 2.0/(3*dy); } else if (top) { getGrayPixel(x - dx, y - dy, &gray1); getGrayPixel(x , y - dy, &gray2); getGrayPixel(x + dx, y - dy, &gray3); getGrayPixel(x - dx, y , &gray4); getGrayPixel(x , y , &gray5); getGrayPixel(x + dx, y , &gray6); xgray = -2*gray1 +2*gray3 -1*gray4 +1*gray6; ygray = -1*gray1 -2*gray2 -1*gray3 +1*gray4 +2*gray5 +1*gray6; xf = 1.0/(3*dx); yf = 1.0/(2*dy); } else if (left) { getGrayPixel(x - dx, y - dy, &gray1); getGrayPixel(x , y - dy, &gray2); getGrayPixel(x - dx, y , &gray3); getGrayPixel(x , y , &gray4); getGrayPixel(x - dx, y + dy, &gray5); getGrayPixel(x , y + dy, &gray6); xgray = -1*gray1 +1*gray2 -2*gray3 +2*gray4 -1*gray5 +1*gray6; ygray = -2*gray1 -1*gray2 +2*gray5 +1*gray6; xf = 1.0/(2*dx); yf = 1.0/(3*dy); } else if (right) { getGrayPixel(x , y - dy, &gray1); getGrayPixel(x + dx, y - dy, &gray2); getGrayPixel(x , y , &gray3); getGrayPixel(x + dx, y , &gray4); getGrayPixel(x , y + dy, &gray5); getGrayPixel(x + dx, y + dy, &gray6); xgray = -1*gray1 +1*gray2 -2*gray3 +2*gray4 -1*gray5 +1*gray6; ygray = -1*gray1 -2*gray2 +1*gray5 +2*gray6; xf = 1.0/(2*dx); yf = 1.0/(3*dy); } else if (bottom) { getGrayPixel(x - dx, y , &gray1); getGrayPixel(x , y , &gray2); getGrayPixel(x + dx, y , &gray3); getGrayPixel(x - dx, y + dy, &gray4); getGrayPixel(x , y + dy, &gray5); getGrayPixel(x + dx, y + dy, &gray6); xgray = -1*gray1 +1*gray3 -2*gray4 +2*gray6; ygray = -1*gray1 -2*gray2 -1*gray3 +1*gray4 +2*gray5 +1*gray6; xf = 1.0/(3*dx); yf = 1.0/(2*dy); } else { getGrayPixel(x - dx, y - dy, &gray1); getGrayPixel(x , y - dy, &gray2); getGrayPixel(x + dx, y - dy, &gray3); getGrayPixel(x - dx, y , &gray4); //getGrayPixel(x , y , &gray5); getGrayPixel(x + dx, y , &gray6); getGrayPixel(x - dx, y + dy, &gray7); getGrayPixel(x , y + dy, &gray8); getGrayPixel(x + dx, y + dy, &gray9); xgray = -1*gray1 +1*gray3 -2*gray4 +2*gray6 -1*gray7 +1*gray9; ygray = -1*gray1 -2*gray2 -1*gray3 +1*gray7 +2*gray8 +1*gray9; xf = 1.0/(4*dx); yf = 1.0/(4*dy); } } //--- void CImage:: convolve(CImagePtr src, CImagePtr &dst, const std::vector<double> &kernel) { int size = sqrt(kernel.size()); return convolve(src, dst, size, size, kernel); } CImagePtr CImage:: convolve(const std::vector<double> &kernel) { int size = sqrt(kernel.size()); return convolve(size, size, kernel); } void CImage:: convolve(CImagePtr &dst, const std::vector<double> &kernel) { int size = sqrt(kernel.size()); return convolve(dst, size, size, kernel); } void CImage:: convolve(CImagePtr src, CImagePtr &dst, int xsize, int ysize, const std::vector<double> &kernel) { return src->convolve(dst, xsize, ysize, kernel); } CImagePtr CImage:: convolve(int xsize, int ysize, const std::vector<double> &kernel) { CImagePtr image = CImageMgrInst->createImage(); image->setDataSize(size_); convolve(image, xsize, ysize, kernel); return image; } void CImage:: convolve(CImagePtr &dst, int xsize, int ysize, const std::vector<double> &kernel) { CImageConvolveData data; data.xsize = xsize; data.ysize = ysize; data.kernel = kernel; convolve(dst, data); } void CImage:: convolve(CImagePtr &dst, const CImageConvolveData &data) { int xsize = data.xsize; int ysize = data.ysize; if (xsize < 0) xsize = sqrt(data.kernel.size()); if (ysize < 0) ysize = sqrt(data.kernel.size()); //--- int xborder = (xsize - 1)/2; int yborder = (ysize - 1)/2; double divisor = data.divisor; if (divisor < 0) { divisor = 0; for (const auto &k : data.kernel) divisor += k; if (divisor == 0) divisor = 1; } //--- int wx1, wy1, wx2, wy2; getWindow(&wx1, &wy1, &wx2, &wy2); int y = wy1; for ( ; y < yborder; ++y) { int x = wx1; for ( ; x <= wx2 - xborder; ++x) { CRGBA rgba; getRGBAPixel(x, y, rgba); dst->setRGBAPixel(x, y, rgba); } } for ( ; y <= wy2 - yborder; ++y) { int x = wx1; for ( ; x < xborder; ++x) { CRGBA rgba; getRGBAPixel(x, y, rgba); dst->setRGBAPixel(x, y, rgba); } for ( ; x <= wx2 - xborder; ++x) { CRGBA sum; int k = 0; for (int yk = -yborder; yk <= yborder; ++yk) { for (int xk = -xborder; xk <= xborder; ++xk) { CRGBA rgba; getRGBAPixel(x + xk, y + yk, rgba); sum += rgba*data.kernel[k]; ++k; } } sum /= divisor; sum.clamp(); if (data.preserveAlpha) { CRGBA rgba; getRGBAPixel(x, y, rgba); sum.setAlpha(rgba.getAlpha()); } dst->setRGBAPixel(x, y, sum); } for ( ; x <= wx2; ++x) { CRGBA rgba; getRGBAPixel(x, y, rgba); dst->setRGBAPixel(x, y, rgba); } } for ( ; y <= wy2; ++y) { int x = wx1; for ( ; x <= wx2; ++x) { CRGBA rgba; getRGBAPixel(x, y, rgba); dst->setRGBAPixel(x, y, rgba); } } } bool CImage:: gaussianBlur(CImagePtr src, CImagePtr &dst, double bx, double by, int nx, int ny) { return src->gaussianBlur(dst, bx, by, nx, ny); } bool CImage:: gaussianBlur(double bx, double by, int nx, int ny) { CImagePtr dst = dup(); if (! gaussianBlur(dst, bx, by, nx, ny)) return false; replace(dst); return true; } bool CImage:: gaussianBlur(CImagePtr &dst, double bx, double by, int nx, int ny) { return gaussianBlurExec(dst, bx, by, nx, ny); } bool CImage:: gaussianBlurExec(CImagePtr &dst, double bx, double by, int nx, int ny) { if (hasColormap()) { CImagePtr src = dup(); src->convertToRGB(); return src->gaussianBlur(dst, bx, by, nx, ny); } //--- class CImageWrapper { public: CImageWrapper(CImage *image) : image_(image) { } void getPixelRange(int *x1, int *y1, int *x2, int *y2) const { *x1 = 0; *y1 = 0; *x2 = image_->getWidth () - 1; *y2 = image_->getHeight() - 1; } void getWindow(int *x1, int *y1, int *x2, int *y2) const { image_->getWindow(x1, y1, x2, y2); } void getRGBA(int x, int y, double *r, double *g, double *b, double *a) const { CRGBA rgba; image_->getRGBAPixel(x, y, rgba); *r = rgba.getRed (); *g = rgba.getGreen(); *b = rgba.getBlue (); *a = rgba.getAlpha(); } void setRGBA(int x, int y, double r, double g, double b, double a) { image_->setRGBAPixel(x, y, CRGBA(r, g, b, a)); } private: CImage *image_; }; //--- CGaussianBlur<CImageWrapper> blur; CImageWrapper wsrc(this); CImageWrapper wdst(dst.getPtr()); blur.blur(wsrc, wdst, bx, by, nx, ny); #if 0 double minb = std::min(bx, by); if (minb <= 0) return false; //--- // calc matrix size if (nx == 0) { nx = int(6*bx + 1); if (nx > 4) nx = 4; } if (ny == 0) { ny = int(6*by + 1); if (ny > 4) ny = 4; } int nx1 = -nx/2; int nx2 = nx/2; int ny1 = -ny/2; int ny2 = ny/2; nx = nx2 - nx1 + 1; ny = ny2 - ny1 + 1; //--- // set matrix typedef std::vector<double> Reals; typedef std::vector<Reals> RealsArray; RealsArray m; m.resize(nx); for (int i = 0; i < nx; ++i) m[i].resize(ny); double bxy = bx*by; double bxy1 = 2*bxy; double bxy2 = 1.0/sqrt(M_PI*bxy1); double sm = 0.0; for (int i = 0, i1 = nx1; i < nx; ++i, ++i1) { int i2 = i1*i1; for (int j = 0, j1 = ny1; j < ny; ++j, ++j1) { int j2 = j1*j1; m[i][j] = bxy2*exp(-(i2 + j2)/bxy1); sm += m[i][j]; } } //--- // apply to image int wx1, wy1, wx2, wy2; getWindow(&wx1, &wy1, &wx2, &wy2); for (int y1 = wy1 + ny1, y2 = wy1, y3 = wy1 + ny2; y2 <= wy2; ++y1, ++y2, ++y3) { for (int x1 = wx1 + nx1, x2 = wx1, x3 = wx1 + nx2; x2 <= wx2; ++x1, ++x2, ++x3) { CRGBA rgba; double a = 0.0; int n = 0; for (int i = 0, x = x1; i < nx; ++i, ++x) { for (int j = 0, y = y1; j < ny; ++j, ++y) { if (! validPixel(x, y)) continue; CRGBA rgba1; getRGBAPixel(x, y, rgba1); rgba += rgba1*m[i][j]/sm; a += rgba1.getAlpha(); ++n; } } rgba.clamp(); rgba.setAlpha(a/n); dst->setRGBAPixel(x2, y2, rgba); } } #endif return true; } void CImage:: turbulence(bool fractal, double baseFreq, int numOctaves, int seed) { turbulence(fractal, baseFreq, baseFreq, numOctaves, seed); } void CImage:: turbulence(bool fractal, double baseFreqX, double baseFreqY, int numOctaves, int seed) { CTurbulenceUtil turbulence(seed); double r, g, b, a, point[2]; int wx1, wy1, wx2, wy2; getWindow(&wx1, &wy1, &wx2, &wy2); for (int y = wy1; y <= wy2; ++y) { for (int x = wx1; x <= wx2; ++x) { CRGBA rgba; getRGBAPixel(x, y, rgba); if (rgba.isTransparent()) continue; //TODO: keep alpha ? //double a = rgba.getAlpha(); point[0] = x; point[1] = y; r = turbulence.turbulence(0, point, baseFreqX, baseFreqY, numOctaves, fractal); g = turbulence.turbulence(1, point, baseFreqX, baseFreqY, numOctaves, fractal); b = turbulence.turbulence(2, point, baseFreqX, baseFreqY, numOctaves, fractal); a = turbulence.turbulence(3, point, baseFreqX, baseFreqY, numOctaves, fractal); if (fractal) { r = (r + 1.0) / 2.0; g = (g + 1.0) / 2.0; b = (b + 1.0) / 2.0; a = (a + 1.0) / 2.0; } r = std::min(std::max(r, 0.0), 1.0); g = std::min(std::max(g, 0.0), 1.0); b = std::min(std::max(b, 0.0), 1.0); a = std::min(std::max(a, 0.0), 1.0); setRGBAPixel(x, y, CRGBA(r, g, b, a)); } } } CImagePtr CImage:: displacementMap(CImagePtr dispImage, CRGBAComponent xcolor, CRGBAComponent ycolor, double scale) { CImagePtr dst = CImageMgrInst->createImage(); dst->setDataSize(size_); displacementMap(dispImage, xcolor, ycolor, scale, dst); return dst; } void CImage:: displacementMap(CImagePtr dispImage, CRGBAComponent xcolor, CRGBAComponent ycolor, double scale, CImagePtr dst) { int wx1, wy1, wx2, wy2; getWindow(&wx1, &wy1, &wx2, &wy2); for (int y = wy1; y <= wy2; ++y) { for (int x = wx1; x <= wx2; ++x) { CRGBA rgba1(0,0,0,0); // get displacement from dispImage color components if (dispImage->validPixel(x, y)) { CRGBA rgba2; dispImage->getRGBAPixel(x, y, rgba2); double rx = rgba2.getComponent(xcolor); double ry = rgba2.getComponent(ycolor); double x1 = x + scale*(rx - 0.5); double y1 = y + scale*(ry - 0.5); // TODO: interp pixel int ix1 = int(x1 + 0.5); int iy1 = int(y1 + 0.5); if (validPixel(ix1, iy1)) getRGBAPixel(ix1, iy1, rgba1); else { //getRGBAPixel(x, y, rgba1); } } else { //getRGBAPixel(x, y, rgba1); } dst->setRGBAPixel(x, y, rgba1); } } }
20.516524
96
0.530665
[ "vector" ]
ab7507a228cad1514ccc164436a13d719fefd16e
1,418
cpp
C++
interface/src/Stars.cpp
DaveDubUK/hifi
1ceed98ca2f43f9accef2a174a16ab4228093144
[ "Apache-2.0" ]
null
null
null
interface/src/Stars.cpp
DaveDubUK/hifi
1ceed98ca2f43f9accef2a174a16ab4228093144
[ "Apache-2.0" ]
null
null
null
interface/src/Stars.cpp
DaveDubUK/hifi
1ceed98ca2f43f9accef2a174a16ab4228093144
[ "Apache-2.0" ]
null
null
null
// // Stars.cpp // interface/src // // Created by Tobias Schwinger on 3/22/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Stars.h" #include <NumericalConstants.h> #include "InterfaceConfig.h" #include "starfield/Controller.h" Stars::Stars() : _controller(0l), _starsLoaded(false) { _controller = new starfield::Controller; } Stars::~Stars() { delete _controller; } bool Stars::generate(unsigned numStars, unsigned seed) { _starsLoaded = _controller->computeStars(numStars, seed); return _starsLoaded; } bool Stars::setResolution(unsigned k) { return _controller->setResolution(k); } void Stars::render(float fovY, float aspect, float nearZ, float alpha) { // determine length of screen diagonal from quadrant height and aspect ratio float quadrantHeight = nearZ * tanf(RADIANS_PER_DEGREE * fovY * 0.5f); float halfDiagonal = sqrt(quadrantHeight * quadrantHeight * (1.0f + aspect * aspect)); // determine fov angle in respect to the diagonal float fovDiagonal = atanf(halfDiagonal / nearZ) * 2.0f; // pull the modelview matrix off the GL stack glm::mat4 view; glGetFloatv(GL_MODELVIEW_MATRIX, glm::value_ptr(view)); _controller->render(fovDiagonal, aspect, glm::affineInverse(view), alpha); }
28.36
90
0.715797
[ "render" ]
ab76b167e3a3cd2aeff26dffaef748a67d252553
33,786
hxx
C++
main/oox/inc/oox/xls/addressconverter.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/oox/inc/oox/xls/addressconverter.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/oox/inc/oox/xls/addressconverter.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef OOX_XLS_ADDRESSCONVERTER_HXX #define OOX_XLS_ADDRESSCONVERTER_HXX #include <vector> #include <com/sun/star/table/CellAddress.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #include "oox/xls/workbookhelper.hxx" namespace oox { namespace xls { class BiffInputStream; class BiffOutputStream; // ============================================================================ // ============================================================================ /** A vector of com.sun.star.table.CellRangeAddress elements and additional functionality. */ class ApiCellRangeList : public ::std::vector< ::com::sun::star::table::CellRangeAddress > { public: inline explicit ApiCellRangeList() {} /** Returns the base address of this range list (top-left cell of first range). */ ::com::sun::star::table::CellAddress getBaseAddress() const; }; // ============================================================================ /** A 2D cell address struct for binary filters. */ struct BinAddress { sal_Int32 mnCol; sal_Int32 mnRow; inline explicit BinAddress() : mnCol( 0 ), mnRow( 0 ) {} inline explicit BinAddress( sal_Int32 nCol, sal_Int32 nRow ) : mnCol( nCol ), mnRow( nRow ) {} inline explicit BinAddress( const ::com::sun::star::table::CellAddress& rAddr ) : mnCol( rAddr.Column ), mnRow( rAddr.Row ) {} inline void set( sal_Int32 nCol, sal_Int32 nRow ) { mnCol = nCol; mnRow = nRow; } inline void set( const ::com::sun::star::table::CellAddress& rAddr ) { mnCol = rAddr.Column; mnRow = rAddr.Row; } void read( SequenceInputStream& rStrm ); void read( BiffInputStream& rStrm, bool bCol16Bit = true, bool bRow32Bit = false ); void write( BiffOutputStream& rStrm, bool bCol16Bit = true, bool bRow32Bit = false ) const; }; // ---------------------------------------------------------------------------- inline bool operator==( const BinAddress& rL, const BinAddress& rR ) { return (rL.mnCol == rR.mnCol) && (rL.mnRow == rR.mnRow); } inline bool operator<( const BinAddress& rL, const BinAddress& rR ) { return (rL.mnCol < rR.mnCol) || ((rL.mnCol == rR.mnCol) && (rL.mnRow < rR.mnRow)); } inline SequenceInputStream& operator>>( SequenceInputStream& rStrm, BinAddress& orPos ) { orPos.read( rStrm ); return rStrm; } inline BiffInputStream& operator>>( BiffInputStream& rStrm, BinAddress& orPos ) { orPos.read( rStrm ); return rStrm; } inline BiffOutputStream& operator<<( BiffOutputStream& rStrm, const BinAddress& rPos ) { rPos.write( rStrm ); return rStrm; } // ============================================================================ /** A 2D cell range address struct for binary filters. */ struct BinRange { BinAddress maFirst; BinAddress maLast; inline explicit BinRange() {} inline explicit BinRange( const BinAddress& rAddr ) : maFirst( rAddr ), maLast( rAddr ) {} inline explicit BinRange( const BinAddress& rFirst, const BinAddress& rLast ) : maFirst( rFirst ), maLast( rLast ) {} inline explicit BinRange( sal_Int32 nCol1, sal_Int32 nRow1, sal_Int32 nCol2, sal_Int32 nRow2 ) : maFirst( nCol1, nRow1 ), maLast( nCol2, nRow2 ) {} inline explicit BinRange( const ::com::sun::star::table::CellAddress& rAddr ) : maFirst( rAddr ), maLast( rAddr ) {} inline explicit BinRange( const ::com::sun::star::table::CellAddress& rFirst, const ::com::sun::star::table::CellAddress& rLast ) : maFirst( rFirst ), maLast( rLast ) {} inline explicit BinRange( const ::com::sun::star::table::CellRangeAddress& rRange ) : maFirst( rRange.StartColumn, rRange.StartRow ), maLast( rRange.EndColumn, rRange.EndRow ) {} inline void set( const BinAddress& rFirst, const BinAddress& rLast ) { maFirst = rFirst; maLast = rLast; } inline void set( sal_Int32 nCol1, sal_Int32 nRow1, sal_Int32 nCol2, sal_Int32 nRow2 ) { maFirst.set( nCol1, nRow1 ); maLast.set( nCol2, nRow2 ); } inline void set( const ::com::sun::star::table::CellAddress& rFirst, const ::com::sun::star::table::CellAddress& rLast ) { maFirst.set( rFirst ); maLast.set( rLast ); } inline void set( const ::com::sun::star::table::CellRangeAddress& rRange ) { maFirst.set( rRange.StartColumn, rRange.StartRow ); maLast.set( rRange.EndColumn, rRange.EndRow ); } inline sal_Int32 getColCount() const { return maLast.mnCol - maFirst.mnCol + 1; } inline sal_Int32 getRowCount() const { return maLast.mnRow - maFirst.mnRow + 1; } bool contains( const BinAddress& rAddr ) const; void read( SequenceInputStream& rStrm ); void read( BiffInputStream& rStrm, bool bCol16Bit = true, bool bRow32Bit = false ); void write( BiffOutputStream& rStrm, bool bCol16Bit = true, bool bRow32Bit = false ) const; }; // ---------------------------------------------------------------------------- inline bool operator==( const BinRange& rL, const BinRange& rR ) { return (rL.maFirst == rR.maFirst) && (rL.maLast == rR.maLast); } inline bool operator<( const BinRange& rL, const BinRange& rR ) { return (rL.maFirst < rR.maFirst) || ((rL.maFirst == rR.maFirst) && (rL.maLast < rR.maLast)); } inline SequenceInputStream& operator>>( SequenceInputStream& rStrm, BinRange& orRange ) { orRange.read( rStrm ); return rStrm; } inline BiffInputStream& operator>>( BiffInputStream& rStrm, BinRange& orRange ) { orRange.read( rStrm ); return rStrm; } inline BiffOutputStream& operator<<( BiffOutputStream& rStrm, const BinRange& rRange ) { rRange.write( rStrm ); return rStrm; } // ============================================================================ /** A 2D cell range address list for binary filters. */ class BinRangeList : public ::std::vector< BinRange > { public: inline explicit BinRangeList() {} BinRange getEnclosingRange() const; void read( SequenceInputStream& rStrm ); void read( BiffInputStream& rStrm, bool bCol16Bit = true, bool bRow32Bit = false ); void write( BiffOutputStream& rStrm, bool bCol16Bit = true, bool bRow32Bit = false ) const; void writeSubList( BiffOutputStream& rStrm, size_t nBegin, size_t nCount, bool bCol16Bit = true, bool bRow32Bit = false ) const; }; // ---------------------------------------------------------------------------- inline SequenceInputStream& operator>>( SequenceInputStream& rStrm, BinRangeList& orRanges ) { orRanges.read( rStrm ); return rStrm; } inline BiffInputStream& operator>>( BiffInputStream& rStrm, BinRangeList& orRanges ) { orRanges.read( rStrm ); return rStrm; } inline BiffOutputStream& operator<<( BiffOutputStream& rStrm, const BinRangeList& rRanges ) { rRanges.write( rStrm ); return rStrm; } // ============================================================================ /** Different target types that can be encoded in a BIFF URL. */ enum BiffTargetType { BIFF_TARGETTYPE_URL, /// URL, URL with sheet name, or sheet name. BIFF_TARGETTYPE_SAMESHEET, /// Target for special '!A1' syntax to refer to current sheet. BIFF_TARGETTYPE_LIBRARY, /// Library directory in application installation. BIFF_TARGETTYPE_DDE_OLE, /// DDE server/topic or OLE class/target. BIFF_TARGETTYPE_UNKNOWN /// Unknown/unsupported target type. }; // ============================================================================ // ============================================================================ /** Converter for cell addresses and cell ranges for OOXML and BIFF filters. */ class AddressConverter : public WorkbookHelper { public: explicit AddressConverter( const WorkbookHelper& rHelper ); // ------------------------------------------------------------------------ /** Tries to parse the passed string for a 2d cell address in A1 notation. This function accepts all strings that match the regular expression "[a-zA-Z]{1,6}0*[1-9][0-9]{0,8}" (without quotes), i.e. 1 to 6 letters for the column index (translated to 0-based column indexes from 0 to 321,272,405), and 1 to 9 digits for the 1-based row index (translated to 0-based row indexes from 0 to 999,999,998). The row number part may contain leading zeros, they will be ignored. It is up to the caller to handle cell addresses outside of a specific valid range (e.g. the entire spreadsheet). @param ornColumn (out-parameter) Returns the converted column index. @param ornRow (out-parameter) returns the converted row index. @param rString The string containing the cell address. @param nStart Start index of string part in rString to be parsed. @param nLength Length of string part in rString to be parsed. @return true = Parsed string was valid, returned values can be used. */ static bool parseOoxAddress2d( sal_Int32& ornColumn, sal_Int32& ornRow, const ::rtl::OUString& rString, sal_Int32 nStart = 0, sal_Int32 nLength = SAL_MAX_INT32 ); /** Tries to parse the passed string for a 2d cell range in A1 notation. This function accepts all strings that match the regular expression "ADDR(:ADDR)?" (without quotes), where ADDR is a cell address accepted by the parseOoxAddress2d() function of this class. It is up to the caller to handle cell ranges outside of a specific valid range (e.g. the entire spreadsheet). @param ornStartColumn (out-parameter) Returns the converted start column index. @param ornStartRow (out-parameter) returns the converted start row index. @param ornEndColumn (out-parameter) Returns the converted end column index. @param ornEndRow (out-parameter) returns the converted end row index. @param rString The string containing the cell address. @param nStart Start index of string part in rString to be parsed. @param nLength Length of string part in rString to be parsed. @return true = Parsed string was valid, returned values can be used. */ static bool parseOoxRange2d( sal_Int32& ornStartColumn, sal_Int32& ornStartRow, sal_Int32& ornEndColumn, sal_Int32& ornEndRow, const ::rtl::OUString& rString, sal_Int32 nStart = 0, sal_Int32 nLength = SAL_MAX_INT32 ); /** Tries to parse an encoded name of an external link target in BIFF documents, e.g. from EXTERNSHEET or SUPBOOK records. @param orClassName (out-parameter) DDE server name or OLE class name. @param orTargetUrl (out-parameter) Target URL, DDE topic or OLE object name. @param orSheetName (out-parameter) Sheet name in target document. @param rBiffEncoded Encoded name of the external link target. @param bFromDConRec True = path from DCONREF/DCONNAME/DCONBINAME records, false = other records. @return Type of the decoded target. */ BiffTargetType parseBiffTargetUrl( ::rtl::OUString& orClassName, ::rtl::OUString& orTargetUrl, ::rtl::OUString& orSheetName, const ::rtl::OUString& rBiffTargetUrl, bool bFromDConRec = false ); // ------------------------------------------------------------------------ /** Returns the biggest valid cell address in the own Calc document. */ inline const ::com::sun::star::table::CellAddress& getMaxApiAddress() const { return maMaxApiPos; } /** Returns the biggest valid cell address in the imported/exported Excel document. */ inline const ::com::sun::star::table::CellAddress& getMaxXlsAddress() const { return maMaxXlsPos; } /** Returns the biggest valid cell address in both Calc and the imported/exported Excel document. */ inline const ::com::sun::star::table::CellAddress& getMaxAddress() const { return maMaxPos; } /** Returns the column overflow status. */ inline bool isColOverflow() const { return mbColOverflow; } /** Returns the row overflow status. */ inline bool isRowOverflow() const { return mbRowOverflow; } /** Returns the sheet overflow status. */ inline bool isTabOverflow() const { return mbTabOverflow; } // ------------------------------------------------------------------------ /** Checks if the passed column index is valid. @param nCol The column index to check. @param bTrackOverflow true = Update the internal overflow flag, if the column index is outside of the supported limits. @return true = Passed column index is valid (no index overflow). */ bool checkCol( sal_Int32 nCol, bool bTrackOverflow ); /** Checks if the passed row index is valid. @param nRow The row index to check. @param bTrackOverflow true = Update the internal overflow flag, if the row index is outside of the supported limits. @return true = Passed row index is valid (no index overflow). */ bool checkRow( sal_Int32 nRow, bool bTrackOverflow ); /** Checks if the passed sheet index is valid. @param nSheet The sheet index to check. @param bTrackOverflow true = Update the internal overflow flag, if the sheet index is outside of the supported limits. @return true = Passed sheet index is valid (no index overflow). */ bool checkTab( sal_Int16 nSheet, bool bTrackOverflow ); // ------------------------------------------------------------------------ /** Checks the passed cell address if it fits into the spreadsheet limits. @param rAddress The cell address to be checked. @param bTrackOverflow true = Update the internal overflow flags, if the address is outside of the supported sheet limits. @return true = Passed address is valid (no index overflow). */ bool checkCellAddress( const ::com::sun::star::table::CellAddress& rAddress, bool bTrackOverflow ); /** Converts the passed string to a single cell address, without checking any sheet limits. @param orAddress (out-parameter) Returns the converted cell address. @param rString Cell address string in A1 notation. @param nSheet Sheet index to be inserted into orAddress. @return true = Cell address could be parsed from the passed string. */ bool convertToCellAddressUnchecked( ::com::sun::star::table::CellAddress& orAddress, const ::rtl::OUString& rString, sal_Int16 nSheet ); /** Tries to convert the passed string to a single cell address. @param orAddress (out-parameter) Returns the converted cell address. @param rString Cell address string in A1 notation. @param nSheet Sheet index to be inserted into orAddress (will be checked). @param bTrackOverflow true = Update the internal overflow flags, if the address is outside of the supported sheet limits. @return true = Converted address is valid (no index overflow). */ bool convertToCellAddress( ::com::sun::star::table::CellAddress& orAddress, const ::rtl::OUString& rString, sal_Int16 nSheet, bool bTrackOverflow ); /** Returns a valid cell address by moving it into allowed dimensions. @param rString Cell address string in A1 notation. @param nSheet Sheet index for the returned address (will be checked). @param bTrackOverflow true = Update the internal overflow flags, if the address is outside of the supported sheet limits. @return A valid API cell address struct. */ ::com::sun::star::table::CellAddress createValidCellAddress( const ::rtl::OUString& rString, sal_Int16 nSheet, bool bTrackOverflow ); /** Converts the passed address to a single cell address, without checking any sheet limits. @param orAddress (out-parameter) Returns the converted cell address. @param rBinAddress Binary cell address struct. @param nSheet Sheet index to be inserted into orAddress. */ void convertToCellAddressUnchecked( ::com::sun::star::table::CellAddress& orAddress, const BinAddress& rBinAddress, sal_Int16 nSheet ); /** Tries to convert the passed address to a single cell address. @param orAddress (out-parameter) Returns the converted cell address. @param rBinAddress Binary cell address struct. @param nSheet Sheet index to be inserted into orAddress (will be checked). @param bTrackOverflow true = Update the internal overflow flags, if the address is outside of the supported sheet limits. @return true = Converted address is valid (no index overflow). */ bool convertToCellAddress( ::com::sun::star::table::CellAddress& orAddress, const BinAddress& rBinAddress, sal_Int16 nSheet, bool bTrackOverflow ); /** Returns a valid cell address by moving it into allowed dimensions. @param rBinAddress Binary cell address struct. @param nSheet Sheet index for the returned address (will be checked). @param bTrackOverflow true = Update the internal overflow flags, if the address is outside of the supported sheet limits. @return A valid API cell address struct. */ ::com::sun::star::table::CellAddress createValidCellAddress( const BinAddress& rBinAddress, sal_Int16 nSheet, bool bTrackOverflow ); // ------------------------------------------------------------------------ /** Checks the passed cell range if it fits into the spreadsheet limits. @param rRange The cell range address to be checked. @param bAllowOverflow true = Allow ranges that start inside the supported sheet limits but may end outside of these limits. false = Do not allow ranges that overflow the supported limits. @param bTrackOverflow true = Update the internal overflow flags, if the passed range contains cells outside of the supported sheet limits. @return true = Cell range is valid. This function returns also true, if only parts of the range are outside the current sheet limits and such an overflow is allowed via parameter bAllowOverflow. Returns false, if the entire range is outside the sheet limits, or if overflow is not allowed via parameter bAllowOverflow. */ bool checkCellRange( const ::com::sun::star::table::CellRangeAddress& rRange, bool bAllowOverflow, bool bTrackOverflow ); /** Checks the passed cell range, may try to fit it to current sheet limits. First, this function reorders the column and row indexes so that the starting indexes are less than or equal to the end indexes. Then, depending on the parameter bAllowOverflow, the range is just checked or cropped to the current sheet limits. @param orRange (in-out-parameter) Converts the passed cell range into a valid cell range address. If the passed range contains cells outside the currently supported spreadsheet limits, it will be cropped to these limits. @param bAllowOverflow true = Allow ranges that start inside the supported sheet limits but may end outside of these limits. The cell range returned in orRange will be cropped to these limits. false = Do not allow ranges that overflow the supported limits. The function will return false when the range overflows the sheet limits. @param bTrackOverflow true = Update the internal overflow flags, if the original range contains cells outside of the supported sheet limits. @return true = Converted range address is valid. This function returns also true, if overflowing ranges are allowed via parameter bAllowOverflow and the range has been cropped, but still contains cells inside the current sheet limits. Returns false, if the entire range is outside the sheet limits or overflowing ranges are not allowed via parameter bAllowOverflow. */ bool validateCellRange( ::com::sun::star::table::CellRangeAddress& orRange, bool bAllowOverflow, bool bTrackOverflow ); /** Converts the passed string to a cell range address, without checking any sheet limits. @param orRange (out-parameter) Returns the converted range address. @param rString Cell range string in A1 notation. @param nSheet Sheet index to be inserted into orRange. @return true = Range address could be parsed from the passed string. */ bool convertToCellRangeUnchecked( ::com::sun::star::table::CellRangeAddress& orRange, const ::rtl::OUString& rString, sal_Int16 nSheet ); /** Tries to convert the passed string to a cell range address. @param orRange (out-parameter) Returns the converted cell range address. If the original range in the passed string contains cells outside the currently supported spreadsheet limits, and parameter bAllowOverflow is set to true, the range will be cropped to these limits. Example: the range string "A1:ZZ100000" may be converted to the range A1:IV65536. @param rString Cell range string in A1 notation. @param nSheet Sheet index to be inserted into orRange (will be checked). @param bAllowOverflow true = Allow ranges that start inside the supported sheet limits but may end outside of these limits. The cell range returned in orRange will be cropped to these limits. false = Do not allow ranges that overflow the supported limits. @param bTrackOverflow true = Update the internal overflow flags, if the original range contains cells outside of the supported sheet limits. @return true = Converted and returned range is valid. This function returns also true, if overflowing ranges are allowed via parameter bAllowOverflow and the range has been cropped, but still contains cells inside the current sheet limits. Returns false, if the entire range is outside the sheet limits or overflowing ranges are not allowed via parameter bAllowOverflow. */ bool convertToCellRange( ::com::sun::star::table::CellRangeAddress& orRange, const ::rtl::OUString& rString, sal_Int16 nSheet, bool bAllowOverflow, bool bTrackOverflow ); /** Converts the passed range to a cell range address, without checking any sheet limits. @param orRange (out-parameter) Returns the converted range address. @param rBinRange Binary cell range struct. @param nSheet Sheet index to be inserted into orRange. */ void convertToCellRangeUnchecked( ::com::sun::star::table::CellRangeAddress& orRange, const BinRange& rBinRange, sal_Int16 nSheet ); /** Tries to convert the passed range to a cell range address. @param orRange (out-parameter) Returns the converted cell range address. If the passed original range contains cells outside the currently supported spreadsheet limits, and parameter bAllowOverflow is set to true, the range will be cropped to these limits. @param rBinRange Binary cell range struct. @param nSheet Sheet index to be inserted into orRange (will be checked). @param bAllowOverflow true = Allow ranges that start inside the supported sheet limits but may end outside of these limits. The cell range returned in orRange will be cropped to these limits. false = Do not allow ranges that overflow the supported limits. @param bTrackOverflow true = Update the internal overflow flags, if the original range contains cells outside of the supported sheet limits. @return true = Converted and returned range is valid. This function returns also true, if overflowing ranges are allowed via parameter bAllowOverflow and the range has been cropped, but still contains cells inside the current sheet limits. Returns false, if the entire range is outside the sheet limits or if overflowing ranges are not allowed via parameter bAllowOverflow. */ bool convertToCellRange( ::com::sun::star::table::CellRangeAddress& orRange, const BinRange& rBinRange, sal_Int16 nSheet, bool bAllowOverflow, bool bTrackOverflow ); // ------------------------------------------------------------------------ /** Checks the passed cell range list if it fits into the spreadsheet limits. @param rRanges The cell range list to be checked. @param bAllowOverflow true = Allow ranges that start inside the supported sheet limits but may end outside of these limits. false = Do not allow ranges that overflow the supported limits. @param bTrackOverflow true = Update the internal overflow flags, if the passed range list contains cells outside of the supported sheet limits. @return true = All cell ranges are valid. This function returns also true, if overflowing ranges are allowed via parameter bAllowOverflow and only parts of the ranges are outside the current sheet limits. Returns false, if one of the ranges is completely outside the sheet limits or if overflowing ranges are not allowed via parameter bAllowOverflow. */ bool checkCellRangeList( const ApiCellRangeList& rRanges, bool bAllowOverflow, bool bTrackOverflow ); /** Tries to restrict the passed cell range list to current sheet limits. @param orRanges (in-out-parameter) Restricts the cell range addresses in the passed list to the current sheet limits and removes invalid ranges from the list. @param bTrackOverflow true = Update the internal overflow flags, if the original ranges contain cells outside of the supported sheet limits. */ void validateCellRangeList( ApiCellRangeList& orRanges, bool bTrackOverflow ); /** Tries to convert the passed string to a cell range list. @param orRanges (out-parameter) Returns the converted cell range addresses. If a range in the passed string contains cells outside the currently supported spreadsheet limits, it will be cropped to these limits. Example: the range string "A1:ZZ100000" may be converted to the range A1:IV65536. If a range is completely outside the limits, it will be omitted. @param rString Cell range list string in A1 notation, space separated. @param nSheet Sheet index to be inserted into orRanges (will be checked). @param bTrackOverflow true = Update the internal overflow flags, if the original ranges contain cells outside of the supported sheet limits. */ void convertToCellRangeList( ApiCellRangeList& orRanges, const ::rtl::OUString& rString, sal_Int16 nSheet, bool bTrackOverflow ); /** Tries to convert the passed range list to a cell range list. @param orRanges (out-parameter) Returns the converted cell range addresses. If a range in the passed string contains cells outside the currently supported spreadsheet limits, it will be cropped to these limits. Example: the range string "A1:ZZ100000" may be converted to the range A1:IV65536. If a range is completely outside the limits, it will be omitted. @param rBinRanges List of binary cell range objects. @param nSheet Sheet index to be inserted into orRanges (will be checked). @param bTrackOverflow true = Update the internal overflow flags, if the original ranges contain cells outside of the supported sheet limits. */ void convertToCellRangeList( ApiCellRangeList& orRanges, const BinRangeList& rBinRanges, sal_Int16 nSheet, bool bTrackOverflow ); // ------------------------------------------------------------------------ private: void initializeMaxPos( sal_Int16 nMaxXlsTab, sal_Int32 nMaxXlsCol, sal_Int32 nMaxXlsRow ); private: struct ControlCharacters { sal_Unicode mcThisWorkbook; /// Control character: Link to current workbook. sal_Unicode mcExternal; /// Control character: Link to external workbook/sheet. sal_Unicode mcThisSheet; /// Control character: Link to current sheet. sal_Unicode mcInternal; /// Control character: Link to internal sheet. sal_Unicode mcSameSheet; /// Control character: Link to same sheet (special '!A1' syntax). void set( sal_Unicode cThisWorkbook, sal_Unicode cExternal, sal_Unicode cThisSheet, sal_Unicode cInternal, sal_Unicode cSameSheet ); }; ::com::sun::star::table::CellAddress maMaxApiPos; /// Maximum valid cell address in Calc. ::com::sun::star::table::CellAddress maMaxXlsPos; /// Maximum valid cell address in Excel. ::com::sun::star::table::CellAddress maMaxPos; /// Maximum valid cell address in Calc/Excel. ControlCharacters maLinkChars; /// Control characters for external link import (BIFF). ControlCharacters maDConChars; /// Control characters for DCON* record import (BIFF). bool mbColOverflow; /// Flag for "columns overflow". bool mbRowOverflow; /// Flag for "rows overflow". bool mbTabOverflow; /// Flag for "tables overflow". }; // ============================================================================ } // namespace xls } // namespace oox #endif
49.107558
186
0.597674
[ "object", "vector" ]
ab77577d5773f3b7c4085fe9f227cca5999ff81a
489
hpp
C++
src/HNSW/DynamicList.hpp
Matej-Chmel/hnsw-chm0065
ada0d367b0231caf94551a3fc760d22648c783c6
[ "MIT" ]
null
null
null
src/HNSW/DynamicList.hpp
Matej-Chmel/hnsw-chm0065
ada0d367b0231caf94551a3fc760d22648c783c6
[ "MIT" ]
null
null
null
src/HNSW/DynamicList.hpp
Matej-Chmel/hnsw-chm0065
ada0d367b0231caf94551a3fc760d22648c783c6
[ "MIT" ]
null
null
null
#pragma once #include "FurthestHeap.hpp" #include "NearestHeap.hpp" namespace chm { class DynamicList : public Unique { void clear(); public: FurthestHeap furthestHeap; NearestHeap nearestHeap; void add(float distance, size_t nodeID); DynamicList(float distance, size_t entryID); void fillResults(size_t K, std::vector<size_t>& outIDs, std::vector<float>& outDistances); NodeDistance furthest(); void keepOnlyNearest(); void removeFurthest(); size_t size(); }; }
22.227273
92
0.734151
[ "vector" ]
ab7be5169e0daae05b0e4e9919cf75727ada287d
15,685
cpp
C++
tests/tests/ChipmunkTest/drawSpace.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
tests/tests/ChipmunkTest/drawSpace.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
tests/tests/ChipmunkTest/drawSpace.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
/* Copyright (c) 2007 Scott Lembcke * * 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 "chipmunk.h" #include "drawSpace.h" #include "cocos2d.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include <limits.h> #include <string.h> using namespace cocos2d; /* IMPORTANT - READ ME! This file sets up a simple interface that the individual demos can use to get a Chipmunk space running and draw what's in it. In order to keep the Chipmunk examples clean and simple, they contain no graphics code. All drawing is done by accessing the Chipmunk structures at a very low level. It is NOT recommended to write a game or application this way as it does not scale beyond simple shape drawing and is very dependent on implementation details about Chipmunk which may change with little to no warning. */ #define LINE_COLOR 0.0f, 0.0f, 0.0f, 1.0f #define COLLISION_COLOR 1.0f, 0.0f, 0.0f, 1.0f #define BODY_COLOR 0.0f, 0.0f, 1.0f, 1.0f static void glColor_from_pointer(void *ptr) { unsigned long val = (long)ptr; // hash the pointer up nicely val = (val+0x7ed55d16) + (val<<12); val = (val^0xc761c23c) ^ (val>>19); val = (val+0x165667b1) + (val<<5); val = (val+0xd3a2646c) ^ (val<<9); val = (val+0xfd7046c5) + (val<<3); val = (val^0xb55a4f09) ^ (val>>16); // GLfloat v = (GLfloat)val/(GLfloat)ULONG_MAX; // v = 0.95f - v*0.15f; // // glColor3f(v, v, v); GLubyte r = (val>>0) & 0xFF; GLubyte g = (val>>8) & 0xFF; GLubyte b = (val>>16) & 0xFF; GLubyte max = r>g ? (r>b ? r : b) : (g>b ? g : b); const int mult = 127; const int add = 63; r = (r*mult)/max + add; g = (g*mult)/max + add; b = (b*mult)/max + add; // glColor4ub isn't implemented on some android devices // glColor4ub(r, g, b, 255); glColor4f( ((GLfloat)r)/255, ((GLfloat)g) / 255, ((GLfloat)b)/255, 1.0f ); } static void glColor_for_shape(cpShape *shape, cpSpace *space) { cpBody *body = shape->body; if(body){ if(body->node.next){ GLfloat v = 0.25f; glColor4f(v,v,v,1); return; } else if(body->node.idleTime > space->sleepTimeThreshold) { GLfloat v = 0.9f; glColor4f(v,v,v,1); return; } } glColor_from_pointer(shape); } static const GLfloat circleVAR[] = { 0.0000f, 1.0000f, 0.2588f, 0.9659f, 0.5000f, 0.8660f, 0.7071f, 0.7071f, 0.8660f, 0.5000f, 0.9659f, 0.2588f, 1.0000f, 0.0000f, 0.9659f, -0.2588f, 0.8660f, -0.5000f, 0.7071f, -0.7071f, 0.5000f, -0.8660f, 0.2588f, -0.9659f, 0.0000f, -1.0000f, -0.2588f, -0.9659f, -0.5000f, -0.8660f, -0.7071f, -0.7071f, -0.8660f, -0.5000f, -0.9659f, -0.2588f, -1.0000f, -0.0000f, -0.9659f, 0.2588f, -0.8660f, 0.5000f, -0.7071f, 0.7071f, -0.5000f, 0.8660f, -0.2588f, 0.9659f, 0.0000f, 1.0000f, 0.0f, 0.0f, // For an extra line to see the rotation. }; static const int circleVAR_count = sizeof(circleVAR)/sizeof(GLfloat)/2; static void drawCircleShape(cpBody *body, cpCircleShape *circle, cpSpace *space) { glVertexPointer(2, GL_FLOAT, 0, circleVAR); // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY // Needed states: GL_VERTEX_ARRAY, // Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY glDisable(GL_TEXTURE_2D); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glPushMatrix(); { cpVect center = circle->tc; glTranslatef(center.x, center.y, 0.0f); glRotatef(body->a*180.0f/(float)M_PI, 0.0f, 0.0f, 1.0f); glScalef(circle->r, circle->r, 1.0f); if(!circle->shape.sensor){ glColor_for_shape((cpShape *)circle, space); glDrawArrays(GL_TRIANGLE_FAN, 0, circleVAR_count - 1); } glColor4f(LINE_COLOR); glDrawArrays(GL_LINE_STRIP, 0, circleVAR_count); } glPopMatrix(); // restore default GL state glEnable(GL_TEXTURE_2D); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); } static const GLfloat pillVAR[] = { 0.0000f, 1.0000f, 1.0f, 0.2588f, 0.9659f, 1.0f, 0.5000f, 0.8660f, 1.0f, 0.7071f, 0.7071f, 1.0f, 0.8660f, 0.5000f, 1.0f, 0.9659f, 0.2588f, 1.0f, 1.0000f, 0.0000f, 1.0f, 0.9659f, -0.2588f, 1.0f, 0.8660f, -0.5000f, 1.0f, 0.7071f, -0.7071f, 1.0f, 0.5000f, -0.8660f, 1.0f, 0.2588f, -0.9659f, 1.0f, 0.0000f, -1.0000f, 1.0f, 0.0000f, -1.0000f, 0.0f, -0.2588f, -0.9659f, 0.0f, -0.5000f, -0.8660f, 0.0f, -0.7071f, -0.7071f, 0.0f, -0.8660f, -0.5000f, 0.0f, -0.9659f, -0.2588f, 0.0f, -1.0000f, -0.0000f, 0.0f, -0.9659f, 0.2588f, 0.0f, -0.8660f, 0.5000f, 0.0f, -0.7071f, 0.7071f, 0.0f, -0.5000f, 0.8660f, 0.0f, -0.2588f, 0.9659f, 0.0f, 0.0000f, 1.0000f, 0.0f, }; static const int pillVAR_count = sizeof(pillVAR)/sizeof(GLfloat)/3; static void drawSegmentShape(cpBody *body, cpSegmentShape *seg, cpSpace *space) { cpVect a = seg->ta; cpVect b = seg->tb; if(seg->r){ glVertexPointer(3, GL_FLOAT, 0, pillVAR); // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY // Needed states: GL_VERTEX_ARRAY, // Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY glDisable(GL_TEXTURE_2D); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glPushMatrix(); { cpVect d = cpvsub(b, a); cpVect r = cpvmult(d, seg->r/cpvlength(d)); const GLfloat matrix[] = { r.x, r.y, 0.0f, 0.0f, -r.y, r.x, 0.0f, 0.0f, d.x, d.y, 0.0f, 0.0f, a.x, a.y, 0.0f, 1.0f, }; glMultMatrixf(matrix); if(!seg->shape.sensor){ glColor_for_shape((cpShape *)seg, space); glDrawArrays(GL_TRIANGLE_FAN, 0, pillVAR_count); } glColor4f(LINE_COLOR); glDrawArrays(GL_LINE_LOOP, 0, pillVAR_count); } glPopMatrix(); // restore default GL state glEnable(GL_TEXTURE_2D); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); } else { glColor4f(LINE_COLOR); ccDrawLine(ccp(a.x, a.y),ccp(b.x, b.y)); } } static void drawPolyShape(cpBody *body, cpPolyShape *poly, cpSpace *space) { int count = poly->numVerts; #if CP_USE_DOUBLES glVertexPointer(2, GL_DOUBLE, 0, poly->tVerts); #else glVertexPointer(2, GL_FLOAT, 0, poly->tVerts); #endif // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY // Needed states: GL_VERTEX_ARRAY, // Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY glDisable(GL_TEXTURE_2D); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(!poly->shape.sensor){ glColor_for_shape((cpShape *)poly, space); glDrawArrays(GL_TRIANGLE_FAN, 0, count); } glColor4f(LINE_COLOR); glDrawArrays(GL_LINE_LOOP, 0, count); // restore default GL state glEnable(GL_TEXTURE_2D); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); } static void drawObject(cpShape *shape, cpSpace *space) { cpBody *body = shape->body; switch(shape->klass->type){ case CP_CIRCLE_SHAPE: drawCircleShape(body, (cpCircleShape *)shape, space); break; case CP_SEGMENT_SHAPE: drawSegmentShape(body, (cpSegmentShape *)shape, space); break; case CP_POLY_SHAPE: drawPolyShape(body, (cpPolyShape *)shape, space); break; default: CCLOG("Bad enumeration in drawObject().\n"); break; } } static const GLfloat springVAR[] = { 0.00f, 0.0f, 0.20f, 0.0f, 0.25f, 3.0f, 0.30f,-6.0f, 0.35f, 6.0f, 0.40f,-6.0f, 0.45f, 6.0f, 0.50f,-6.0f, 0.55f, 6.0f, 0.60f,-6.0f, 0.65f, 6.0f, 0.70f,-3.0f, 0.75f, 6.0f, 0.80f, 0.0f, 1.00f, 0.0f, }; static const int springVAR_count = sizeof(springVAR)/sizeof(GLfloat)/2; static void drawSpring(cpDampedSpring *spring, cpBody *body_a, cpBody *body_b) { cpVect a = cpvadd(body_a->p, cpvrotate(spring->anchr1, body_a->rot)); cpVect b = cpvadd(body_b->p, cpvrotate(spring->anchr2, body_b->rot)); glPointSize(5.0f); ccDrawPoint( ccp(a.x, a.y) ); ccDrawPoint( ccp(b.x, b.y) ); cpVect delta = cpvsub(b, a); // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY // Needed states: GL_VERTEX_ARRAY, // Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY glDisable(GL_TEXTURE_2D); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(2, GL_FLOAT, 0, springVAR); glPushMatrix(); { GLfloat x = a.x; GLfloat y = a.y; GLfloat cos = delta.x; GLfloat sin = delta.y; GLfloat s = 1.0f/cpvlength(delta); const GLfloat matrix[] = { cos, sin, 0.0f, 0.0f, -sin*s, cos*s, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, x, y, 0.0f, 1.0f, }; glMultMatrixf(matrix); glDrawArrays(GL_LINE_STRIP, 0, springVAR_count); } glPopMatrix(); // restore default GL state glEnable(GL_TEXTURE_2D); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); } static void drawConstraint(cpConstraint *constraint) { cpBody *body_a = constraint->a; cpBody *body_b = constraint->b; const cpConstraintClass *klass = constraint->klass; if(klass == cpPinJointGetClass()){ cpPinJoint *joint = (cpPinJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); glPointSize(5.0f); ccDrawPoint( ccp(a.x, a.y) ); ccDrawPoint( ccp(b.x, b.y) ); ccDrawLine( ccp(a.x, a.y), ccp(b.x, b.y) ); } else if(klass == cpSlideJointGetClass()){ cpSlideJoint *joint = (cpSlideJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); glPointSize(5.0f); ccDrawPoint( ccp(a.x, a.y) ); ccDrawPoint( ccp(b.x, b.y) ); ccDrawLine( ccp(a.x, a.y), ccp(b.x, b.y) ); } else if(klass == cpPivotJointGetClass()){ cpPivotJoint *joint = (cpPivotJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); glPointSize(10.0f); ccDrawPoint( ccp(a.x, a.y) ); ccDrawPoint( ccp(b.x, b.y) ); } else if(klass == cpGrooveJointGetClass()){ cpGrooveJoint *joint = (cpGrooveJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->grv_a, body_a->rot)); cpVect b = cpvadd(body_a->p, cpvrotate(joint->grv_b, body_a->rot)); cpVect c = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); glPointSize(5.0f); ccDrawPoint( ccp(c.x, c.y) ); ccDrawLine( ccp(a.x, a.y), ccp(b.x, b.y) ); } else if(klass == cpDampedSpringGetClass()){ drawSpring((cpDampedSpring *)constraint, body_a, body_b); } else { // printf("Cannot draw constraint\n"); } } static void drawBB(cpShape *shape, void *unused) { CCPoint vertices[] = { ccp(shape->bb.l, shape->bb.b), ccp(shape->bb.l, shape->bb.t), ccp(shape->bb.r, shape->bb.t), ccp(shape->bb.r, shape->bb.b), }; ccDrawPoly(vertices, 4, false); } // copied from cpSpaceHash.c static inline cpHashValue hash_func(cpHashValue x, cpHashValue y, cpHashValue n) { return (x*1640531513ul ^ y*2654435789ul) % n; } static void drawSpatialHash(cpSpaceHash *hash) { cpBB bb = cpBBNew(-320, -240, 320, 240); cpFloat dim = hash->celldim; int n = hash->numcells; int l = (int)floor(bb.l/dim); int r = (int)floor(bb.r/dim); int b = (int)floor(bb.b/dim); int t = (int)floor(bb.t/dim); for(int i=l; i<=r; i++){ for(int j=b; j<=t; j++){ int cell_count = 0; int index = hash_func(i,j,n); for(cpSpaceHashBin *bin = hash->table[index]; bin; bin = bin->next) cell_count++; GLfloat v = 1.0f - (GLfloat)cell_count/10.0f; glColor4f(v,v,v,1); // glRectf(i*dim, j*dim, (i + 1)*dim, (j + 1)*dim); } } } void drawSpace(cpSpace *space, drawSpaceOptions *options) { if(options->drawHash){ glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_TRUE); drawSpatialHash(space->activeShapes); glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE); drawSpatialHash(space->staticShapes); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } glLineWidth(options->lineThickness); if(options->drawShapes){ cpSpaceHashEach(space->activeShapes, (cpSpaceHashIterator)drawObject, space); cpSpaceHashEach(space->staticShapes, (cpSpaceHashIterator)drawObject, space); } glLineWidth(1.0f); if(options->drawBBs){ glColor4f(0.3f, 0.5f, 0.3f,1); cpSpaceHashEach(space->activeShapes, (cpSpaceHashIterator)drawBB, NULL); cpSpaceHashEach(space->staticShapes, (cpSpaceHashIterator)drawBB, NULL); } cpArray *constraints = space->constraints; glColor4f(0.5f, 1.0f, 0.5f, 1); for(int i=0, count = constraints->num; i<count; i++){ drawConstraint((cpConstraint *)constraints->arr[i]); } if(options->bodyPointSize){ glPointSize(options->bodyPointSize); cpArray *bodies = space->bodies; // cocos2d-x: use ccDrawPoints to optimize the speed CCPoint *aPoints = new CCPoint[bodies->num]; glColor4f(LINE_COLOR); for(int i=0, count = bodies->num; i<count; i++){ cpBody *body = (cpBody *)bodies->arr[i]; aPoints[i] = CCPoint(body->p.x, body->p.y); // ccDrawPoint( ccp(body->p.x, body->p.y) ); } ccDrawPoints( aPoints, bodies->num ); delete []aPoints; // glColor3f(0.5f, 0.5f, 0.5f); // cpArray *components = space->components; // for(int i=0; i<components->num; i++){ // cpBody *root = components->arr[i]; // cpBody *body = root, *next; // do { // next = body->node.next; // glVertex2f(body->p.x, body->p.y); // } while((body = next) != root); // } } if(options->collisionPointSize){ glPointSize(options->collisionPointSize); cpArray *arbiters = space->arbiters; for(int i=0; i<arbiters->num; i++){ cpArbiter *arb = (cpArbiter*)arbiters->arr[i]; // cocos2d-x: use ccDrawPoints to optimze the speed CCPoint *aPoints = new CCPoint[arb->numContacts]; glColor4f(COLLISION_COLOR); for(int i=0; i<arb->numContacts; i++){ cpVect v = arb->contacts[i].p; // ccDrawPoint( ccp(v.x, v.y) ); aPoints[i] = CCPoint(v.x, v.y); } ccDrawPoints( aPoints, arb->numContacts ); delete []aPoints; } } }
28.674589
95
0.653809
[ "shape" ]
ab7cf33390b3784053c6ec66f680e96a6ce96c15
8,887
cpp
C++
src/OT_Exact_L2.cpp
stegua/dotlib
754d93f16522714668e99a3c313a2acdc2cd0bd1
[ "MIT" ]
4
2018-02-21T20:19:36.000Z
2021-05-07T03:23:38.000Z
src/OT_Exact_L2.cpp
stegua/dotlib
754d93f16522714668e99a3c313a2acdc2cd0bd1
[ "MIT" ]
null
null
null
src/OT_Exact_L2.cpp
stegua/dotlib
754d93f16522714668e99a3c313a2acdc2cd0bd1
[ "MIT" ]
null
null
null
/** * @fileoverview Copyright (c) 2017-2018, Stefano Gualandi, * via Ferrata, 1, I-27100, Pavia, Italy * * @author stefano.gualandi@gmail.com (Stefano Gualandi) * */ #include "OT_Exact_L2.h"" /** * @brief Solve standard Trasportation Problem on the complete bipartite graph * using Wassertein distance W_1^2 (order 1, with cost=L_2) */ real_t solve_exact_W_1_2(const histogram_t& h1, const histogram_t& h2) { auto logger = spd::get("console"); using namespace lemon; real_t distance = std::numeric_limits<real_t>::max(); size_t d = h1.size(); size_t s = static_cast<size_t>(sqrt(d)); auto ID = [&s](size_t x, size_t y) { return x * s + y; }; // Time vars std::chrono::time_point<std::chrono::system_clock> start, end; // Start time. start = std::chrono::system_clock::now(); // Build the graph for max flow Graph g; // add d nodes for each histrogam (d+1) source, (d+2) target std::vector<Graph::Node> nodes_A; nodes_A.reserve(d); // add first d source nodes for first partition for (size_t i = 0; i < d; ++i) nodes_A.emplace_back(g.addNode()); std::vector<Graph::Node> nodes_B; nodes_B.reserve(d); // add first d source nodes for second partition for (size_t i = 0; i < d; ++i) nodes_B.emplace_back(g.addNode()); // Add arcs for complete bipartite graph std::vector<Graph::Arc> arcs; arcs.reserve(d*d); std::vector<real_t> arcs_costs; arcs_costs.reserve(d*d); for (int i = 0; i < s; ++i) for (int j = 0; j < s; ++j) { for (int v = 0; v < s; ++v) for (int w = 0; w < s; ++w) { arcs.emplace_back(g.addArc(nodes_A[ID(i, j)], nodes_B[ID(v, w)])); arcs_costs.emplace_back(sqrt(pow(double(i - v), 2) + pow(double(j - w), 2))); } } // End time. end = std::chrono::system_clock::now(); std::chrono::duration<double> inlineTimeElapsed = end - start; start = std::chrono::system_clock::now(); NetworkSimplex<Graph, LimitValueType, real_t> cycle(g); // lower and upper bounds, cost ListDigraph::ArcMap<LimitValueType> l_i(g), u_i(g); ListDigraph::ArcMap<real_t> c_i(g); // FLow balance ListDigraph::NodeMap<LimitValueType> b_i(g); for (size_t i = 0; i < d; ++i) { b_i[nodes_A[i]] = +LimitValueType(h1[i]); b_i[nodes_B[i]] = -LimitValueType(h2[i]); } // Add all edges for (size_t i = 0, i_max = arcs.size(); i < i_max; ++i) { const auto& a = arcs[i]; l_i[a] = 0; u_i[a] = cycle.INF; c_i[a] = std::trunc(MUL * arcs_costs[i]); } //set lower/upper bounds, cost cycle.lowerMap(l_i).upperMap(u_i).costMap(c_i).supplyMap(b_i); NetworkSimplex<Graph, LimitValueType, real_t>::ProblemType ret = cycle.run(); switch (ret) { case NetworkSimplex<Graph>::INFEASIBLE: logger->error("INFEASIBLE"); break; case NetworkSimplex<Graph>::OPTIMAL: logger->info("OPTIMAL"); break; case NetworkSimplex<Graph>::UNBOUNDED: logger->error("UNBOUNDED"); break; } real_t sol_value = cycle.totalCost()/ MUL; end = std::chrono::system_clock::now(); std::chrono::duration<double> run_time = end - start; logger->info("STE nodes {} arcs {} n {} N {} build_time {} cost {:.2f} run_time {}", countNodes(g), countArcs(g), h1.size(), s, inlineTimeElapsed.count(), sol_value, run_time.count()); return sol_value; } /** * @brief Solve standard Trasportation Problem on the complete bipartite graph * using Wassertein distance W_1^2 (order 1, with cost=L_2) */ real_t solve_exact_W_1_1(const histogram_t& h1, const histogram_t& h2) { auto logger = spd::get("console"); using namespace lemon; real_t distance = std::numeric_limits<real_t>::max(); size_t d = h1.size(); size_t s = static_cast<size_t>(sqrt(d)); auto ID = [&s](size_t x, size_t y) { return x * s + y; }; // Build the graph for max flow Graph g; // add d nodes for each histrogam (d+1) source, (d+2) target std::vector<Graph::Node> nodes_A; nodes_A.reserve(d); // add first d source nodes for first partition for (size_t i = 0; i < d; ++i) nodes_A.emplace_back(g.addNode()); std::vector<Graph::Node> nodes_B; nodes_B.reserve(d); // add first d source nodes for second partition for (size_t i = 0; i < d; ++i) nodes_B.emplace_back(g.addNode()); // Add arcs for complete bipartite graph std::vector<Graph::Arc> arcs; arcs.reserve(d*d); std::vector<real_t> arcs_costs; arcs_costs.reserve(d*d); for (int i = 0; i < s; ++i) for (int j = 0; j < s; ++j) { for (int v = 0; v < s; ++v) for (int w = 0; w < s; ++w) { arcs.emplace_back(g.addArc(nodes_A[ID(i, j)], nodes_B[ID(v, w)])); arcs_costs.emplace_back(double(i - v) + double(j - w)); } } logger->info("Input graph created with {} nodes and {} arcs", countNodes(g), countArcs(g)); NetworkSimplex<Graph, LimitValueType, real_t> cycle(g); // lower and upper bounds, cost ListDigraph::ArcMap<LimitValueType> l_i(g), u_i(g); ListDigraph::ArcMap<real_t> c_i(g); // FLow balance ListDigraph::NodeMap<LimitValueType> b_i(g); for (size_t i = 0; i < d; ++i) { b_i[nodes_A[i]] = +LimitValueType(h1[i]); b_i[nodes_B[i]] = -LimitValueType(h2[i]); } // Add all edges for (size_t i = 0, i_max = arcs.size(); i < i_max; ++i) { const auto& a = arcs[i]; l_i[a] = 0; u_i[a] = cycle.INF; c_i[a] = MUL*arcs_costs[i]; } //set lower/upper bounds, cost cycle.lowerMap(l_i).upperMap(u_i).costMap(c_i).supplyMap(b_i); NetworkSimplex<Graph, LimitValueType, real_t>::ProblemType ret = cycle.run(); switch (ret) { case NetworkSimplex<Graph>::INFEASIBLE: logger->error("INFEASIBLE"); break; case NetworkSimplex<Graph>::OPTIMAL: logger->info("OPTIMAL"); break; case NetworkSimplex<Graph>::UNBOUNDED: logger->error("UNBOUNDED"); break; } real_t sol_value = cycle.totalCost(); return sol_value; } /** * @brief Solve standard Trasportation Problem on the complete bipartite graph * using Wassertein distance W_1 ^ 2 (order 1, with cost = L_2) */ real_t solve_exact_W_1_8(const histogram_t& h1, const histogram_t& h2) { auto logger = spd::get("console"); using namespace lemon; real_t distance = std::numeric_limits<real_t>::max(); size_t d = h1.size(); size_t s = static_cast<size_t>(sqrt(d)); auto ID = [&s](size_t x, size_t y) { return x * s + y; }; // Build the graph for max flow Graph g; // add d nodes for each histrogam (d+1) source, (d+2) target std::vector<Graph::Node> nodes_A; nodes_A.reserve(d); // add first d source nodes for first partition for (size_t i = 0; i < d; ++i) nodes_A.emplace_back(g.addNode()); std::vector<Graph::Node> nodes_B; nodes_B.reserve(d); // add first d source nodes for second partition for (size_t i = 0; i < d; ++i) nodes_B.emplace_back(g.addNode()); // Add arcs for complete bipartite graph std::vector<Graph::Arc> arcs; arcs.reserve(d*d); std::vector<real_t> arcs_costs; arcs_costs.reserve(d*d); for (int i = 0; i < s; ++i) for (int j = 0; j < s; ++j) { for (int v = 0; v < s; ++v) for (int w = 0; w < s; ++w) { arcs.emplace_back(g.addArc(nodes_A[ID(i, j)], nodes_B[ID(v, w)])); arcs_costs.emplace_back(std::max(double(i - v), double(j - w))); } } logger->info("Input graph created with {} nodes and {} arcs", countNodes(g), countArcs(g)); NetworkSimplex<Graph, LimitValueType, real_t> cycle(g); // lower and upper bounds, cost ListDigraph::ArcMap<LimitValueType> l_i(g), u_i(g); ListDigraph::ArcMap<real_t> c_i(g); // FLow balance ListDigraph::NodeMap<LimitValueType> b_i(g); for (size_t i = 0; i < d; ++i) { b_i[nodes_A[i]] = +LimitValueType(h1[i]); b_i[nodes_B[i]] = -LimitValueType(h2[i]); } // Add all edges for (size_t i = 0, i_max = arcs.size(); i < i_max; ++i) { const auto& a = arcs[i]; l_i[a] = 0; u_i[a] = cycle.INF; c_i[a] = std::trunc(10000 * 65536 * arcs_costs[i]) / (10000 * 65536); } //set lower/upper bounds, cost cycle.lowerMap(l_i).upperMap(u_i).costMap(c_i).supplyMap(b_i); NetworkSimplex<Graph, LimitValueType, real_t>::ProblemType ret = cycle.run(); switch (ret) { case NetworkSimplex<Graph>::INFEASIBLE: logger->error("INFEASIBLE"); break; case NetworkSimplex<Graph>::OPTIMAL: logger->info("OPTIMAL"); break; case NetworkSimplex<Graph>::UNBOUNDED: logger->error("UNBOUNDED"); break; } real_t sol_value = cycle.totalCost(); return sol_value; }
28.853896
115
0.607292
[ "vector" ]
ab83766b1b109fb2e29ec5c4c489b9344a2420d6
13,530
cpp
C++
ftkGUI/ImageBrowser5D.cpp
tostathaina/farsight
7e9d6d15688735f34f7ca272e4e715acd11473ff
[ "Apache-2.0" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
ftkGUI/ImageBrowser5D.cpp
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
ftkGUI/ImageBrowser5D.cpp
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
/*========================================================================= Copyright 2009 Rensselaer Polytechnic Institute 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 "ImageBrowser5D.h" //#include "itkImageRegionConstIterator.h" //Destructor ImageBrowser5D::~ImageBrowser5D() { m_channelActors.clear(); m_lookuptable.clear(); m_volumeproperty.clear(); m_volumes.clear(); m_chflag.clear(); if(m_imageview) delete m_imageview; } //Constructors ImageBrowser5D::ImageBrowser5D(QString filename, RenderMode mode) { img = ftk::Image::New(); if( !img->LoadFile( filename.toStdString() ) ) return; m_mode = mode; //if( !img->LoadFileSeries("C:/TestImages/Ying_image - 5D - tiff/021805m5bwt_t%02d.tif",1,10,1) ) return; //m_mode = VOLUME; this->Setup(); } ImageBrowser5D::ImageBrowser5D(ftk::Image::Pointer img, RenderMode mode) { this->img = img; m_mode = mode; this->Setup(); } void ImageBrowser5D::Setup() { if(!img) return; for(int c=0; c<img->GetImageInfo()->numChannels; ++c) m_chflag.push_back(true); CreateObjects(); CreateLayout(); CreateLookupTable(); CreateVolumeProperties(); CreateInteractorStyle(); UpdateVSlider(); UpdateHSlider(); UpdateRenderer(); this->resize(img->GetImageInfo()->numColumns, img->GetImageInfo()->numRows); this->setAttribute ( Qt::WA_DeleteOnClose ); this->setWindowTitle(tr("Image Browser")); } void ImageBrowser5D::ToggleMode() { if(m_mode == VOLUME) SetMode(SLICE); else SetMode(VOLUME); } void ImageBrowser5D::SetMode(RenderMode mode) { if(mode != m_mode) { m_mode = mode; UpdateVSlider(); UpdateRenderer(); } } void ImageBrowser5D::ToggleShowChannel(int channel) { if(channel >= img->GetImageInfo()->numChannels) return; if(m_chflag.at(channel) == false) SetShowChannel(channel, true); else SetShowChannel(channel, false); } void ImageBrowser5D::SetShowChannel(int channel, bool show) { if(channel >= img->GetImageInfo()->numChannels) return; if(m_chflag.at(channel) != show) { m_chflag.at(channel) = show; if(m_mode == VOLUME) m_volumes.at(channel)->SetVisibility(show); else m_channelActors.at(channel)->SetVisibility(show); Rerender(); } } //Instantiate the objects: void ImageBrowser5D::CreateObjects() { vSlider = new QSlider(this); vSlider->setOrientation(Qt::Vertical); vSpin = new QSpinBox(this); vSpin->resize( vSpin->minimumSizeHint() ); vLabel = new QLabel("z",this); hSlider = new QSlider(this); hSlider->setOrientation(Qt::Horizontal); hSpin = new QSpinBox(this); hSpin->resize( hSpin->minimumSizeHint() ); hLabel = new QLabel("t",this); //CREATE A QVTK Widget for putting a QVTK renderer in QT window m_imageview = new QVTKWidget(this); m_vtkrenderer = RendererPointerType::New(); m_imageview->GetRenderWindow()->AddRenderer(m_vtkrenderer); //m_vtkrenderer->SetBackground(0.0,0.0,0.0); //setup connections connect(vSlider, SIGNAL(valueChanged(int)), this, SLOT(SetZ(int))); connect(hSlider, SIGNAL(valueChanged(int)), this, SLOT(SetT(int))); connect(vSlider, SIGNAL(valueChanged(int)), vSpin, SLOT(setValue(int))); connect(hSlider, SIGNAL(valueChanged(int)), hSpin, SLOT(setValue(int))); connect(vSpin, SIGNAL(valueChanged(int)), vSlider, SLOT(setValue(int))); connect(hSpin, SIGNAL(valueChanged(int)), hSlider, SLOT(setValue(int))); } //Create the Layout of all items in this widget. //Also creates many of the objects!! void ImageBrowser5D::CreateLayout() { QGridLayout *vsliderLayout = new QGridLayout; vsliderLayout->addWidget(vSpin,0,0,1,2); vsliderLayout->addWidget(vSlider,1,0,1,1); vsliderLayout->addWidget(vLabel,1,1,1,1); QHBoxLayout *hsliderLayout = new QHBoxLayout; hsliderLayout->addWidget(hSpin); hsliderLayout->addWidget(hLabel); hsliderLayout->addWidget(hSlider); QGridLayout *viewerLayout = new QGridLayout(); viewerLayout->addWidget(m_imageview, 0, 0); viewerLayout->addLayout(vsliderLayout, 0, 1); viewerLayout->addLayout(hsliderLayout, 1, 0); this->setLayout(viewerLayout); } //Creates lookup tables for each channel void ImageBrowser5D::CreateLookupTable() { if(!img) return; m_lookuptable.clear(); int chs = img->GetImageInfo()->numChannels; for(int i=0; i<chs; ++i) { LookupTablePointerType table = vtkSmartPointer<vtkLookupTable>::New(); table->SetRange(0, 255); // image intensity range std::vector<double> hsv = RGBtoHSV( img->GetImageInfo()->channelColors.at(i) ); //S and V should always be 1, it is H that I am most concerned about table->SetHueRange(hsv[0],hsv[0]); // Split Range table->SetSaturationRange(hsv[1],hsv[1]); // Full Color Saturation table->SetValueRange(hsv[2],hsv[2]); // from black to white table->SetAlphaRange(0,1); table->Build(); m_lookuptable.push_back(table); } } void ImageBrowser5D::CreateVolumeProperties() { if(!img) return; m_volumeproperty.clear(); int chs = img->GetImageInfo()->numChannels; for(int i=0; i<chs; ++i) { vtkSmartPointer<vtkPiecewiseFunction> opacityTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); opacityTransferFunction->AddPoint(2,0.0); opacityTransferFunction->AddPoint(255,1.0); vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New(); colorTransferFunction->AddRGBPoint(0.0,0.0,0.0,0.0); std::vector<unsigned char> rgb = img->GetImageInfo()->channelColors.at(i); colorTransferFunction->AddRGBPoint(255.0, double(rgb[0])/255.0 , double(rgb[1])/255.0, double(rgb[2])/255.0); VolumePropertyPointerType volumeProperty = vtkSmartPointer<vtkVolumeProperty>::New(); volumeProperty->SetScalarOpacity(opacityTransferFunction); volumeProperty->SetColor(colorTransferFunction); volumeProperty->SetInterpolationTypeToLinear(); volumeProperty->DisableGradientOpacityOn(); volumeProperty->ShadeOff(); m_volumeproperty.push_back(volumeProperty); } } //Sets up the renderer and adds actors to it for each channel. //This should only be called when T or CH selections change!! void ImageBrowser5D::UpdateRenderer() { if( !img ) return; if(m_mode == SLICE) UpdateImageActors(); else UpdateImageVolumes(); Rerender(); } void ImageBrowser5D::Rerender() { m_vtkrenderer->ResetCameraClippingRange(); //This fixes the "disappearing image" problem m_imageview->GetRenderWindow()->Render(); } //This functions removes all props from the renderer (2D and 3D) and clears the vector void ImageBrowser5D::CleanProps(void) { //Clean up existing actors for(int i=0; i< (int)m_channelActors.size(); ++i) { m_vtkrenderer->RemoveActor( m_channelActors.at(i) ); } m_channelActors.clear(); //Clean up existing volumes for(int i=0; i< (int)m_volumes.size(); ++i) { m_vtkrenderer->RemoveVolume( m_volumes.at(i) ); } m_volumes.clear(); } //vtkImageActors will display slices of a 3D image. void ImageBrowser5D::UpdateImageActors(void) { CleanProps(); //Create new actors: int chs = img->GetImageInfo()->numChannels; for(int i=0; i<chs; ++i) { vtkSmartPointer<vtkImageMapToColors> color = vtkSmartPointer<vtkImageMapToColors>::New(); vtkSmartPointer<vtkImageData> channel = img->GetVtkPtr(m_T,i); color->SetInput( channel ); color->SetLookupTable( m_lookuptable.at(i) ); //Create the actor and set its input to the image ImageActorPointerType actor = ImageActorPointerType::New(); actor->SetInput( color->GetOutput() ); actor->SetDisplayExtent(0, img->GetImageInfo()->numColumns - 1, 0, img->GetImageInfo()->numRows - 1, 0, 0 ); actor->SetZSlice( this->vSlider->value() ); actor->SetVisibility( m_chflag.at(i) ); actor->RotateWXYZ(180,0,0,1); actor->RotateWXYZ(180,0,1,0); m_channelActors.push_back(actor); m_vtkrenderer->AddActor(actor); } } //This creates volumes of the 3D image void ImageBrowser5D::UpdateImageVolumes(void) { CleanProps(); int chs = img->GetImageInfo()->numChannels; for(int i=0; i<chs; ++i) { /* vtkSmartPointer<vtkVolumeTextureMapper3D> vMapper = vtkSmartPointer<vtkVolumeTextureMapper3D>::New(); vMapper->SetSampleDistance(1); vMapper->SetInput(img->GetVtkPtr(m_T,i)); */ /* vtkSmartPointer<vtkVolumeRayCastMapper> vMapper = vtkSmartPointer<vtkVolumeRayCastMapper>::New(); vtkSmartPointer<vtkVolumeRayCastCompositeFunction> compFunction = vtkSmartPointer<vtkVolumeRayCastCompositeFunction>::New(); vMapper->SetVolumeRayCastFunction(compFunction); vMapper->SetInput(img->GetVtkPtr(m_T,i)); */ vtkSmartPointer<vtkFixedPointVolumeRayCastMapper> vMapper = vtkSmartPointer<vtkFixedPointVolumeRayCastMapper>::New(); vMapper->SetInput(img->GetVtkPtr(m_T,i)); /* vtkSmartPointer<vtkVolumeTextureMapper2D> vMapper = vtkSmartPointer<vtkVolumeTextureMapper2D>::New(); vMapper->SetMaximumNumberOfPlanes(50); vMapper->SetInput(img->GetVtkPtr(m_T,i)); vMapper->Update(); */ vtkSmartPointer<vtkVolume> volume = vtkSmartPointer<vtkVolume>::New(); volume->SetMapper(vMapper); volume->SetProperty( m_volumeproperty.at(i) ); volume->SetVisibility( m_chflag.at(i) ); volume->Update(); m_volumes.push_back(volume); m_vtkrenderer->AddVolume(volume); } } void ImageBrowser5D::SetZ(int z) { for (int i=0; i<(int)m_channelActors.size(); ++i) { m_channelActors.at(i)->SetZSlice(z); } Rerender(); } void ImageBrowser5D::SetT(int t) { m_T = t; UpdateRenderer(); } //************************************************************************************************** // 2 functions to update the z and t sliders and their corresponding spin boxes and labels // according to the current image size. //************************************************************************************************** void ImageBrowser5D::UpdateVSlider(void) //This slider is for z { if(!img || !vSlider || !vSpin || !vLabel) return; int z = img->GetImageInfo()->numZSlices; vSlider->setRange(0,z-1); vSpin->setRange(0,z-1); vSlider->setValue(0); vSpin->setValue(0); if (z > 1 && m_mode == SLICE) { vSlider->setEnabled(true); vSpin->setEnabled(true); vLabel->setEnabled(true); } else { vSlider->setEnabled(false); vSpin->setEnabled(false); vLabel->setEnabled(false); } } void ImageBrowser5D::UpdateHSlider(void) { if(!img || !hSlider || !hSpin || !hLabel) return; int t = img->GetImageInfo()->numTSlices; hSlider->setRange(0,t-1); hSlider->setValue(0); hSpin->setRange(0,t-1); hSpin->setValue(0); if (t > 1) { hSlider->setEnabled(true); hSpin->setEnabled(true); hLabel->setEnabled(true); } else { hSlider->setEnabled(false); hSpin->setEnabled(false); hLabel->setEnabled(false); } m_T = hSlider->value(); } //THIS FUNCTION COMPUTES THE HSV VALUES FROM RGB VALUES: std::vector<double> ImageBrowser5D::RGBtoHSV(std::vector<unsigned char> rgb) { std::vector<double> rVal; rVal.assign(3,0); if( rgb.size() != 3) return rVal; double h=0.0,s=0.0,v = 0.0; //Get RGB values and normalize: double r = (double)rgb.at(0)/255.0; double g = (double)rgb.at(1)/255.0; double b = (double)rgb.at(2)/255.0; double vmax = std::max(std::max(r,g),b); double vmin = std::min(std::min(r,g),b); double del_max = vmax-vmin; v = vmax; //VALUE if( del_max == 0 ) { h = 0; //HUE s = 0; //SATURATION } else { s = del_max / vmax; double del_R = ( ( ( vmax - r ) / 6 ) + ( del_max / 2 ) ) / del_max; double del_G = ( ( ( vmax - g ) / 6 ) + ( del_max / 2 ) ) / del_max; double del_B = ( ( ( vmax - b ) / 6 ) + ( del_max / 2 ) ) / del_max; if ( r == vmax ) h = del_B - del_G; else if ( g == vmax ) h = ( 1.0 / 3.0 ) + del_R - del_B; else if ( b == vmax ) h = ( 2.0 / 3.0 ) + del_G - del_R; if ( h < 0 ) h += 1; if ( h > 1 ) h -= 1; } rVal.at(0) = h; rVal.at(1) = s; rVal.at(2) = v; return rVal; } void ImageBrowser5D::CreateInteractorStyle(void) { m_kycallback = vtkSmartPointer<vtkCallbackCommand>::New(); m_kycallback->SetCallback(keyPress); m_kycallback->SetClientData(this); //m_imageview->GetRenderWindow()->GetInteractor()->SetInteractorStyle(NULL); //I want to keep mouse command observers, but change the key ones: m_imageview->GetRenderWindow()->GetInteractor()->RemoveObservers(vtkCommand::KeyPressEvent); m_imageview->GetRenderWindow()->GetInteractor()->RemoveObservers(vtkCommand::KeyReleaseEvent); m_imageview->GetRenderWindow()->GetInteractor()->RemoveObservers(vtkCommand::CharEvent); m_imageview->GetRenderWindow()->GetInteractor()->AddObserver(vtkCommand::KeyPressEvent, m_kycallback); } void ImageBrowser5D::keyPress(vtkObject * object, unsigned long eid, void *clientdata, void * callerdata) { ImageBrowser5D * client = (ImageBrowser5D*) clientdata; int keypressed = client->m_imageview->GetInteractor()->GetKeyCode(); switch(keypressed) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': client->ToggleShowChannel( int(keypressed) - int(48) - 1 ); //Convert key to integer break; case 'v': case 'V': client->SetMode(VOLUME); break; case 's': case 'S': client->SetMode(SLICE); break; } }
28.604651
126
0.695344
[ "render", "object", "vector", "3d" ]
ab83a2a65f684c9c5367c39fd572cbd87e6c5465
19,315
cpp
C++
test/old_tests/UnitTests/delegate.cpp
sylveon/cppwinrt
4d5c5ae3de386ce1f18c3410a27b9ceb40aa524d
[ "MIT" ]
859
2016-10-13T00:11:52.000Z
2019-05-06T15:45:46.000Z
test/old_tests/UnitTests/delegate.cpp
shinsetsu/cppwinrt
ae0378373d2318d91448b8697a91d5b65a1fb2e5
[ "MIT" ]
655
2019-10-08T12:15:16.000Z
2022-03-31T18:26:40.000Z
test/old_tests/UnitTests/delegate.cpp
shinsetsu/cppwinrt
ae0378373d2318d91448b8697a91d5b65a1fb2e5
[ "MIT" ]
137
2016-10-13T04:19:59.000Z
2018-11-09T05:08:03.000Z
#include "pch.h" #include "catch.hpp" using namespace winrt; using namespace Windows; using namespace Windows::Graphics::Display; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; // // Each of the sections in this test case exercises a unique edge case presented by an existing delegate in the Windows SDK. // TEST_CASE("delegate,return") { // // This delegate returns a bool value. // SECTION("PerceptionStartFaceAuthenticationHandler") { using namespace Windows::Devices::Perception::Provider; bool expected = true; PerceptionStartFaceAuthenticationHandler handler = [&] (IPerceptionFaceAuthenticationGroup const &) { return expected; }; REQUIRE(true == handler(nullptr)); expected = false; REQUIRE(false == handler(nullptr)); } // // This delegate returns an IInspectable value. // SECTION("CreateDefaultValueCallback") { using namespace Windows::Foundation; using namespace Windows::UI::Xaml; CreateDefaultValueCallback handler = [] { return Uri(L"http://moderncpp.com/"); }; Windows::Foundation::IInspectable result = handler(); Uri uri = result.as<Uri>(); REQUIRE(uri.Domain() == L"moderncpp.com"); } // // This one covers all the particular ways you can return a string from a delegate, which happens to require specific TMP support. // SECTION("ListViewItemToKeyHandler") { using namespace Windows::UI::Xaml::Controls; { ListViewItemToKeyHandler handler = [] (Windows::Foundation::IInspectable const &) { return L"raw"; }; hstring result = handler(nullptr); REQUIRE(result == L"raw"); } { ListViewItemToKeyHandler handler = [](Windows::Foundation::IInspectable const &) { return hstring(L"hstring"); }; hstring result = handler(nullptr); REQUIRE(result == L"hstring"); } } // // This just verifies that the delegate is correctly projected to return an IAsyncOperation. // SECTION("ListViewKeyToItemHandler") { using namespace Windows::Foundation; using namespace Windows::UI::Xaml::Controls; ListViewKeyToItemHandler handler = [] (hstring const&) { return nullptr; }; IAsyncOperation<Windows::Foundation::IInspectable> result = handler(L"key"); } } Windows::Foundation::IInspectable Handler() { return Uri(L"http://free/"); } struct MemberHandler { Uri m_uri { L"http://member/" }; Windows::Foundation::IInspectable Handler() { return m_uri; } }; TEST_CASE("delegate,binding") { SECTION("free function") { using namespace Windows::Foundation; using namespace Windows::UI::Xaml; CreateDefaultValueCallback handler = Handler; Windows::Foundation::IInspectable result = handler(); Uri uri = result.as<Uri>(); REQUIRE(uri.Host() == L"free"); } SECTION("member function") { using namespace Windows::Foundation; using namespace Windows::UI::Xaml; MemberHandler that; CreateDefaultValueCallback handler = { &that, &MemberHandler::Handler }; Windows::Foundation::IInspectable result = handler(); Uri uri = result.as<Uri>(); REQUIRE(uri.Host() == L"member"); } SECTION("lambda") { using namespace Windows::Foundation; using namespace Windows::UI::Xaml; CreateDefaultValueCallback handler = [] { return Uri(L"http://lambda/"); }; Windows::Foundation::IInspectable result = handler(); Uri uri = result.as<Uri>(); REQUIRE(uri.Host() == L"lambda"); } } // // Delegates defined in the base library // static void AsyncActionCompletedHandler_Free(IAsyncAction const & sender, AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); } struct AsyncActionCompletedHandler_Member { void Handler(IAsyncAction const & sender, AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); } }; TEST_CASE("delegate,AsyncActionCompletedHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { AsyncActionCompletedHandler a; AsyncActionCompletedHandler b = nullptr; } SECTION("lambda") { AsyncActionCompletedHandler h = [] (IAsyncAction const & sender, AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); }; h(nullptr, AsyncStatus::Completed); } SECTION("free function") { AsyncActionCompletedHandler h = AsyncActionCompletedHandler_Free; h(nullptr, AsyncStatus::Completed); } SECTION("member function") { AsyncActionCompletedHandler_Member object; AsyncActionCompletedHandler h { &object, &AsyncActionCompletedHandler_Member::Handler }; h(nullptr, AsyncStatus::Completed); } } static void AsyncActionProgressHandler_Free(IAsyncActionWithProgress<double> const & sender, double args) { REQUIRE(sender == nullptr); REQUIRE(args == 123.0); } struct AsyncActionProgressHandler_Member { void Handler(IAsyncActionWithProgress<double> const & sender, double args) { REQUIRE(sender == nullptr); REQUIRE(args == 123.0); } }; TEST_CASE("delegate,AsyncActionProgressHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { AsyncActionProgressHandler<double> a; AsyncActionProgressHandler<double> b = nullptr; } SECTION("lambda") { AsyncActionProgressHandler<double> h = [](IAsyncActionWithProgress<double> const & sender, double args) { REQUIRE(sender == nullptr); REQUIRE(args == 123.0); }; h(nullptr, 123.0); } SECTION("free function") { AsyncActionProgressHandler<double> h = AsyncActionProgressHandler_Free; h(nullptr, 123.0); } SECTION("member function") { AsyncActionProgressHandler_Member object; AsyncActionProgressHandler<double> h{ &object, &AsyncActionProgressHandler_Member::Handler }; h(nullptr, 123.0); } } static void AsyncActionWithProgressCompletedHandler_Free(const IAsyncActionWithProgress<double> & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); } struct AsyncActionWithProgressCompletedHandler_Member { void Handler(const IAsyncActionWithProgress<double> & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); } }; TEST_CASE("delegate,AsyncActionWithProgressCompletedHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { AsyncActionWithProgressCompletedHandler<double> a; AsyncActionWithProgressCompletedHandler<double> b = nullptr; } SECTION("lambda") { AsyncActionWithProgressCompletedHandler<double> h = [](const IAsyncActionWithProgress<double> & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); }; h(nullptr, AsyncStatus::Completed); } SECTION("free function") { AsyncActionWithProgressCompletedHandler<double> h = AsyncActionWithProgressCompletedHandler_Free; h(nullptr, AsyncStatus::Completed); } SECTION("member function") { AsyncActionWithProgressCompletedHandler_Member object; AsyncActionWithProgressCompletedHandler<double> h{ &object, &AsyncActionWithProgressCompletedHandler_Member::Handler }; h(nullptr, AsyncStatus::Completed); } } static void AsyncOperationProgressHandler_Free(const IAsyncOperationWithProgress<uint64_t, uint64_t> & sender, uint64_t args) { REQUIRE(sender == nullptr); REQUIRE(args == 123); } struct AsyncOperationProgressHandler_Member { void Handler(const IAsyncOperationWithProgress<uint64_t, uint64_t> & sender, uint64_t args) { REQUIRE(sender == nullptr); REQUIRE(args == 123); } }; TEST_CASE("delegate,AsyncOperationProgressHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { AsyncOperationProgressHandler<uint64_t, uint64_t> a; AsyncOperationProgressHandler<uint64_t, uint64_t> b = nullptr; } SECTION("lambda") { AsyncOperationProgressHandler<uint64_t, uint64_t> h = [](const IAsyncOperationWithProgress<uint64_t, uint64_t> & sender, uint64_t args) { REQUIRE(sender == nullptr); REQUIRE(args == 123); }; h(nullptr, 123); } SECTION("free function") { AsyncOperationProgressHandler<uint64_t, uint64_t> h = AsyncOperationProgressHandler_Free; h(nullptr, 123); } SECTION("member function") { AsyncOperationProgressHandler_Member object; AsyncOperationProgressHandler<uint64_t, uint64_t> h{ &object, &AsyncOperationProgressHandler_Member::Handler }; h(nullptr, 123); } } static void AsyncOperationWithProgressCompletedHandler_Free(const IAsyncOperationWithProgress<uint64_t, uint64_t> & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); } struct AsyncOperationWithProgressCompletedHandler_Member { void Handler(const IAsyncOperationWithProgress<uint64_t, uint64_t> & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); } }; TEST_CASE("delegate,AsyncOperationWithProgressCompletedHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { AsyncOperationWithProgressCompletedHandler<uint64_t, uint64_t> a; AsyncOperationWithProgressCompletedHandler<uint64_t, uint64_t> b = nullptr; } SECTION("lambda") { AsyncOperationWithProgressCompletedHandler<uint64_t, uint64_t> h = [](const IAsyncOperationWithProgress<uint64_t, uint64_t> & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); }; h(nullptr, AsyncStatus::Completed); } SECTION("free function") { AsyncOperationWithProgressCompletedHandler<uint64_t, uint64_t> h = AsyncOperationWithProgressCompletedHandler_Free; h(nullptr, AsyncStatus::Completed); } SECTION("member function") { AsyncOperationWithProgressCompletedHandler_Member object; AsyncOperationWithProgressCompletedHandler<uint64_t, uint64_t> h{ &object, &AsyncOperationWithProgressCompletedHandler_Member::Handler }; h(nullptr, AsyncStatus::Completed); } } static void AsyncOperationCompletedHandler_Free(IAsyncOperation<bool> const & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); } struct AsyncOperationCompletedHandler_Member { void Handler(IAsyncOperation<bool> const & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); } }; TEST_CASE("delegate,AsyncOperationCompletedHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { AsyncOperationCompletedHandler<bool> a; AsyncOperationCompletedHandler<bool> b = nullptr; } SECTION("lambda") { AsyncOperationCompletedHandler<bool> h = [](IAsyncOperation<bool> const & sender, const AsyncStatus args) { REQUIRE(sender == nullptr); REQUIRE(args == AsyncStatus::Completed); }; h(nullptr, AsyncStatus::Completed); } SECTION("free function") { AsyncOperationCompletedHandler<bool> h = AsyncOperationCompletedHandler_Free; h(nullptr, AsyncStatus::Completed); } SECTION("member function") { AsyncOperationCompletedHandler_Member object; AsyncOperationCompletedHandler<bool> h{ &object, &AsyncOperationCompletedHandler_Member::Handler }; h(nullptr, AsyncStatus::Completed); } } static void EventHandler_Free(const Windows::Foundation::IInspectable & sender, const Windows::Foundation::IInspectable & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); } struct EventHandler_Member { void Handler(const Windows::Foundation::IInspectable & sender, const Windows::Foundation::IInspectable & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); } }; TEST_CASE("delegate,EventHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { EventHandler<bool> a; EventHandler<bool> b = nullptr; } SECTION("lambda") { EventHandler<Windows::Foundation::IInspectable> h = [](const Windows::Foundation::IInspectable & sender, const Windows::Foundation::IInspectable & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); }; h(nullptr, nullptr); } SECTION("free function") { EventHandler<Windows::Foundation::IInspectable> h = EventHandler_Free; h(nullptr, nullptr); } SECTION("member function") { EventHandler_Member object; EventHandler<Windows::Foundation::IInspectable> h{ &object, &EventHandler_Member::Handler }; h(nullptr, nullptr); } } static void TypedEventHandler_Free(const Windows::Foundation::IInspectable & sender, const Windows::Foundation::IInspectable & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); } struct TypedEventHandler_Member { void Handler(const Windows::Foundation::IInspectable & sender, const Windows::Foundation::IInspectable & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); } }; TEST_CASE("delegate,TypedEventHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { TypedEventHandler<DisplayInformation, Windows::Foundation::IInspectable> a; TypedEventHandler<DisplayInformation, Windows::Foundation::IInspectable> b = nullptr; } SECTION("lambda") { TypedEventHandler<DisplayInformation, Windows::Foundation::IInspectable> h = [](const DisplayInformation & sender, const Windows::Foundation::IInspectable & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); }; h(nullptr, nullptr); } SECTION("free function") { TypedEventHandler<DisplayInformation, Windows::Foundation::IInspectable> h = TypedEventHandler_Free; h(nullptr, nullptr); } SECTION("member function") { TypedEventHandler_Member object; TypedEventHandler<DisplayInformation, Windows::Foundation::IInspectable> h{ &object, &TypedEventHandler_Member::Handler }; h(nullptr, nullptr); } } static void VectorChangedEventHandler_Free(IObservableVector<Windows::Foundation::IInspectable> const & sender, IVectorChangedEventArgs const & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); } struct VectorChangedEventHandler_Member { void Handler(IObservableVector<Windows::Foundation::IInspectable> const & sender, IVectorChangedEventArgs const & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); } }; TEST_CASE("delegate,VectorChangedEventHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { VectorChangedEventHandler<Windows::Foundation::IInspectable> a; VectorChangedEventHandler<Windows::Foundation::IInspectable> b = nullptr; } SECTION("lambda") { VectorChangedEventHandler<Windows::Foundation::IInspectable> h = [](IObservableVector<Windows::Foundation::IInspectable> const & sender, IVectorChangedEventArgs const & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); }; h(nullptr, nullptr); } SECTION("free function") { VectorChangedEventHandler<Windows::Foundation::IInspectable> h = VectorChangedEventHandler_Free; h(nullptr, nullptr); } SECTION("member function") { VectorChangedEventHandler_Member object; VectorChangedEventHandler<Windows::Foundation::IInspectable> h{ &object, &VectorChangedEventHandler_Member::Handler }; h(nullptr, nullptr); } } static void MapChangedEventHandler_Free(IObservableMap<hstring, Windows::Foundation::IInspectable> const & sender, IMapChangedEventArgs<hstring> const & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); } struct MapChangedEventHandler_Member { void Handler(IObservableMap<hstring, Windows::Foundation::IInspectable> const & sender, IMapChangedEventArgs<hstring> const & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); } }; TEST_CASE("delegate,MapChangedEventHandler") { // // This section verifies that the default and nullptr_t constructor is present. // SECTION("default") { MapChangedEventHandler<hstring, Windows::Foundation::IInspectable> a; MapChangedEventHandler<hstring, Windows::Foundation::IInspectable> b = nullptr; } SECTION("lambda") { MapChangedEventHandler<hstring, Windows::Foundation::IInspectable> h = [](IObservableMap<hstring, Windows::Foundation::IInspectable> const & sender, IMapChangedEventArgs<hstring> const & args) { REQUIRE(sender == nullptr); REQUIRE(args == nullptr); }; h(nullptr, nullptr); } SECTION("free function") { MapChangedEventHandler<hstring, Windows::Foundation::IInspectable> h = MapChangedEventHandler_Free; h(nullptr, nullptr); } SECTION("member function") { MapChangedEventHandler_Member object; MapChangedEventHandler<hstring, Windows::Foundation::IInspectable> h{ &object, &MapChangedEventHandler_Member::Handler }; h(nullptr, nullptr); } } TEST_CASE("delegate,collection") { // // Mostly a compiliation test to ensure that we can create collections of delegates. This is a rare corner case that was // previously not working. // IVector<EventHandler<int>> v = single_threaded_vector<EventHandler<int>>(); std::array<EventHandler<int>, 10> a; REQUIRE(0 == v.GetMany(0, a)); }
27.871573
200
0.662231
[ "object" ]
ab84acc4710ace324d3a54c16eac1c5410c8ada8
11,444
cpp
C++
Code/BasicFilters/btkForcePlatformWrenchFilter.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
61
2015-04-21T20:40:37.000Z
2022-03-25T03:35:03.000Z
Code/BasicFilters/btkForcePlatformWrenchFilter.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
17
2015-06-23T20:51:57.000Z
2020-08-17T17:08:57.000Z
Code/BasicFilters/btkForcePlatformWrenchFilter.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
56
2015-05-11T11:04:35.000Z
2022-01-15T20:37:04.000Z
/* * The Biomechanical ToolKit * Copyright (c) 2009-2014, Arnaud Barré * 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(s) of the copyright holders 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. */ #include "btkForcePlatformWrenchFilter.h" #include "btkConvert.h" namespace btk { /** * @class ForcePlatformWrenchFilter btkForcePlatformWrenchFilter.h * @brief Calcule the wrench of the center of the force platform data, expressed in the global frame (by default). * * Based on the given collection of forceplate set in input, this filter transform the associated analog channels in forces and moments. * This transformation take into account the type of each force platform. * * You can use the method SetTransformToGlobalFrame() to have the wrench expressed in the frame of the force platform. * * @ingroup BTKBasicFilters */ /** * @typedef ForcePlatformWrenchFilter::Pointer * Smart pointer associated with a ForcePlatformWrenchFilter object. */ /** * @typedef ForcePlatformWrenchFilter::ConstPointer * Smart pointer associated with a const ForcePlatformWrenchFilter object. */ /** * @fn static Pointer ForcePlatformWrenchFilter::New(); * Creates a smart pointer associated with a ForcePlatformWrenchFilter object. */ /** * @fn WrenchCollection::Pointer ForcePlatformWrenchFilter::GetInput() * Gets the input registered with this process. */ /** * @fn void ForcePlatformWrenchFilter::SetInput(ForcePlatform::Pointer input) * Sets the input required with this process. This input is transformed in a collection force platforms with a single force platform. */ /** * @fn void ForcePlatformWrenchFilter::SetInput(ForcePlatformCollection::Pointer input) * Sets the input required with this process. */ /** * @fn PointCollection::Pointer ForcePlatformWrenchFilter::GetOutput() * Gets the output created with this process. */ /** * Sets the flag to activate the transformation to the global frame. */ void ForcePlatformWrenchFilter::SetTransformToGlobalFrame(bool activation) { if (this->m_GlobalTransformationActivated == activation) return; this->m_GlobalTransformationActivated = activation; this->Modified(); }; /** * @fn bool ForcePlatformWrenchFilter::GetTransformToGlobalFrame() const * Returns the activation flag for the transformation in the global frame. */ /** * Constructor. Sets the number of inputs and outputs to 1. */ ForcePlatformWrenchFilter::ForcePlatformWrenchFilter() : ProcessObject() { this->SetInputNumber(1); this->SetOutputNumber(1); this->m_GlobalTransformationActivated = true; }; /** * @fn ForcePlatformCollection::Pointer ForcePlatformWrenchFilter::GetInput(int idx) * Returns the input at the index @a idx. */ /** * @fn WrenchCollection::Pointer ForcePlatformWrenchFilter::GetOutput(int idx) * Returns the output at the index @a idx. */ /** * Creates a WrenchCollection:Pointer object and return it as a DataObject::Pointer. */ DataObject::Pointer ForcePlatformWrenchFilter::MakeOutput(int /* idx */) { return WrenchCollection::New(); }; /** * Generates the outputs' data. */ void ForcePlatformWrenchFilter::GenerateData() { WrenchCollection::Pointer output = this->GetOutput(); ForcePlatformCollection::Pointer input = this->GetInput(); if (input != ForcePlatformCollection::Null) { int inc = 0; for (ForcePlatformCollection::ConstIterator it = input->Begin() ; it != input->End() ; ++it) { ++inc; if ((*it)->GetChannelNumber() == 0) { btkWarningMacro("Unexpected number of analog channels (0) for force platform #" + ToString(inc)); continue; } int frameNumber = (*it)->GetChannel(0)->GetFrameNumber(); Wrench::Pointer wrh; if (inc <= output->GetItemNumber()) { wrh = output->GetItem(inc-1); wrh->SetFrameNumber(frameNumber); output->Modified(); } else { wrh = Wrench::New(this->GetWrenchPrefix() + ToString(inc), frameNumber); output->InsertItem(wrh); } wrh->Modified(); // Residuals wrh->GetPosition()->GetResiduals().setZero(frameNumber); wrh->GetForce()->GetResiduals().setZero(frameNumber); wrh->GetMoment()->GetResiduals().setZero(frameNumber); // Values switch((*it)->GetType()) { // 6 channels case 1: wrh->GetForce()->GetValues().col(0) = (*it)->GetChannel(0)->GetValues(); wrh->GetForce()->GetValues().col(1) = (*it)->GetChannel(1)->GetValues(); wrh->GetForce()->GetValues().col(2) = (*it)->GetChannel(2)->GetValues(); wrh->GetPosition()->GetValues().col(0) = (*it)->GetChannel(3)->GetValues(); wrh->GetPosition()->GetValues().col(1) = (*it)->GetChannel(4)->GetValues(); wrh->GetPosition()->GetValues().col(2).setZero(); wrh->GetMoment()->GetValues().col(0).setZero(); wrh->GetMoment()->GetValues().col(1).setZero(); wrh->GetMoment()->GetValues().col(2) = (*it)->GetChannel(5)->GetValues(); this->FinishTypeI(wrh, *it, inc); break; case 2: case 4: case 5: wrh->GetForce()->GetValues().col(0) = (*it)->GetChannel(0)->GetValues(); wrh->GetForce()->GetValues().col(1) = (*it)->GetChannel(1)->GetValues(); wrh->GetForce()->GetValues().col(2) = (*it)->GetChannel(2)->GetValues(); wrh->GetMoment()->GetValues().col(0) = (*it)->GetChannel(3)->GetValues(); wrh->GetMoment()->GetValues().col(1) = (*it)->GetChannel(4)->GetValues(); wrh->GetMoment()->GetValues().col(2) = (*it)->GetChannel(5)->GetValues(); this->FinishAMTI(wrh, *it, inc); break; case 3: // Fx wrh->GetForce()->GetValues().col(0) = (*it)->GetChannel(0)->GetValues() + (*it)->GetChannel(1)->GetValues(); // Fy wrh->GetForce()->GetValues().col(1) = (*it)->GetChannel(2)->GetValues() + (*it)->GetChannel(3)->GetValues(); // Fz wrh->GetForce()->GetValues().col(2) = (*it)->GetChannel(4)->GetValues() + (*it)->GetChannel(5)->GetValues() + (*it)->GetChannel(6)->GetValues() + (*it)->GetChannel(7)->GetValues(); // Mx wrh->GetMoment()->GetValues().col(0) = (*it)->GetOrigin().y() * ((*it)->GetChannel(4)->GetValues() + (*it)->GetChannel(5)->GetValues() - (*it)->GetChannel(6)->GetValues() - (*it)->GetChannel(7)->GetValues()); // My wrh->GetMoment()->GetValues().col(1) = (*it)->GetOrigin().x() * ((*it)->GetChannel(5)->GetValues() + (*it)->GetChannel(6)->GetValues() - (*it)->GetChannel(4)->GetValues() - (*it)->GetChannel(7)->GetValues()); // Mz wrh->GetMoment()->GetValues().col(2) = (*it)->GetOrigin().y() * ((*it)->GetChannel(1)->GetValues() - (*it)->GetChannel(0)->GetValues()) + (*it)->GetOrigin().x() * ((*it)->GetChannel(2)->GetValues() - (*it)->GetChannel(3)->GetValues()); this->FinishKistler(wrh, *it, inc); break; case 6: btkErrorMacro("Force Platform type 6 is not yet supported. Please, report this to the developers"); break; case 7: btkErrorMacro("Force Platform type 7 is not yet supported. Please, report this to the developers"); break; case 11: btkErrorMacro("Force Platform type 11 is not yet supported. Please, report this to the developers"); break; case 12: btkErrorMacro("Force Platform type 12 is not yet supported. Please, report this to the developers"); break; case 21: btkErrorMacro("Force Platform type 21 is not yet supported. Please, report this to the developers"); break; } if (this->m_GlobalTransformationActivated) this->TransformToGlobal(wrh, (*it)->GetCorners()); } output->SetItemNumber(input->GetItemNumber()); } }; /** * Finish the computation of the wrench for the force platform type I. * Because, it is force platform Type I, the position is not set to the origin, but measured to the COP. The moment must be corrected! */ void ForcePlatformWrenchFilter::FinishTypeI(Wrench::Pointer wrh , ForcePlatform::Pointer /* fp */, int /* index */) { typedef Eigen::Array<double, Eigen::Dynamic, 1> Component; Component Fx = wrh->GetForce()->GetValues().col(0).array(); Component Fy = wrh->GetForce()->GetValues().col(1).array(); Component Fz = wrh->GetForce()->GetValues().col(2).array(); Component Mx = wrh->GetMoment()->GetValues().col(0).array(); Component My = wrh->GetMoment()->GetValues().col(1).array(); Component Mz = wrh->GetMoment()->GetValues().col(2).array(); Component Px = wrh->GetPosition()->GetValues().col(0).array(); Component Py = wrh->GetPosition()->GetValues().col(1).array(); Component Pz = wrh->GetPosition()->GetValues().col(2).array(); Mx -= Fy * Pz - Py * Fz; My -= Fz * Px - Pz * Fx; Mz -= Fx * Py - Px * Fy; wrh->GetMoment()->GetValues().col(0) = Mx; wrh->GetMoment()->GetValues().col(1) = My; wrh->GetMoment()->GetValues().col(2) = Mz; }; /** * Finish the computation of the wrench for the AMTI force platform (nothing to do). */ void ForcePlatformWrenchFilter::FinishAMTI(Wrench::Pointer /* wrh */, ForcePlatform::Pointer /* fp */, int /* index */) {}; /** * Finish the computation of the wrench for the Kistler force platform (nothing to do). */ void ForcePlatformWrenchFilter::FinishKistler(Wrench::Pointer /* wrh */, ForcePlatform::Pointer /* fp */, int /* index */) {}; };
42.228782
247
0.630811
[ "object", "transform" ]
ab86780fc8b33dcc774993c03a3e8a40678d91a4
770
cpp
C++
cppprimer_anwser/9.7.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
cppprimer_anwser/9.7.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
cppprimer_anwser/9.7.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <forward_list> #include <list> #include <map> #include <deque> #include <algorithm> template <typename T> void printContainer(const std::string desc, const T& container) { std::cout <<desc << " Container Have: " << std::endl; std::for_each(container.begin(), container.end(), [](auto& p) { std::cout << p << " "; } ); std::cout << std::endl; } int main() { using namespace std; vector<int> vii {1,2,3,4,5,6,7,89,0}; vector<int>::value_type iii = vii[2]; vector<int>::reference riii = vii[2]; riii = 1000; cout << "vector<int>::value_type iii = " << iii << endl; cout << "vector<int>::reference riii = " << riii << endl; cout << "vector<int> vii[2] = " << vii[2] << endl; }
27.5
95
0.593506
[ "vector" ]
ab92421d5093901004b743cb4704c0079ecaeacb
40,256
cpp
C++
Source/Vk.cpp
marcussvensson92/vulkan_testbed
6cfbee9fd5fb245f10c1d5694812eda6232b9a6c
[ "MIT" ]
10
2020-03-26T08:51:29.000Z
2021-08-17T07:43:12.000Z
Source/Vk.cpp
marcussvensson92/vulkan_testbed
6cfbee9fd5fb245f10c1d5694812eda6232b9a6c
[ "MIT" ]
null
null
null
Source/Vk.cpp
marcussvensson92/vulkan_testbed
6cfbee9fd5fb245f10c1d5694812eda6232b9a6c
[ "MIT" ]
null
null
null
#include "Vk.h" #define VMA_IMPLEMENTATION #include <vk_mem_alloc.h> _Vk Vk; static const VkDeviceSize UPLOAD_BUFFER_SIZE = 1024 * 1024 * 1024; static const VkDeviceSize UPLOAD_BUFFER_MASK = UPLOAD_BUFFER_SIZE - 1; static_assert((UPLOAD_BUFFER_SIZE & UPLOAD_BUFFER_MASK) == 0, "UPLOAD_BUFFER_SIZE must be a power of two"); static const uint32_t TIMESTAMP_QUERY_POOL_SIZE = 256; static_assert((TIMESTAMP_QUERY_POOL_SIZE & 1) == 0, "TIMESTAMP_QUERY_POOL_SIZE must be an even number"); static VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT, uint64_t, size_t, int32_t code, const char*, const char* message, void*) { if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0) { VkError(message); } else if ((flags & (VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)) != 0) { printf("Warning: %s\n", message); } else { printf("Information: %s\n", message); } return VK_FALSE; } static void CreateSwapchain(uint32_t width, uint32_t height, uint32_t image_count, VkDisplayMode display_mode) { VkSurfaceCapabilitiesKHR surface_capabilities = {}; VK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(Vk.PhysicalDevice, Vk.Surface, &surface_capabilities)); Vk.SwapchainImageExtent.width = VkMin(VkMax(width, surface_capabilities.minImageExtent.width), surface_capabilities.maxImageExtent.width); Vk.SwapchainImageExtent.height = VkMin(VkMax(height, surface_capabilities.minImageExtent.height), surface_capabilities.maxImageExtent.height); Vk.SwapchainImageCount = surface_capabilities.maxImageCount == 0 ? VkMax(image_count, surface_capabilities.minImageCount) : VkMin(VkMax(image_count, surface_capabilities.minImageCount), surface_capabilities.maxImageCount); Vk.DisplayMode = display_mode; uint32_t surface_format_count = 0; VK(vkGetPhysicalDeviceSurfaceFormatsKHR(Vk.PhysicalDevice, Vk.Surface, &surface_format_count, NULL)); std::vector<VkSurfaceFormatKHR> surface_formats(surface_format_count); VK(vkGetPhysicalDeviceSurfaceFormatsKHR(Vk.PhysicalDevice, Vk.Surface, &surface_format_count, surface_formats.data())); bool surface_format_supported = false; switch (Vk.DisplayMode) { case VK_DISPLAY_MODE_SDR: for (uint32_t i = 0; i < surface_format_count; ++i) { if ((surface_formats[i].format == VK_FORMAT_R8G8B8A8_UNORM || surface_formats[i].format == VK_FORMAT_B8G8R8A8_UNORM) && surface_formats[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { Vk.SwapchainSurfaceFormat = surface_formats[i]; surface_format_supported = true; break; } } break; case VK_DISPLAY_MODE_HDR10: for (uint32_t i = 0; i < surface_format_count; ++i) { if ((surface_formats[i].format == VK_FORMAT_A2R10G10B10_UNORM_PACK32 || surface_formats[i].format == VK_FORMAT_A2B10G10R10_UNORM_PACK32) && surface_formats[i].colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT) { Vk.SwapchainSurfaceFormat = surface_formats[i]; surface_format_supported = true; break; } } break; case VK_DISPLAY_MODE_SCRGB: for (uint32_t i = 0; i < surface_format_count; ++i) { if ((surface_formats[i].format == VK_FORMAT_R16G16B16A16_SFLOAT) && surface_formats[i].colorSpace == VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT) { Vk.SwapchainSurfaceFormat = surface_formats[i]; surface_format_supported = true; break; } } break; } if (!surface_format_supported) { VkError("Surface format is not supported"); } uint32_t present_mode_count = 0; VK(vkGetPhysicalDeviceSurfacePresentModesKHR(Vk.PhysicalDevice, Vk.Surface, &present_mode_count, NULL)); std::vector<VkPresentModeKHR> present_modes(present_mode_count); VK(vkGetPhysicalDeviceSurfacePresentModesKHR(Vk.PhysicalDevice, Vk.Surface, &present_mode_count, present_modes.data())); VkSwapchainCreateInfoKHR swapchain_info = {}; swapchain_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swapchain_info.surface = Vk.Surface; swapchain_info.minImageCount = Vk.SwapchainImageCount; swapchain_info.imageFormat = Vk.SwapchainSurfaceFormat.format; swapchain_info.imageColorSpace = Vk.SwapchainSurfaceFormat.colorSpace; swapchain_info.imageExtent = Vk.SwapchainImageExtent; swapchain_info.imageArrayLayers = 1; swapchain_info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; swapchain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swapchain_info.preTransform = surface_capabilities.currentTransform; swapchain_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swapchain_info.presentMode = VK_PRESENT_MODE_FIFO_KHR; swapchain_info.clipped = VK_TRUE; swapchain_info.oldSwapchain = Vk.Swapchain; VK(vkCreateSwapchainKHR(Vk.Device, &swapchain_info, NULL, &Vk.Swapchain)); if (swapchain_info.oldSwapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(Vk.Device, swapchain_info.oldSwapchain, NULL); } if (Vk.DisplayMode == VK_DISPLAY_MODE_HDR10 || Vk.DisplayMode == VK_DISPLAY_MODE_SCRGB) { VkHdrMetadataEXT hdr_metadata = {}; hdr_metadata.sType = VK_STRUCTURE_TYPE_HDR_METADATA_EXT; hdr_metadata.displayPrimaryRed = VkXYColorEXT{ 0.708f, 0.292f }; hdr_metadata.displayPrimaryGreen = VkXYColorEXT{ 0.170f, 0.797f }; hdr_metadata.displayPrimaryBlue = VkXYColorEXT{ 0.131f, 0.046f }; hdr_metadata.whitePoint = VkXYColorEXT{ 0.3127f, 0.3290f }; hdr_metadata.maxLuminance = 1000.0f; hdr_metadata.minLuminance = 0.0f; hdr_metadata.maxContentLightLevel = 1000.0f; hdr_metadata.maxFrameAverageLightLevel = 400.0f; vkSetHdrMetadataEXT(Vk.Device, 1, &Vk.Swapchain, &hdr_metadata); } VK(vkGetSwapchainImagesKHR(Vk.Device, Vk.Swapchain, &Vk.SwapchainImageCount, NULL)); std::vector<VkImage> swapchain_images(Vk.SwapchainImageCount); VK(vkGetSwapchainImagesKHR(Vk.Device, Vk.Swapchain, &Vk.SwapchainImageCount, swapchain_images.data())); Vk.SwapchainImageIndex = 0; Vk.SwapchainImages.resize(Vk.SwapchainImageCount); Vk.SwapchainImageViews.resize(Vk.SwapchainImageCount); for (uint32_t i = 0; i < Vk.SwapchainImageCount; ++i) { Vk.SwapchainImages[i] = swapchain_images[i]; VkImageViewCreateInfo image_view_info = {}; image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; image_view_info.image = Vk.SwapchainImages[i]; image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; image_view_info.format = Vk.SwapchainSurfaceFormat.format; image_view_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; image_view_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; image_view_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; image_view_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; image_view_info.subresourceRange.baseMipLevel = 0; image_view_info.subresourceRange.levelCount = 1; image_view_info.subresourceRange.baseArrayLayer = 0; image_view_info.subresourceRange.layerCount = 1; VK(vkCreateImageView(Vk.Device, &image_view_info, NULL, &Vk.SwapchainImageViews[i])); VkRecordCommands( [=](VkCommandBuffer cmd) { VkImageMemoryBarrier barrier; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.pNext = NULL; barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = Vk.SwapchainImages[i]; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, NULL, 0, NULL, 1, &barrier); }); } Vk.CommandBuffers.resize(Vk.SwapchainImageCount); Vk.CommandBufferFences.resize(Vk.SwapchainImageCount); Vk.CommandBufferSemaphores.resize(Vk.SwapchainImageCount); Vk.PresentSemaphores.resize(Vk.SwapchainImageCount); Vk.DescriptorPools.resize(Vk.SwapchainImageCount); Vk.UploadBufferTails.resize(Vk.SwapchainImageCount); for (uint32_t i = 0; i < Vk.SwapchainImageCount; ++i) { VkCommandBufferAllocateInfo command_buffer_info = {}; command_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; command_buffer_info.commandPool = Vk.CommandPool; command_buffer_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; command_buffer_info.commandBufferCount = 1; VK(vkAllocateCommandBuffers(Vk.Device, &command_buffer_info, &Vk.CommandBuffers[i])); VkFenceCreateInfo fence_info = {}; fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; VK(vkCreateFence(Vk.Device, &fence_info, NULL, &Vk.CommandBufferFences[i])); VkSemaphoreCreateInfo semaphore_info = {}; semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VK(vkCreateSemaphore(Vk.Device, &semaphore_info, NULL, &Vk.CommandBufferSemaphores[i])); VK(vkCreateSemaphore(Vk.Device, &semaphore_info, NULL, &Vk.PresentSemaphores[i])); std::vector<VkDescriptorPoolSize> descriptor_pool_sizes = { { VK_DESCRIPTOR_TYPE_SAMPLER, 65535 }, { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 65535 }, { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 65535 }, { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 65535 }, { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 65535 }, { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 65535 }, { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 65535 }, { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 65535 }, { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 65535 }, { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 65535 }, }; if (Vk.IsRayTracingSupported) { descriptor_pool_sizes.push_back({ VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 65535 }); } VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.poolSizeCount = static_cast<uint32_t>(descriptor_pool_sizes.size()); pool_info.pPoolSizes = descriptor_pool_sizes.data(); pool_info.maxSets = 65535; VK(vkCreateDescriptorPool(Vk.Device, &pool_info, NULL, &Vk.DescriptorPools[i])); Vk.UploadBufferTails[i] = 0; } Vk.UploadBufferHead = 0; Vk.FrameIndexCurr = 0; Vk.FrameIndexNext = (Vk.FrameIndexCurr + 1) % Vk.SwapchainImageCount; } static void DestroySwapchain() { for (uint32_t i = 0; i < Vk.SwapchainImageCount; ++i) { vkDestroyDescriptorPool(Vk.Device, Vk.DescriptorPools[i], NULL); vkDestroySemaphore(Vk.Device, Vk.PresentSemaphores[i], NULL); vkDestroySemaphore(Vk.Device, Vk.CommandBufferSemaphores[i], NULL); vkDestroyFence(Vk.Device, Vk.CommandBufferFences[i], NULL); vkFreeCommandBuffers(Vk.Device, Vk.CommandPool, 1, &Vk.CommandBuffers[i]); vkDestroyImageView(Vk.Device, Vk.SwapchainImageViews[i], NULL); } } void VkInitialize(const VkInitializeParams& params) { VK(volkInitialize()); std::vector<const char*> instance_extensions = { VK_KHR_SURFACE_EXTENSION_NAME, #if defined(VK_USE_PLATFORM_WIN32_KHR) VK_KHR_WIN32_SURFACE_EXTENSION_NAME, #elif defined(VK_USE_PLATFORM_XLIB_KHR) VK_KHR_XLIB_SURFACE_EXTENSION_NAME, #endif VK_EXT_DEBUG_REPORT_EXTENSION_NAME, }; std::vector<const char*> device_extensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; const char* validation_layer = "VK_LAYER_KHRONOS_validation"; uint32_t instance_extension_properties_count = 0; VK(vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_properties_count, NULL)); std::vector<VkExtensionProperties> instance_extension_properties(instance_extension_properties_count); VK(vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_properties_count, instance_extension_properties.data())); for (uint32_t i = 0; i < static_cast<uint32_t>(instance_extensions.size()); ++i) { bool extension_supported = false; for (uint32_t j = 0; j < instance_extension_properties_count; ++j) { if (strcmp(instance_extensions[i], instance_extension_properties[j].extensionName) == 0) { extension_supported = true; break; } } if (!extension_supported) { VkError("All instance extensions are not supported"); } } if (params.EnableValidationLayer) { uint32_t instance_layer_properties_count = 0; VK(vkEnumerateInstanceLayerProperties(&instance_layer_properties_count, NULL)); std::vector<VkLayerProperties> instance_layer_properties(instance_layer_properties_count); VK(vkEnumerateInstanceLayerProperties(&instance_layer_properties_count, instance_layer_properties.data())); bool validation_layer_supported = false; for (uint32_t i = 0; i < instance_layer_properties_count; ++i) { if (strcmp(validation_layer, instance_layer_properties[i].layerName) == 0) { validation_layer_supported = true; break; } } if (!validation_layer_supported) { VkError("Validation layer is not supported"); } } VkApplicationInfo app_info = {}; app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; app_info.apiVersion = VK_API_VERSION_1_2; VkInstanceCreateInfo instance_info = {}; instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instance_info.pApplicationInfo = &app_info; instance_info.enabledExtensionCount = static_cast<uint32_t>(instance_extensions.size()); instance_info.ppEnabledExtensionNames = instance_extensions.data(); if (params.EnableValidationLayer) { instance_info.enabledLayerCount = 1; instance_info.ppEnabledLayerNames = &validation_layer; } VK(vkCreateInstance(&instance_info, NULL, &Vk.Instance)); volkLoadInstance(Vk.Instance); Vk.DebugCallback = VK_NULL_HANDLE; if (params.EnableValidationLayer) { VkDebugReportCallbackCreateInfoEXT callback_info = {}; callback_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; callback_info.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; callback_info.pfnCallback = DebugCallback; VK(vkCreateDebugReportCallbackEXT(Vk.Instance, &callback_info, NULL, &Vk.DebugCallback)); } #if defined(VK_USE_PLATFORM_WIN32_KHR) VkWin32SurfaceCreateInfoKHR surface_info = {}; surface_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; surface_info.hwnd = static_cast<HWND>(params.WindowHandle); surface_info.hinstance = static_cast<HINSTANCE>(params.DisplayHandle); VK(vkCreateWin32SurfaceKHR(Vk.Instance, &surface_info, NULL, &Vk.Surface)); #elif defined(VK_USE_PLATFORM_XLIB_KHR) VkXlibSurfaceCreateInfoKHR surface_info = {}; surface_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; surface_info.window = reinterpret_cast<Window>(params.WindowHandle); surface_info.dpy = static_cast<Display*>(params.DisplayHandle); VK(vkCreateXlibSurfaceKHR(Vk.Instance, &surface_info, NULL, &Vk.Surface)); #endif uint32_t physical_device_count = 0; VK(vkEnumeratePhysicalDevices(Vk.Instance, &physical_device_count, NULL)); std::vector<VkPhysicalDevice> physical_devices(physical_device_count); VK(vkEnumeratePhysicalDevices(Vk.Instance, &physical_device_count, physical_devices.data())); Vk.PhysicalDevice = VK_NULL_HANDLE; Vk.GraphicsQueueIndex = ~0U; for (size_t i = 0; i < physical_devices.size(); ++i) { uint32_t device_extension_properties_count = 0; VK(vkEnumerateDeviceExtensionProperties(physical_devices[i], NULL, &device_extension_properties_count, NULL)); std::vector<VkExtensionProperties> device_extension_properties(device_extension_properties_count); VK(vkEnumerateDeviceExtensionProperties(physical_devices[i], NULL, &device_extension_properties_count, device_extension_properties.data())); bool all_extensions_supported = true; for (uint32_t j = 0; j < static_cast<uint32_t>(device_extensions.size()); ++j) { bool extension_supported = false; for (uint32_t k = 0; k < device_extension_properties_count; ++k) { if (strcmp(device_extensions[j], device_extension_properties[k].extensionName) == 0) { extension_supported = true; break; } } if (!extension_supported) { all_extensions_supported = false; break; } } if (!all_extensions_supported) continue; if (params.EnableValidationLayer) { uint32_t device_layer_properties_count = 0; VK(vkEnumerateDeviceLayerProperties(physical_devices[i], &device_layer_properties_count, NULL)); std::vector<VkLayerProperties> device_layer_properties(device_layer_properties_count); VK(vkEnumerateDeviceLayerProperties(physical_devices[i], &device_layer_properties_count, device_layer_properties.data())); bool validation_layer_supported = false; for (uint32_t j = 0; j < device_layer_properties_count; ++j) { if (strcmp(validation_layer, device_layer_properties[j].layerName) == 0) { validation_layer_supported = true; break; } } if (!validation_layer_supported) continue; } uint32_t queue_family_properties_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, NULL); std::vector<VkQueueFamilyProperties> queue_family_properties(queue_family_properties_count); vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, queue_family_properties.data()); for (uint32_t j = 0; j < queue_family_properties_count; ++j) { VkBool32 queue_flags_supported = (queue_family_properties[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0; VkBool32 surface_supported = VK_FALSE; VK(vkGetPhysicalDeviceSurfaceSupportKHR(physical_devices[i], j, Vk.Surface, &surface_supported)); if (queue_flags_supported && surface_supported) { Vk.GraphicsQueueIndex = j; break; } } if (Vk.GraphicsQueueIndex == ~0U) continue; VkPhysicalDeviceProperties device_properties; vkGetPhysicalDeviceProperties(physical_devices[i], &device_properties); if (VK_VERSION_MAJOR(device_properties.apiVersion) < 1 || (VK_VERSION_MAJOR(device_properties.apiVersion) == 1 && VK_VERSION_MINOR(device_properties.apiVersion) < 2)) continue; Vk.PhysicalDevice = physical_devices[i]; break; } if (Vk.PhysicalDevice == VK_NULL_HANDLE) { VkError("Error: No compatible physical device was found"); } vkGetPhysicalDeviceProperties(Vk.PhysicalDevice, &Vk.PhysicalDeviceProperties); uint32_t device_extension_properties_count = 0; VK(vkEnumerateDeviceExtensionProperties(Vk.PhysicalDevice, NULL, &device_extension_properties_count, NULL)); std::vector<VkExtensionProperties> device_extension_properties(device_extension_properties_count); VK(vkEnumerateDeviceExtensionProperties(Vk.PhysicalDevice, NULL, &device_extension_properties_count, device_extension_properties.data())); // Check if HDR display modes are supported { std::vector<const char*> hdr_display_extensions = { VK_EXT_HDR_METADATA_EXTENSION_NAME, }; bool is_hdr_display_supported = true; for (size_t i = 0; i < hdr_display_extensions.size(); ++i) { bool is_extension_supported = false; for (uint32_t j = 0; j < device_extension_properties_count; ++j) { if (strcmp(device_extension_properties[j].extensionName, hdr_display_extensions[i]) == 0) { is_extension_supported = true; break; } } if (!is_extension_supported) { is_hdr_display_supported = false; break; } } if (is_hdr_display_supported) { for (size_t i = 0; i < hdr_display_extensions.size(); ++i) { device_extensions.push_back(hdr_display_extensions[i]); } } uint32_t surface_format_count = 0; VK(vkGetPhysicalDeviceSurfaceFormatsKHR(Vk.PhysicalDevice, Vk.Surface, &surface_format_count, NULL)); std::vector<VkSurfaceFormatKHR> surface_formats(surface_format_count); VK(vkGetPhysicalDeviceSurfaceFormatsKHR(Vk.PhysicalDevice, Vk.Surface, &surface_format_count, surface_formats.data())); memset(Vk.IsDisplayModeSupported, 0, sizeof(Vk.IsDisplayModeSupported)); for (uint32_t i = 0; i < surface_format_count; ++i) { Vk.IsDisplayModeSupported[VK_DISPLAY_MODE_SDR] |= ((surface_formats[i].format == VK_FORMAT_R8G8B8A8_UNORM || surface_formats[i].format == VK_FORMAT_B8G8R8A8_UNORM) && surface_formats[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR); if (is_hdr_display_supported) { Vk.IsDisplayModeSupported[VK_DISPLAY_MODE_HDR10] |= ((surface_formats[i].format == VK_FORMAT_A2R10G10B10_UNORM_PACK32 || surface_formats[i].format == VK_FORMAT_A2B10G10R10_UNORM_PACK32) && surface_formats[i].colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT); Vk.IsDisplayModeSupported[VK_DISPLAY_MODE_SCRGB] |= ((surface_formats[i].format == VK_FORMAT_R16G16B16A16_SFLOAT) && surface_formats[i].colorSpace == VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT); } } } // Check if ray tracing is supported { Vk.IsRayTracingSupported = true; std::vector<const char*> ray_tracing_extensions = { VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME, VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME, VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME, VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME, VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, }; for (size_t i = 0; i < ray_tracing_extensions.size(); ++i) { bool is_extension_supported = false; for (uint32_t j = 0; j < device_extension_properties_count; ++j) { if (strcmp(device_extension_properties[j].extensionName, ray_tracing_extensions[i]) == 0) { is_extension_supported = true; break; } } if (!is_extension_supported) { Vk.IsRayTracingSupported = false; break; } } if (Vk.IsRayTracingSupported) { for (size_t i = 0; i < ray_tracing_extensions.size(); ++i) { device_extensions.push_back(ray_tracing_extensions[i]); } } } const float queue_priority = 1.0f; VkDeviceQueueCreateInfo queue_info = {}; queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queue_info.queueFamilyIndex = Vk.GraphicsQueueIndex; queue_info.queueCount = 1; queue_info.pQueuePriorities = &queue_priority; VkPhysicalDeviceFeatures device_features = {}; device_features.samplerAnisotropy = VK_TRUE; device_features.shaderStorageImageExtendedFormats = VK_TRUE; VkPhysicalDeviceVulkan12Features device_vulkan_1_2_features = {}; device_vulkan_1_2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; device_vulkan_1_2_features.bufferDeviceAddress = VK_TRUE; device_vulkan_1_2_features.runtimeDescriptorArray = VK_TRUE; device_vulkan_1_2_features.descriptorIndexing = VK_TRUE; device_vulkan_1_2_features.descriptorBindingPartiallyBound = VK_TRUE; VkPhysicalDeviceAccelerationStructureFeaturesKHR device_acceleration_structure_features = {}; device_acceleration_structure_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR; device_acceleration_structure_features.pNext = &device_vulkan_1_2_features; device_acceleration_structure_features.accelerationStructure = VK_TRUE; VkPhysicalDeviceRayTracingPipelineFeaturesKHR device_ray_tracing_pipeline_features = {}; device_ray_tracing_pipeline_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR; device_ray_tracing_pipeline_features.pNext = &device_acceleration_structure_features; device_ray_tracing_pipeline_features.rayTracingPipeline = VK_TRUE; VkDeviceCreateInfo device_info = {}; device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; device_info.pNext = Vk.IsRayTracingSupported ? &device_ray_tracing_pipeline_features : NULL; device_info.queueCreateInfoCount = 1; device_info.pQueueCreateInfos = &queue_info; device_info.enabledExtensionCount = static_cast<uint32_t>(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.data(); device_info.pEnabledFeatures = &device_features; if (params.EnableValidationLayer) { device_info.enabledLayerCount = 1; device_info.ppEnabledLayerNames = &validation_layer; } VK(vkCreateDevice(Vk.PhysicalDevice, &device_info, NULL, &Vk.Device)); volkLoadDevice(Vk.Device); vkGetDeviceQueue(Vk.Device, Vk.GraphicsQueueIndex, 0, &Vk.GraphicsQueue); VkCommandPoolCreateInfo command_pool_info = {}; command_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; command_pool_info.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; command_pool_info.queueFamilyIndex = Vk.GraphicsQueueIndex; VK(vkCreateCommandPool(Vk.Device, &command_pool_info, NULL, &Vk.CommandPool)); VmaAllocatorCreateInfo allocator_info = {}; allocator_info.flags = VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT | (Vk.IsRayTracingSupported ? VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT : 0); allocator_info.physicalDevice = Vk.PhysicalDevice; allocator_info.device = Vk.Device; allocator_info.instance = Vk.Instance; allocator_info.pAllocationCallbacks = NULL; VK(vmaCreateAllocator(&allocator_info, &Vk.Allocator)); VkBufferCreateInfo upload_buffer_info = {}; upload_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; upload_buffer_info.size = UPLOAD_BUFFER_SIZE; upload_buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; upload_buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VmaAllocationCreateInfo upload_buffer_allocation_info = {}; upload_buffer_allocation_info.usage = VMA_MEMORY_USAGE_CPU_ONLY; upload_buffer_allocation_info.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; VmaAllocationInfo allocation_info = {}; VK(vmaCreateBuffer(Vk.Allocator, &upload_buffer_info, &upload_buffer_allocation_info, &Vk.UploadBuffer, &Vk.UploadBufferAllocation, &allocation_info)); Vk.UploadBufferMemory = allocation_info.deviceMemory; Vk.UploadBufferMemoryOffset = allocation_info.offset; Vk.UploadBufferMappedData = (uint8_t*)allocation_info.pMappedData; Vk.Swapchain = VK_NULL_HANDLE; CreateSwapchain(params.BackBufferWidth, params.BackBufferHeight, params.DesiredBackBufferCount, params.DisplayMode); VkQueryPoolCreateInfo timestamp_query_pool_info = {}; timestamp_query_pool_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; timestamp_query_pool_info.queryType = VK_QUERY_TYPE_TIMESTAMP; timestamp_query_pool_info.queryCount = TIMESTAMP_QUERY_POOL_SIZE; VK(vkCreateQueryPool(Vk.Device, &timestamp_query_pool_info, NULL, &Vk.TimestampQueryPool)); Vk.TimestampQueryPoolOffset = 0; } void VkTerminate() { DestroySwapchain(); vkDestroySwapchainKHR(Vk.Device, Vk.Swapchain, NULL); vkDestroyQueryPool(Vk.Device, Vk.TimestampQueryPool, NULL); vmaDestroyBuffer(Vk.Allocator, Vk.UploadBuffer, Vk.UploadBufferAllocation); vmaDestroyAllocator(Vk.Allocator); vkDestroyCommandPool(Vk.Device, Vk.CommandPool, NULL); vkDestroyDevice(Vk.Device, NULL); vkDestroySurfaceKHR(Vk.Instance, Vk.Surface, NULL); if (Vk.DebugCallback != VK_NULL_HANDLE) { vkDestroyDebugReportCallbackEXT(Vk.Instance, Vk.DebugCallback, NULL); } vkDestroyInstance(Vk.Instance, NULL); } void VkResize(uint32_t width, uint32_t height, VkDisplayMode display_mode) { DestroySwapchain(); CreateSwapchain(width, height, Vk.SwapchainImageCount, display_mode); } VkAllocation VkAllocateUploadBuffer(VkDeviceSize size, VkDeviceSize alignment) { VkDeviceSize head = Vk.UploadBufferHead; VkDeviceSize tail = Vk.UploadBufferTails[Vk.FrameIndexNext]; VkDeviceSize offset = (head + alignment - 1) & ~(alignment - 1); if (offset + size > UPLOAD_BUFFER_SIZE) { offset = 0; } if (offset + size > UPLOAD_BUFFER_SIZE || ((head - tail) & UPLOAD_BUFFER_MASK) > ((offset + size - tail) & UPLOAD_BUFFER_MASK)) { VkError("Upload buffer is out of memory"); } Vk.UploadBufferHead = offset + size; VkAllocation allocation; allocation.Buffer = Vk.UploadBuffer; allocation.Offset = offset; allocation.Data = Vk.UploadBufferMappedData + offset; return allocation; } void VkRecordCommands(const std::function<void(VkCommandBuffer)>& commands) { Vk.RecordedCommands.emplace_back(commands); } VkCommandBuffer VkBeginFrame() { VK(vkAcquireNextImageKHR(Vk.Device, Vk.Swapchain, UINT64_MAX, Vk.PresentSemaphores[Vk.FrameIndexCurr], VK_NULL_HANDLE, &Vk.SwapchainImageIndex)); VK(vkWaitForFences(Vk.Device, 1, &Vk.CommandBufferFences[Vk.FrameIndexCurr], VK_TRUE, UINT64_MAX)); VK(vkResetFences(Vk.Device, 1, &Vk.CommandBufferFences[Vk.FrameIndexCurr])); VK(vkResetDescriptorPool(Vk.Device, Vk.DescriptorPools[Vk.FrameIndexCurr], 0)); VkCommandBuffer cmd = Vk.CommandBuffers[Vk.FrameIndexCurr]; VkCommandBufferBeginInfo cmd_begin_info = {}; cmd_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmd_begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; VK(vkBeginCommandBuffer(cmd, &cmd_begin_info)); for (const std::function<void(VkCommandBuffer)>& commands : Vk.RecordedCommands) { commands(cmd); } Vk.RecordedCommands.clear(); while (!Vk.TimestampLabelsInFlight.empty()) { const std::pair<std::string, uint32_t>& label = Vk.TimestampLabelsInFlight.front(); uint64_t timestamps[2]; VkResult result = vkGetQueryPoolResults(Vk.Device, Vk.TimestampQueryPool, label.second, 2, sizeof(uint64_t) * 2, timestamps, sizeof(uint64_t), VK_QUERY_RESULT_64_BIT); assert(result == VK_SUCCESS || result == VK_NOT_READY); if (result == VK_NOT_READY) { break; } const double timestamp_period = static_cast<double>(Vk.PhysicalDeviceProperties.limits.timestampPeriod) * 1e-6; float duration = static_cast<float>(static_cast<double>(timestamps[1] - timestamps[0]) * timestamp_period); if (Vk.TimestampLabelsResult.find(label.first) == Vk.TimestampLabelsResult.end()) { Vk.TimestampLabelsResult[label.first] = 0.0f; } Vk.TimestampLabelsResult[label.first] += (duration - Vk.TimestampLabelsResult[label.first]) * 0.25f; Vk.TimestampLabelsInFlight.erase(Vk.TimestampLabelsInFlight.begin()); } VkImageMemoryBarrier barrier; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.pNext = NULL; barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; barrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = Vk.SwapchainImages[Vk.SwapchainImageIndex]; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, NULL, 0, NULL, 1, &barrier); return cmd; } void VkEndFrame() { VkCommandBuffer cmd = Vk.CommandBuffers[Vk.FrameIndexCurr]; VkImageMemoryBarrier barrier; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.pNext = NULL; barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = Vk.SwapchainImages[Vk.SwapchainImageIndex]; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, NULL, 0, NULL, 1, &barrier); VK(vkEndCommandBuffer(cmd)); Vk.UploadBufferTails[Vk.FrameIndexCurr] = Vk.UploadBufferHead; assert(Vk.TimestampLabelsPushed.empty()); VkPipelineStageFlags wait_stage_flags = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; VkSubmitInfo submit_info = {}; submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info.waitSemaphoreCount = 1; submit_info.pWaitSemaphores = &Vk.PresentSemaphores[Vk.FrameIndexCurr]; submit_info.pWaitDstStageMask = &wait_stage_flags; submit_info.signalSemaphoreCount = 1; submit_info.pSignalSemaphores = &Vk.CommandBufferSemaphores[Vk.FrameIndexCurr]; submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &Vk.CommandBuffers[Vk.FrameIndexCurr]; VK(vkQueueSubmit(Vk.GraphicsQueue, 1, &submit_info, Vk.CommandBufferFences[Vk.FrameIndexCurr])); VkPresentInfoKHR present_info = {}; present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present_info.waitSemaphoreCount = 1; present_info.pWaitSemaphores = &Vk.CommandBufferSemaphores[Vk.FrameIndexCurr]; present_info.swapchainCount = 1; present_info.pSwapchains = &Vk.Swapchain; present_info.pImageIndices = &Vk.SwapchainImageIndex; VK(vkQueuePresentKHR(Vk.GraphicsQueue, &present_info)); Vk.FrameIndexCurr = Vk.FrameIndexNext; Vk.FrameIndexNext = (Vk.FrameIndexCurr + 1) % Vk.SwapchainImageCount; } VkDescriptorSet VkCreateDescriptorSetForCurrentFrame(VkDescriptorSetLayout layout, std::initializer_list<VkDescriptorSetEntry> entries) { VkDescriptorSetAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; alloc_info.descriptorPool = Vk.DescriptorPools[Vk.FrameIndexCurr]; alloc_info.descriptorSetCount = 1; alloc_info.pSetLayouts = &layout; VkDescriptorSet descriptor_set = VK_NULL_HANDLE; VK(vkAllocateDescriptorSets(Vk.Device, &alloc_info, &descriptor_set)); std::vector<VkWriteDescriptorSet> write_info(entries.size()); for (size_t i = 0; i < entries.size(); ++i) { const VkDescriptorSetEntry& entry = *(entries.begin() + i); write_info[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write_info[i].dstSet = descriptor_set; write_info[i].dstBinding = entry.Binding; write_info[i].dstArrayElement = entry.ArrayIndex; write_info[i].descriptorCount = entry.ArrayCount; write_info[i].descriptorType = entry.Type; switch (entry.Type) { case VK_DESCRIPTOR_TYPE_SAMPLER: case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: write_info[i].pImageInfo = entry.ArrayCount > 1 ? entry.ImageInfos : &entry.ImageInfo; break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: write_info[i].pBufferInfo = entry.ArrayCount > 1 ? entry.BufferInfos : &entry.BufferInfo; break; case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: write_info[i].pTexelBufferView = entry.ArrayCount > 1 ? entry.TexelBufferInfos : &entry.TexelBufferInfo; break; case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: write_info[i].pNext = entry.ArrayCount > 1 ? entry.AccelerationStructureInfos : &entry.AccelerationStructureInfo; break; } } vkUpdateDescriptorSets(Vk.Device, static_cast<uint32_t>(write_info.size()), write_info.data(), 0, nullptr); return descriptor_set; } VkDescriptorSetEntry::VkDescriptorSetEntry(uint32_t binding, VkDescriptorType type, uint32_t array_index, VkImageView image_view, VkImageLayout image_layout, VkSampler sampler) { Binding = binding; Type = type; ArrayIndex = array_index; ArrayCount = 1; ImageInfo.sampler = sampler; ImageInfo.imageView = image_view; ImageInfo.imageLayout = image_layout; } VkDescriptorSetEntry::VkDescriptorSetEntry(uint32_t binding, VkDescriptorType type, uint32_t array_index, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size) { Binding = binding; Type = type; ArrayIndex = array_index; ArrayCount = 1; BufferInfo.buffer = buffer; BufferInfo.offset = offset; BufferInfo.range = size; } VkDescriptorSetEntry::VkDescriptorSetEntry(uint32_t binding, VkDescriptorType type, uint32_t array_index, VkAccelerationStructureKHR acceleration_structure) { Binding = binding; Type = type; ArrayIndex = array_index; ArrayCount = 1; AccelerationStructureInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR; AccelerationStructureInfo.pNext = NULL; AccelerationStructureInfo.accelerationStructureCount = 1; AccelerationStructureInfo.pAccelerationStructures = &acceleration_structure; } VkDescriptorSetEntry::VkDescriptorSetEntry(uint32_t binding, VkDescriptorType type, uint32_t array_index, uint32_t array_count, const VkDescriptorImageInfo* infos) { assert(array_count > 0); Binding = binding; Type = type; ArrayIndex = array_index; ArrayCount = array_count; if (array_count == 1) { ImageInfo = infos[0]; } else { ImageInfos = infos; } } VkDescriptorSetEntry::VkDescriptorSetEntry(uint32_t binding, VkDescriptorType type, uint32_t array_index, uint32_t array_count, const VkDescriptorBufferInfo* infos) { assert(array_count > 0); Binding = binding; Type = type; ArrayIndex = array_index; ArrayCount = array_count; if (array_count == 1) { BufferInfo = infos[0]; } else { BufferInfos = infos; } } void VkPushLabel(VkCommandBuffer cmd, const std::string& label) { const uint32_t query = Vk.TimestampQueryPoolOffset; Vk.TimestampQueryPoolOffset += 2; if (Vk.TimestampQueryPoolOffset >= TIMESTAMP_QUERY_POOL_SIZE) Vk.TimestampQueryPoolOffset = 0; Vk.TimestampLabelsPushed.push_back({ label, query }); vkCmdResetQueryPool(cmd, Vk.TimestampQueryPool, query, 2); vkCmdWriteTimestamp(cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, Vk.TimestampQueryPool, query); } void VkPopLabel(VkCommandBuffer cmd) { assert(!Vk.TimestampLabelsPushed.empty()); const std::pair<std::string, uint32_t>& label = Vk.TimestampLabelsPushed.back(); Vk.TimestampLabelsInFlight.emplace_back(label); Vk.TimestampLabelsPushed.pop_back(); vkCmdWriteTimestamp(cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, Vk.TimestampQueryPool, label.second + 1); } float VkGetLabel(const std::string& label) { auto label_itr = Vk.TimestampLabelsResult.find(label); if (label_itr != Vk.TimestampLabelsResult.end()) return label_itr->second; return 0.0f; }
42.87114
259
0.759166
[ "vector" ]
ab9fd5feb93a93b9fa38c6921f53776b53f80282
49,736
hpp
C++
include/NP-Engine/Noise/Simplex.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
include/NP-Engine/Noise/Simplex.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
include/NP-Engine/Noise/Simplex.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
#ifndef NP_ENGINE_SIMPLEX_HPP #define NP_ENGINE_SIMPLEX_HPP #include "NP-Engine/Primitive/Primitive.hpp" #include "NP-Engine/Random/Random.hpp" #include "NP-Engine/Math/Math.hpp" #include "NP-Engine/JSON/JSON.hpp" #include "NP-Engine/String/String.hpp" namespace np { namespace noise { /** provides simplex noise 1D, 2D, 3D, 4D provides fractal, fractional, rigid, billow, and warp methods */ class Simplex : public random::Random32Base { public: constexpr static flt DEFAULT_FREQUENCY = 1.f; constexpr static flt DEFAULT_AMPLITUDE = 1.f; constexpr static flt DEFAULT_LACUNARITY = 2.f; constexpr static flt DEFAULT_PERSISTENCE = 0.5f; constexpr static flt DEFAULT_FRACTIONAL_INCREMENT = 0.19f; constexpr static flt DEFAULT_OCTAVE_COUNT = 3; constexpr static ui8 DEFAULT_RIGIDITY = 1; constexpr static ui8 DEFAULT_WARP_OCTAVE_COUNT = 1; constexpr static flt DEFAULT_WARP_OCTAVE_MULTIPLIER = 1.f; constexpr static flt DEFAULT_WARP_OCTAVE_INCREMENT = 0.19f; constexpr static flt DEFAULT_WARP_OCTAVE_DISPLACEMENT = 0.f; private: constexpr static chr AsFilename[] = "simplex.json"; static const ui32 PERMUTATION_SIZE = 256; ui8 _permutation[PERMUTATION_SIZE]; constexpr static flt GRADIENT4D[128] = { 0.f, 1.f, 1.f, 1.f, 0.f, 1.f, 1.f, -1.f, 0.f, 1.f, -1.f, 1.f, 0.f, 1.f, -1.f, -1.f, 0.f, -1.f, 1.f, 1.f, 0.f, -1.f, 1.f, -1.f, 0.f, -1.f, -1.f, 1.f, 0.f, -1.f, -1.f, -1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 0.f, 1.f, -1.f, 1.f, 0.f, -1.f, 1.f, 1.f, 0.f, -1.f, -1.f, -1.f, 0.f, 1.f, 1.f, -1.f, 0.f, 1.f, -1.f, -1.f, 0.f, -1.f, 1.f, -1.f, 0.f, -1.f, -1.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 0.f, -1.f, 1.f, -1.f, 0.f, 1.f, 1.f, -1.f, 0.f, -1.f, -1.f, 1.f, 0.f, 1.f, -1.f, 1.f, 0.f, -1.f, -1.f, -1.f, 0.f, 1.f, -1.f, -1.f, 0.f, -1.f, 1.f, 1.f, 1.f, 0.f, 1.f, 1.f, -1.f, 0.f, 1.f, -1.f, 1.f, 0.f, 1.f, -1.f, -1.f, 0.f, -1.f, 1.f, 1.f, 0.f, -1.f, 1.f, -1.f, 0.f, -1.f, -1.f, 1.f, 0.f, -1.f, -1.f, -1.f, 0.f}; ui8 _warp_octave_count; /// recommend [1, 2] - 0 gives you fbm - > 3 is not very usable due to performance but /// produces cool results - default to 1 for performance reasons flt _warp_octave_multiplier; /// similar to frequency, as this adds more and more "folds" to the warped shape - /// default to 1 flt _warp_octave_increment; /// recommend [0, 1] => [smooth, clumpy] but can be whatever - this is a very small /// detail - 0.19 was chosen as default flt _warp_octave_displacement; /// recommend [0] for performance reasons - can be any value - only change if 0 is /// giving you too "regular" warping flt _frequency; ///< Frequency ("width") of the first octave of noise (default to 1.0) flt _amplitude; ///< Amplitude ("height") of the first octave of noise (default to 1.0) flt _lacunarity; ///< Lacunarity specifies the frequency multiplier between successive octaves (default to 2.0). flt _persistence; ///< Persistence is the loss of amplitude between successive octaves (usually 1/lacunarity) flt _fractional_increment; /// how much the fractional method increments to prevent fractal artifacts (default to /// 0.19) ui8 _octave_count; /// recommends [3, 6] for good control of detail - inputs [6, +oo) can be way much detail and /// perform slow - inputs [0, 3] may be too little detail - default to 3 for performance reasons ui8 _rigidity; /// higher rigidity means a more stark noise (default to 1) //--------------------------------------------------------------------------- /** hash function for given i32 */ inline ui8 Hash(i32 i) const { return _permutation[static_cast<ui8>(i)]; } /** gradient method for 1D noise */ inline static flt Grad(i32 hash, flt x) { i32 h = hash & 0x0F; // Convert low 4 bits of hash code flt grad = 1.0f + (h & 7); // Gradient value 1.0, 2.0, ..., 8.0 if ((h & 8) != 0) grad = -grad; // Set a random sign for the gradient return (grad * x); // Multiply the gradient with the distance } /** gradient method for 2D noise */ inline static flt Grad(i32 hash, flt x, flt y) { i32 h = hash & 0x3F; // Convert low 3 bits of hash code flt u = h < 4 ? x : y; // into 8 simple gradient directions, flt v = h < 4 ? y : x; return ((h & 1) ? -u : u) + ((h & 2) ? -2.0f * v : 2.0f * v); // and compute the dot product with (x,y). } /** gradient method for 3D noise */ inline static flt Grad(i32 hash, flt x, flt y, flt z) { i32 h = hash & 15; // Convert low 4 bits of hash code into 12 simple flt u = h < 8 ? x : y; // gradient directions, and compute dot product. flt v = h < 4 ? y : h == 12 || h == 14 ? x : z; // Fix repeats at h = 12 to 15 return ((h & 1) ? -u : u) + ((h & 2) ? -v : v); } /** gradient method for 4D noise */ inline static flt Grad(i32 hash, flt x, flt y, flt z, flt w) { i32 i = (hash & 31) << 2; return x * GRADIENT4D[i] + y * GRADIENT4D[i + 1] + z * GRADIENT4D[i + 2] + w * GRADIENT4D[i + 3]; } /** inits the permutation with the default values */ inline void InitPermutation() { for (ui32 i = 0; i < PERMUTATION_SIZE; i++) { _permutation[i] = i; } } public: /** constructor */ Simplex(const random::Random32& random_engine = random::Random32()): random::Random32Base(random_engine) { Init(); } /** deconstructor */ ~Simplex() {} //--------------------------------------------------------------------------- /** initializes the noise object -- should be done after you call SetRandomEngine resets the permutation and all properties frequency = 1 amplitude = 1 lacunarity = 2 persistence = 0.5 fractional increment = 0.19 octave count = 3 rigidity = 1 warp octave count = 1 warp octave multiplier = 1 warp octave increment = 0.19 warp octave displacement = 0 */ inline void Init() override { random::Random32Base::Init(); _frequency = DEFAULT_FREQUENCY; _amplitude = DEFAULT_AMPLITUDE; _lacunarity = DEFAULT_LACUNARITY; _persistence = DEFAULT_PERSISTENCE; _fractional_increment = DEFAULT_FRACTIONAL_INCREMENT; _octave_count = DEFAULT_OCTAVE_COUNT; _rigidity = DEFAULT_RIGIDITY; _warp_octave_count = DEFAULT_WARP_OCTAVE_COUNT; _warp_octave_multiplier = DEFAULT_WARP_OCTAVE_MULTIPLIER; _warp_octave_increment = DEFAULT_WARP_OCTAVE_INCREMENT; _warp_octave_displacement = DEFAULT_WARP_OCTAVE_DISPLACEMENT; InitPermutation(); ShufflePermutation(); } /** shuffles the internal permutation */ inline void ShufflePermutation() { for (i32 i = 0; i < PERMUTATION_SIZE; i++) { i32 index = GetRandomEngine().GetLemireWithinRange(PERMUTATION_SIZE - i); // do not swap with itself if (index != PERMUTATION_SIZE - 1 - i) { // temp = last number in perm yet to be shuffled ui8 temp = _permutation[PERMUTATION_SIZE - 1 - i]; _permutation[PERMUTATION_SIZE - 1 - i] = _permutation[index]; _permutation[index] = temp; } } } /** serialization method for us to write we require our objects to know which filepath they are a part of */ virtual ostrm& Insertion(ostrm& os, str filepath) const override { nlohmann::json json; str random32base_path = fs::append(fs::get_parent_path(filepath), "random32base_path"); json["random32base_path"] = random32base_path; json["frequency"] = _frequency; json["amplitude"] = _amplitude; json["lacunarity"] = _lacunarity; json["persistence"] = _persistence; json["fractional_increment"] = _fractional_increment; json["octave_count"] = _octave_count; json["rigidity"] = _rigidity; json["warp_octave_count"] = _warp_octave_count; json["warp_octace_multiplier"] = _warp_octave_multiplier; json["warp_octave_increment"] = _warp_octave_increment; json["warp_octave_displacement"] = _warp_octave_displacement; json["permutation"] = nlohmann::json::array(); for (i32 i = 0; i < PERMUTATION_SIZE; i++) { json["permutation"].push_back(_permutation[i]); } os << json.dump(NP_JSON_SPACING); random::Random32Base::SaveTo(random32base_path); return os; } /** deserialization method for us to read we require our objects to know which filepath they are a part of */ virtual istrm& Extraction(istrm& is, str filepath) override { nlohmann::json json; is >> json; _frequency = json["frequency"]; _amplitude = json["amplitude"]; _lacunarity = json["lacunarity"]; _persistence = json["persistence"]; _fractional_increment = json["fractional_increment"]; _octave_count = json["octave_count"]; _rigidity = json["rigidity"]; _warp_octave_count = json["warp_octave_count"]; _warp_octave_multiplier = json["warp_octace_multiplier"]; _warp_octave_increment = json["warp_octave_increment"]; _warp_octave_displacement = json["warp_octave_displacement"]; for (i32 i = 0; i < PERMUTATION_SIZE; i++) { _permutation[i] = json["permutation"][i]; } str random32base_path = json["random32base_path"]; random::Random32Base::LoadFrom(random32base_path); return is; } /** save oursellves inside the given dirpath return if the save was successful or not */ virtual bl SaveTo(str dirpath) const override { return Simplex::template SaveAs<Simplex>(fs::append(dirpath, AsFilename), this); } /** load outselves from the given dirpath return if the load was successful or not */ virtual bl LoadFrom(str dirpath) override { return Simplex::template LoadAs<Simplex>(fs::append(dirpath, AsFilename), this); } //--------------------------------------------------------------------------- /** sets frequency */ inline void SetFrequency(flt f) { _frequency = f; } /** gets frequency */ inline flt GetFrequency() const { return _frequency; } /** sets amplitude */ inline void SetAmplitude(flt a) { _amplitude = a; } /** gets amplitude */ inline flt GetAmplitude() const { return _amplitude; } /** sets lacunarity */ inline void SetLacunarity(flt l) { _lacunarity = l; } /** gets lacunarity */ inline flt GetLacunarity() const { return _lacunarity; } /** sets persistence */ inline void SetPersistence(flt p) { _persistence = p; } /** gets persistence */ inline flt GetPersistence() const { return _persistence; } /** sets fractional increment */ inline void SetFractionalIncrement(flt f) { _fractional_increment = f; } /** gets fractional increment */ inline flt GetFractionalIncrement() const { return _fractional_increment; } /** sets octave count */ inline void SetOctaveCount(ui8 o) { _octave_count = o; } /** gets octave count */ inline ui8 GetOctaveCount() const { return _octave_count; } /** sets rigidity inputs [0, 8] will use high performance pow, [9, 255] will use math::pow */ inline void SetRigidity(ui8 r) { _rigidity = r; } /** gets rigidity */ inline ui8 GetRigidity() const { return _rigidity; } /** sets the warp octave count recommend inputs [1, 2] - input 0 gives you fbm - inputs [3, +oo) is not very usable due to performance but produces cool results */ inline void SetWarpOctaveCount(ui8 count) { _warp_octave_count = count; } /** gets warp octave count */ inline ui8 GetWarpOctaveCount() const { return _warp_octave_count; } /** sets warp octave multiplier similar to frequency, as this adds more and more "folds" to the warped shape inputs recommend staying around 1 as in recommend inputs [0.5, 1.5] - can be anything */ inline void SetWarpOctaveMultiplier(flt multiplier) { _warp_octave_multiplier = multiplier; } /** gets warp octave multiplier */ inline flt GetWarpOctaveMultiplier() const { return _warp_octave_multiplier; } /** sets warp octave increment recommend inputs [0, 1] => [smooth, clumpy] but can be whatever - this is a very small detail - 0.19 was chosen as default */ inline void SetWarpOctaveIncrement(flt increment) { _warp_octave_increment = increment; } /** gest warp octave increment */ inline flt GetWarpOctaveIncrement() const { return _warp_octave_increment; } /** sets warp octave displacement recommend [0] for performance reasons - can be any value - recommend to change iff 0 is giving you too "regular" or "boring" warping and if so then recommend arbitrary input 0.19 */ inline void SetWarpOctaveDisplacement(flt displacement) { _warp_octave_displacement = displacement; } /** gest warp octave displacement */ inline flt GetWarpOctaveDisplacement() const { return _warp_octave_displacement; } //--------------------------------------------------------------------------- /** noise 1D output range [-amplitude, amplitude] */ inline flt Noise(flt x) const { return GetAmplitude() * CalculateNoise(GetFrequency() * x); } /** noise 2D output range [-amplitude, amplitude] */ inline flt Noise(flt x, flt y) const { return GetAmplitude() * CalculateNoise(GetFrequency() * x, GetFrequency() * y); } /** noise 3D output range [-amplitude, amplitude] */ inline flt Noise(flt x, flt y, flt z) const { return GetAmplitude() * CalculateNoise(GetFrequency() * x, GetFrequency() * y, GetFrequency() * z); } /** noise 4D output range [-amplitude, amplitude] */ inline flt Noise(flt x, flt y, flt z, flt w) const { return GetAmplitude() * CalculateNoise(GetFrequency() * x, GetFrequency() * y, GetFrequency() * z, GetFrequency() * w); } /** noise 1D output range [-1, 1] */ inline flt CalculateNoise(flt x) const { flt n0, n1; // Noise contributions from the two "corners" // No need to skew the input space in 1D // Corners coordinates (nearest integer values): i32 i0 = math::fastfloor(x); i32 i1 = i0 + 1; // Distances to corners (between 0 and 1): flt x0 = x - i0; flt x1 = x0 - 1.0f; // Calculate the contribution from the first corner flt t0 = 1.0f - x0 * x0; // if(t0 < 0.0f) t0 = 0.0f; // not possible t0 *= t0; n0 = t0 * t0 * Grad(Hash(i0), x0); // Calculate the contribution from the second corner flt t1 = 1.0f - x1 * x1; // if(t1 < 0.0f) t1 = 0.0f; // not possible t1 *= t1; n1 = t1 * t1 * Grad(Hash(i1), x1); // The maximum value of this noise is 8*(3/4)^4 = 2.53125 // A factor of 0.395 scales to fit exactly within [-1,1] return 0.395f * (n0 + n1); } /** noise 2D output range [-1, 1] */ inline flt CalculateNoise(flt x, flt y) const { flt n0, n1, n2; // Noise contributions from the three corners // Skewing/Unskewing factors for 2D static const flt F2 = 0.366025403f; // F2 = (math::sqrt(3) - 1) / 2 static const flt G2 = 0.211324865f; // G2 = (3 - math::sqrt(3)) / 6 = F2 / (1 + 2 * K) // Skew the input space to determine which simplex cell we're in flt s = (x + y) * F2; // Hairy factor for 2D flt xs = x + s; flt ys = y + s; i32 i = math::fastfloor(xs); i32 j = math::fastfloor(ys); // Unskew the cell origin back to (x,y) space flt t = static_cast<flt>(i + j) * G2; flt X0 = i - t; flt Y0 = j - t; flt x0 = x - X0; // The x,y distances from the cell origin flt y0 = y - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. i32 i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords if (x0 > y0) // lower triangle, XY order: (0,0)->(1,0)->(1,1) { i1 = 1; j1 = 0; } else // upper triangle, YX order: (0,0)->(0,1)->(1,1) { i1 = 0; j1 = 1; } // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-math::sqrt(3))/6 flt x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords flt y1 = y0 - j1 + G2; flt x2 = x0 - 1.0f + 2.0f * G2; // Offsets for last corner in (x,y) unskewed coords flt y2 = y0 - 1.0f + 2.0f * G2; // Calculate the contribution from the first corner flt t0 = 0.5f - x0 * x0 - y0 * y0; if (t0 < 0.0f) { n0 = 0.0f; } else { // Work out the hashed gradient indices of the three simplex corners i32 gi0 = Hash(i + Hash(j)); t0 *= t0; n0 = t0 * t0 * Grad(gi0, x0, y0); } // Calculate the contribution from the second corner flt t1 = 0.5f - x1 * x1 - y1 * y1; if (t1 < 0.0f) { n1 = 0.0f; } else { // Work out the hashed gradient indices of the three simplex corners i32 gi1 = Hash(i + i1 + Hash(j + j1)); t1 *= t1; n1 = t1 * t1 * Grad(gi1, x1, y1); } // Calculate the contribution from the third corner flt t2 = 0.5f - x2 * x2 - y2 * y2; if (t2 < 0.0f) { n2 = 0.0f; } else { // Work out the hashed gradient indices of the three simplex corners i32 gi2 = Hash(i + 1 + Hash(j + 1)); t2 *= t2; n2 = t2 * t2 * Grad(gi2, x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return 45.23065f * (n0 + n1 + n2); } /** noise 3D output range [-1, 1] */ inline flt CalculateNoise(flt x, flt y, flt z) const { flt n0, n1, n2, n3; // Noise contributions from the four corners // Skewing/Unskewing factors for 3D static const flt F3 = 1.0f / 3.0f; static const flt G3 = 1.0f / 6.0f; // Skew the input space to determine which simplex cell we're in flt s = (x + y + z) * F3; // Very nice and simple skew factor for 3D i32 i = math::fastfloor(x + s); i32 j = math::fastfloor(y + s); i32 k = math::fastfloor(z + s); flt t = (i + j + k) * G3; flt X0 = i - t; // Unskew the cell origin back to (x,y,z) space flt Y0 = j - t; flt Z0 = k - t; flt x0 = x - X0; // The x,y,z distances from the cell origin flt y0 = y - Y0; flt z0 = z - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. i32 i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords i32 i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords if (x0 >= y0) { if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; // X Y Z order } else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; // X Z Y order } else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; // Z X Y order } } else // x0<y0 { if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; // Z Y X order } else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; // Y Z X order } else { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; // Y X Z order } } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where // c = 1/6. flt x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords flt y1 = y0 - j1 + G3; flt z1 = z0 - k1 + G3; flt x2 = x0 - i2 + 2.0f * G3; // Offsets for third corner in (x,y,z) coords flt y2 = y0 - j2 + 2.0f * G3; flt z2 = z0 - k2 + 2.0f * G3; flt x3 = x0 - 1.0f + 3.0f * G3; // Offsets for last corner in (x,y,z) coords flt y3 = y0 - 1.0f + 3.0f * G3; flt z3 = z0 - 1.0f + 3.0f * G3; // Calculate the contribution from the four corners flt t0 = 0.6f - x0 * x0 - y0 * y0 - z0 * z0; if (t0 < 0) { n0 = 0.0; } else { // Work out the hashed gradient indices of the four simplex corners i32 gi0 = Hash(i + Hash(j + Hash(k))); t0 *= t0; n0 = t0 * t0 * Grad(gi0, x0, y0, z0); } flt t1 = 0.6f - x1 * x1 - y1 * y1 - z1 * z1; if (t1 < 0) { n1 = 0.0; } else { // Work out the hashed gradient indices of the four simplex corners i32 gi1 = Hash(i + i1 + Hash(j + j1 + Hash(k + k1))); t1 *= t1; n1 = t1 * t1 * Grad(gi1, x1, y1, z1); } flt t2 = 0.6f - x2 * x2 - y2 * y2 - z2 * z2; if (t2 < 0) { n2 = 0.0; } else { // Work out the hashed gradient indices of the four simplex corners i32 gi2 = Hash(i + i2 + Hash(j + j2 + Hash(k + k2))); t2 *= t2; n2 = t2 * t2 * Grad(gi2, x2, y2, z2); } flt t3 = 0.6f - x3 * x3 - y3 * y3 - z3 * z3; if (t3 < 0) { n3 = 0.0; } else { // Work out the hashed gradient indices of the four simplex corners i32 gi3 = Hash(i + 1 + Hash(j + 1 + Hash(k + 1))); t3 *= t3; n3 = t3 * t3 * Grad(gi3, x3, y3, z3); } // Add contributions from each corner to get the final noise value. // The result is scaled to stay just inside [-1,1] return 32.0f * (n0 + n1 + n2 + n3); } /** noise 4D output range [-1, 1] */ inline flt CalculateNoise(flt x, flt y, flt z, flt w) const { flt n0, n1, n2, n3, n4; // Skewing/Unskewing factors for 4D static const flt F4 = (flt)(math::sqrt(5.f) - 1.f) / 4.f; static const flt G4 = (flt)(5.f - math::sqrt(5.f)) / 20.f; flt t = (x + y + z + w) * F4; i32 i = math::fastfloor(x + t); i32 j = math::fastfloor(y + t); i32 k = math::fastfloor(z + t); i32 l = math::fastfloor(w + t); t = (i + j + k + l) * G4; flt X0 = i - t; flt Y0 = j - t; flt Z0 = k - t; flt W0 = l - t; flt x0 = x - X0; flt y0 = y - Y0; flt z0 = z - Z0; flt w0 = w - W0; i32 rankx = 0; i32 ranky = 0; i32 rankz = 0; i32 rankw = 0; if (x0 > y0) { rankx++; } else { ranky++; } if (x0 > z0) { rankx++; } else { rankz++; } if (x0 > w0) { rankx++; } else { rankw++; } if (y0 > z0) { ranky++; } else { rankz++; } if (y0 > w0) { ranky++; } else { rankw++; } if (z0 > w0) { rankz++; } else { rankw++; } i32 i1 = rankx >= 3 ? 1 : 0; i32 j1 = ranky >= 3 ? 1 : 0; i32 k1 = rankz >= 3 ? 1 : 0; i32 l1 = rankw >= 3 ? 1 : 0; i32 i2 = rankx >= 2 ? 1 : 0; i32 j2 = ranky >= 2 ? 1 : 0; i32 k2 = rankz >= 2 ? 1 : 0; i32 l2 = rankw >= 2 ? 1 : 0; i32 i3 = rankx >= 1 ? 1 : 0; i32 j3 = ranky >= 1 ? 1 : 0; i32 k3 = rankz >= 1 ? 1 : 0; i32 l3 = rankw >= 1 ? 1 : 0; flt x1 = x0 - i1 + G4; flt y1 = y0 - j1 + G4; flt z1 = z0 - k1 + G4; flt w1 = w0 - l1 + G4; flt x2 = x0 - i2 + 2 * G4; flt y2 = y0 - j2 + 2 * G4; flt z2 = z0 - k2 + 2 * G4; flt w2 = w0 - l2 + 2 * G4; flt x3 = x0 - i3 + 3 * G4; flt y3 = y0 - j3 + 3 * G4; flt z3 = z0 - k3 + 3 * G4; flt w3 = w0 - l3 + 3 * G4; flt x4 = x0 - 1 + 4 * G4; flt y4 = y0 - 1 + 4 * G4; flt z4 = z0 - 1 + 4 * G4; flt w4 = w0 - 1 + 4 * G4; t = flt(0.6) - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; if (t < 0) { n0 = 0; } else { i32 gi0 = Hash(i + Hash(j + Hash(k + Hash(l)))); t *= t; n0 = t * t * Grad(gi0, x0, y0, z0, w0); } t = flt(0.6) - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; if (t < 0) { n1 = 0; } else { i32 gi1 = Hash(i + i1 + Hash(j + j1 + Hash(k + k1 + Hash(l + l1)))); t *= t; n1 = t * t * Grad(gi1, x1, y1, z1, w1); } t = flt(0.6) - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; if (t < 0) { n2 = 0; } else { i32 gi2 = Hash(i + i2 + Hash(j + j2 + Hash(k + k2 + Hash(l + l2)))); t *= t; n2 = t * t * Grad(gi2, x2, y2, z2, w2); } t = flt(0.6) - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; if (t < 0) { n3 = 0; } else { i32 gi3 = Hash(i + i3 + Hash(j + j3 + Hash(k + k3 + Hash(l + l3)))); t *= t; n3 = t * t * Grad(gi3, x3, y3, z3, w3); } t = flt(0.6) - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; if (t < 0) { n4 = 0; } else { i32 gi4 = Hash(i + 1 + Hash(j + 1 + Hash(k + 1 + Hash(l + 1)))); t *= t; n4 = t * t * Grad(gi4, x4, y4, z4, w4); } return 27 * (n0 + n1 + n2 + n3 + n4); } /** fractal noise 1D - the same layer of noise will be added on top of itself with respect to lacunarity Note: fractal noise may contain artifacts due to it layers the same layer of noise on top of itself output range [-1, 1] */ inline flt Fractal(flt x) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * CalculateNoise(x * frequency); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } return output / denom; } /** fractal noise 2D - the same layer of noise will be added on top of itself an octave count number of times with detail respect to lacunarity Note: fractal noise may contain artifacts due to it layers the same layer of noise on top of itself output range [-1, 1] */ inline flt Fractal(flt x, flt y) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * CalculateNoise(x * frequency, y * frequency); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } return output / denom; } /** fractal noise 3D - the same layer of noise will be added on top of itself an octave count number of times with detail respect to lacunarity Note: fractal noise may contain artifacts due to it layers the same layer of noise on top of itself output range [-1, 1] */ inline flt Fractal(flt x, flt y, flt z) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * CalculateNoise(x * frequency, y * frequency, z * frequency); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } return output / denom; } /** fractal noise 4D - the same layer of noise will be added on top of itself an octave count number of times with detail respect to lacunarity Note: fractal noise may contain artifacts due to it layers the same layer of noise on top of itself output range [-1, 1] */ inline flt Fractal(flt x, flt y, flt z, flt w) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * CalculateNoise(x * frequency, y * frequency, z * frequency, w * frequency); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } return output / denom; } /** fractional noise 1D - adds an octave count number of layers of noise together with detail respect to lacunarity - the added layers are fractional incremenet's value away from each other in 2D Note: if fractional increment is zero, then fractional noise may contain artifacts due to it layers the same layer of noise on top of itself output range [-1, 1] */ inline flt Fractional(flt x) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * CalculateNoise(x * frequency, i * _fractional_increment * frequency); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } return output / denom; } /** fractional noise 2D - adds an octave count number of layers of noise together with detail respect to lacunarity - the added layers are fractional incremenet's value away from each other in 3D Note: if fractional increment is zero, then fractional noise may contain artifacts due to it layers the same layer of noise on top of itself output range [-1, 1] */ inline flt Fractional(flt x, flt y) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * CalculateNoise(x * frequency, y * frequency, i * _fractional_increment * frequency); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } return output / denom; } /** fractional noise 3D - adds an octave count number of layers of noise together with detail respect to lacunarity - the added layers are fractional incremenet's value away from each other in 4D Note: if fractional increment is zero, then fractional noise may contain artifacts due to it layers the same layer of noise on top of itself output range [-1, 1] */ inline flt Fractional(flt x, flt y, flt z) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * CalculateNoise(x * frequency, y * frequency, z * frequency, i * _fractional_increment * frequency); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } return output / denom; } /** rigid fractal noise 1D - provides the same noise as fractal 1D but adds the abs value of each layer then subtracts it from 1 then raises it to the rigidity value's power output range [0, 1] */ inline flt RigidFractal(flt x) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * math::abs(CalculateNoise(x * frequency)); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } output /= denom; output = math::flip(output); switch (_rigidity) { case 0: output = math::pow0(output); break; case 1: output = math::pow1(output); break; case 2: output = math::pow2(output); break; case 3: output = math::pow3(output); break; case 4: output = math::pow4(output); break; case 5: output = math::pow5(output); break; case 6: output = math::pow6(output); break; case 7: output = math::pow7(output); break; case 8: output = math::pow8(output); break; default: output = math::pow(output, _rigidity); break; } return output; } /** rigid fractal noise 2D - provides the same noise as fractal 2D but adds the abs value of each layer then subtracts it from 1 then raises it to the rigidity value's power output range [0, 1] */ inline flt RigidFractal(flt x, flt y) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * math::abs(CalculateNoise(x * frequency, y * frequency)); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } output /= denom; output = math::flip(output); switch (_rigidity) { case 0: output = math::pow0(output); break; case 1: output = math::pow1(output); break; case 2: output = math::pow2(output); break; case 3: output = math::pow3(output); break; case 4: output = math::pow4(output); break; case 5: output = math::pow5(output); break; case 6: output = math::pow6(output); break; case 7: output = math::pow7(output); break; case 8: output = math::pow8(output); break; default: output = math::pow(output, _rigidity); break; } return output; } /** rigid fractal noise 3D - provides the same noise as fractal 3D but adds the abs value of each layer then subtracts it from 1 then raises it to the rigidity value's power output range [0, 1] */ inline flt RigidFractal(flt x, flt y, flt z) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * math::abs(CalculateNoise(x * frequency, y * frequency, z * frequency)); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } output /= denom; output = math::flip(output); switch (_rigidity) { case 0: output = math::pow0(output); break; case 1: output = math::pow1(output); break; case 2: output = math::pow2(output); break; case 3: output = math::pow3(output); break; case 4: output = math::pow4(output); break; case 5: output = math::pow5(output); break; case 6: output = math::pow6(output); break; case 7: output = math::pow7(output); break; case 8: output = math::pow8(output); break; default: output = math::pow(output, _rigidity); break; } return output; } /** rigid fractal noise 4D - provides the same noise as fractal 4D but adds the abs value of each layer then subtracts it from 1 then raises it to the rigidity value's power output range [0, 1] */ inline flt RigidFractal(flt x, flt y, flt z, flt w) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * math::abs(CalculateNoise(x * frequency, y * frequency, z * frequency, w * frequency)); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } output /= denom; output = math::flip(output); switch (_rigidity) { case 0: output = math::pow0(output); break; case 1: output = math::pow1(output); break; case 2: output = math::pow2(output); break; case 3: output = math::pow3(output); break; case 4: output = math::pow4(output); break; case 5: output = math::pow5(output); break; case 6: output = math::pow6(output); break; case 7: output = math::pow7(output); break; case 8: output = math::pow8(output); break; default: output = math::pow(output, _rigidity); break; } return output; } /** rigid fractional noise 1D - provides the same noise as fractional 1D but adds the abs value of each layer then subtracts it from 1 then raises it to the rigidity value's power output range [0, 1] */ inline flt RigidFractional(flt x) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * math::abs(CalculateNoise(x * frequency, i * _fractional_increment * frequency)); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } output /= denom; output = math::flip(output); switch (_rigidity) { case 0: output = math::pow0(output); break; case 1: output = math::pow1(output); break; case 2: output = math::pow2(output); break; case 3: output = math::pow3(output); break; case 4: output = math::pow4(output); break; case 5: output = math::pow5(output); break; case 6: output = math::pow6(output); break; case 7: output = math::pow7(output); break; case 8: output = math::pow8(output); break; default: output = math::pow(output, _rigidity); break; } return output; } /** rigid fractional noise 2D - provides the same noise as fractional 2D but adds the abs value of each layer then subtracts it from 1 then raises it to the rigidity value's power output range [0, 1] */ inline flt RigidFractional(flt x, flt y) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * math::abs(CalculateNoise(x * frequency, y * frequency, i * _fractional_increment * frequency)); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } output /= denom; output = math::flip(output); switch (_rigidity) { case 0: output = math::pow0(output); break; case 1: output = math::pow1(output); break; case 2: output = math::pow2(output); break; case 3: output = math::pow3(output); break; case 4: output = math::pow4(output); break; case 5: output = math::pow5(output); break; case 6: output = math::pow6(output); break; case 7: output = math::pow7(output); break; case 8: output = math::pow8(output); break; default: output = math::pow(output, _rigidity); break; } return output; } /** rigid fractional noise 3D - provides the same noise as fractional 3D but adds the abs value of each layer then subtracts it from 1 then raises it to the rigidity value's power output range [0, 1] */ inline flt RigidFractional(flt x, flt y, flt z) const { flt output = 0.f; flt denom = 0.f; flt frequency = _frequency; flt amplitude = _amplitude; for (ui8 i = 0; i < _octave_count; i++) { output += amplitude * math::abs(CalculateNoise(x * frequency, y * frequency, z * frequency, i * _fractional_increment * frequency)); denom += amplitude; frequency *= _lacunarity; amplitude *= _persistence; } output /= denom; output = math::flip(output); switch (_rigidity) { case 0: output = math::pow0(output); break; case 1: output = math::pow1(output); break; case 2: output = math::pow2(output); break; case 3: output = math::pow3(output); break; case 4: output = math::pow4(output); break; case 5: output = math::pow5(output); break; case 6: output = math::pow6(output); break; case 7: output = math::pow7(output); break; case 8: output = math::pow8(output); break; default: output = math::pow(output, _rigidity); break; } return output; } /** billow fractal noise 1D - provides the same noise as rigid fractal 1D but subtracts it from 1 */ inline flt BillowFractal(flt x) const { return math::flip(RigidFractal(x)); } /** billow fractal noise 2D - provides the same noise as rigid fractal 2D but subtracts it from 1 */ inline flt BillowFractal(flt x, flt y) const { return math::flip(RigidFractal(x, y)); } /** billow fractal noise 3D - provides the same noise as rigid fractal 3D but subtracts it from 1 */ inline flt BillowFractal(flt x, flt y, flt z) const { return math::flip(RigidFractal(x, y, z)); } /** billow fractal noise 4D - provides the same noise as rigid fractal 4D but subtracts it from 1 */ inline flt BillowFractal(flt x, flt y, flt z, flt w) const { return math::flip(RigidFractal(x, y, z, w)); } /** billow fractional 1D - provides the same noise as rigid fractional 1D but subtracts it from 1 */ inline flt BillowFractional(flt x) const { return math::flip(RigidFractional(x)); } /** billow fractional 2D - provides the same noise as rigid fractional 2D but subtracts it from 1 */ inline flt BillowFractional(flt x, flt y) const { return math::flip(RigidFractional(x, y)); } /** billow fractional 3D - provides the same noise as rigid fractional 3D but subtracts it from 1 */ inline flt BillowFractional(flt x, flt y, flt z) const { return math::flip(RigidFractional(x, y, z)); } /** warpped fractal 1D - provides the same noise as fractal 1D but warps it through itself based on warp related fields */ inline flt WarpFractal(flt x) const { ui8 woc = _warp_octave_count; flt wom = _warp_octave_multiplier; flt woi = _warp_octave_increment; flt wod = _warp_octave_displacement; flt wx = 0; // warping x flt output = 0; // with wod = 0, ox and oy would end up being the same value, so we just use ox below for (ui8 i = 0; i < woc; i++) { wx = Fractal(x + wom * wx + (i + wod) * woi); } output = Fractal(x + wom * wx + woc * woi); return output; } /** warpped fractal 2D - provides the same noise as fractal 2D but warps it through itself based on warp related fields */ inline flt WarpFractal(flt x, flt y) const { ui8 woc = _warp_octave_count; flt wom = _warp_octave_multiplier; flt woi = _warp_octave_increment; flt wod = _warp_octave_displacement; flt wx = 0; // warping x flt wy = 0; // warping y flt output = 0; if (wod == 0) { // with wod = 0, ox and oy would end up being the same value, so we just use ox below for (ui8 i = 0; i < woc; i++) { wx = Fractal(x + wom * wx + i * woi, y + wom * wx + i * woi); } output = Fractal(x + wom * wx + woc * woi, y + wom * wx + woc * woi); } else { for (ui8 i = 0; i < woc; i++) { wx = Fractal(x + wom * wx + i * woi, y + wom * wy + i * woi); wy = Fractal(x + wom * wx + (i + wod) * woi, y + wom * wy + (i + wod) * woi); } output = Fractal(x + wom * wx + woc * woi, y + wom * wy + woc * woi); } return output; } /** warpped fractal 3D - provides the same noise as fractal 3D but warps it through itself based on warp related fields */ inline flt WarpFractal(flt x, flt y, flt z) const { ui8 woc = _warp_octave_count; flt wom = _warp_octave_multiplier; flt woi = _warp_octave_increment; flt wod = _warp_octave_displacement; flt wx = 0; // warping x flt wy = 0; // warping y flt wz = 0; // warping z flt output = 0; if (wod == 0) { // with wod = 0, ox and oy would end up being the same value, so we just use ox below for (ui8 i = 0; i < woc; i++) { wx = Fractal(x + wom * wx + i * woi, y + wom * wx + i * woi, z + wom * wz + i * woi); } output = Fractal(x + wom * wx + woc * woi, y + wom * wx + woc * woi, z + wom * wz + woc * woi); } else { for (ui8 i = 0; i < woc; i++) { wx = Fractal(x + wom * wx + i * woi, y + wom * wy + i * woi, z + wom * wz + i * woi); wy = Fractal(x + wom * wx + (i + wod) * woi, y + wom * wy + (i + wod) * woi, z + wom * wz + (i + wod) * woi); wz = Fractal(x + wom * wx + (i + 2 * wod) * woi, y + wom * wy + (i + 2 * wod) * woi, z + wom * wz + (i + 2 * wod) * woi); } output = Fractal(x + wom * wx + woc * woi, y + wom * wy + woc * woi, z + wom * wz + woc * woi); } return output; } /** warpped fractal 4D - provides the same noise as fractal 4D but warps it through itself based on warp related fields */ inline flt WarpFractal(flt x, flt y, flt z, flt w) const { ui8 woc = _warp_octave_count; flt wom = _warp_octave_multiplier; flt woi = _warp_octave_increment; flt wod = _warp_octave_displacement; flt wx = 0; // warping x flt wy = 0; // warping y flt wz = 0; // warping z flt ww = 0; // warping w flt output = 0; if (wod == 0) { // with wod = 0, ox and oy would end up being the same value, so we just use ox below for (ui8 i = 0; i < woc; i++) { wx = Fractal(x + wom * wx + i * woi, y + wom * wx + i * woi, z + wom * wz + i * woi, w + wom * ww + i * woi); } output = Fractal(x + wom * wx + woc * woi, y + wom * wx + woc * woi, z + wom * wz + woc * woi, w + wom * ww + woc * woi); } else { for (ui8 i = 0; i < woc; i++) { wx = Fractal(x + wom * wx + i * woi, y + wom * wy + i * woi, z + wom * wz + i * woi, w + wom * ww + i * woi); wy = Fractal(x + wom * wx + (i + wod) * woi, y + wom * wy + (i + wod) * woi, z + wom * wz + (i + wod) * woi, w + wom * ww + (i + wod) * woi); wz = Fractal(x + wom * wx + (i + 2 * wod) * woi, y + wom * wy + (i + 2 * wod) * woi, z + wom * wz + (i + 2 * wod) * woi, w + wom * ww + (i + 2 * wod) * woi); ww = Fractal(x + wom * wx + (i + 4 * wod) * woi, y + wom * wy + (i + 4 * wod) * woi, z + wom * wz + (i + 4 * wod) * woi, w + wom * ww + (i + 4 * wod) * woi); } output = Fractal(x + wom * wx + woc * woi, y + wom * wy + woc * woi, z + wom * wz + woc * woi, w + wom * ww + woc * woi); } return output; } /** warpped fractional 1D - provides the same noise as fractional 1D but warps it through itself based on warp related fields */ inline flt WarpFractional(flt x) const { ui8 woc = _warp_octave_count; flt wom = _warp_octave_multiplier; flt woi = _warp_octave_increment; flt wod = _warp_octave_displacement; flt wx = 0; // warping x flt output = 0; // with wod = 0, ox and oy would end up being the same value, so we just use ox below for (ui8 i = 0; i < woc; i++) { wx = Fractional(x + wom * wx + (i + wod) * woi); } output = Fractional(x + wom * wx + woc * woi); return output; } /** warpped fractional 2D - provides the same noise as fractional 2D but warps it through itself based on warp related fields */ inline flt WarpFractional(flt x, flt y) const { ui8 woc = _warp_octave_count; flt wom = _warp_octave_multiplier; flt woi = _warp_octave_increment; flt wod = _warp_octave_displacement; flt wx = 0; // warping x flt wy = 0; // warping y flt output = 0; if (wod == 0) { // with wod = 0, ox and oy would end up being the same value, so we just use ox below for (ui8 i = 0; i < woc; i++) { wx = Fractional(x + wom * wx + i * woi, y + wom * wx + i * woi); } output = Fractional(x + wom * wx + woc * woi, y + wom * wx + woc * woi); } else { for (ui8 i = 0; i < woc; i++) { wx = Fractional(x + wom * wx + i * woi, y + wom * wy + i * woi); wy = Fractional(x + wom * wx + (i + wod) * woi, y + wom * wy + (i + wod) * woi); } output = Fractional(x + wom * wx + woc * woi, y + wom * wy + woc * woi); } return output; } /** warpped fractional 3D - provides the same noise as fractional 3D but warps it through itself based on warp related fields */ inline flt WarpFractional(flt x, flt y, flt z) const { ui8 woc = _warp_octave_count; flt wom = _warp_octave_multiplier; flt woi = _warp_octave_increment; flt wod = _warp_octave_displacement; flt wx = 0; // warping x flt wy = 0; // warping y flt wz = 0; // warping z flt output = 0; if (wod == 0) { // with wod = 0, ox and oy would end up being the same value, so we just use ox below for (ui8 i = 0; i < woc; i++) { wx = Fractional(x + wom * wx + i * woi, y + wom * wx + i * woi, z + wom * wz + i * woi); } output = Fractional(x + wom * wx + woc * woi, y + wom * wx + woc * woi, z + wom * wz + woc * woi); } else { for (ui8 i = 0; i < woc; i++) { wx = Fractional(x + wom * wx + i * woi, y + wom * wy + i * woi, z + wom * wz + i * woi); wy = Fractional(x + wom * wx + (i + wod) * woi, y + wom * wy + (i + wod) * woi, z + wom * wz + (i + wod) * woi); wz = Fractional(x + wom * wx + (i + 2 * wod) * woi, y + wom * wy + (i + 2 * wod) * woi, z + wom * wz + (i + 2 * wod) * woi); } output = Fractional(x + wom * wx + woc * woi, y + wom * wy + woc * woi, z + wom * wz + woc * woi); } return output; } }; } // namespace noise } // namespace np #endif /* NP_ENGINE_SIMPLEX_HPP */
26.34322
119
0.562651
[ "object", "shape", "3d" ]
aba7e81d17421f4bf3ed98e44eb8ca72e6a8de94
8,633
hpp
C++
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/srv/detail/revive_task__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/srv/detail/revive_task__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/srv/detail/revive_task__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
2
2021-06-21T07:32:09.000Z
2021-08-17T03:05:38.000Z
// generated from rosidl_generator_cpp/resource/idl__struct.hpp.em // with input from rmf_task_msgs:srv/ReviveTask.idl // generated code does not contain a copyright notice #ifndef RMF_TASK_MSGS__SRV__DETAIL__REVIVE_TASK__STRUCT_HPP_ #define RMF_TASK_MSGS__SRV__DETAIL__REVIVE_TASK__STRUCT_HPP_ #include <rosidl_runtime_cpp/bounded_vector.hpp> #include <rosidl_runtime_cpp/message_initialization.hpp> #include <algorithm> #include <array> #include <memory> #include <string> #include <vector> #ifndef _WIN32 # define DEPRECATED__rmf_task_msgs__srv__ReviveTask_Request __attribute__((deprecated)) #else # define DEPRECATED__rmf_task_msgs__srv__ReviveTask_Request __declspec(deprecated) #endif namespace rmf_task_msgs { namespace srv { // message struct template<class ContainerAllocator> struct ReviveTask_Request_ { using Type = ReviveTask_Request_<ContainerAllocator>; explicit ReviveTask_Request_(rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) { if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->requester = ""; this->task_id = ""; } } explicit ReviveTask_Request_(const ContainerAllocator & _alloc, rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) : requester(_alloc), task_id(_alloc) { if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->requester = ""; this->task_id = ""; } } // field types and members using _requester_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _requester_type requester; using _task_id_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _task_id_type task_id; // setters for named parameter idiom Type & set__requester( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->requester = _arg; return *this; } Type & set__task_id( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->task_id = _arg; return *this; } // constant declarations // pointer types using RawPtr = rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator> *; using ConstRawPtr = const rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator> const>; template<typename Deleter = std::default_delete< rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete< rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED__rmf_task_msgs__srv__ReviveTask_Request std::shared_ptr<rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator>> Ptr; typedef DEPRECATED__rmf_task_msgs__srv__ReviveTask_Request std::shared_ptr<rmf_task_msgs::srv::ReviveTask_Request_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const ReviveTask_Request_ & other) const { if (this->requester != other.requester) { return false; } if (this->task_id != other.task_id) { return false; } return true; } bool operator!=(const ReviveTask_Request_ & other) const { return !this->operator==(other); } }; // struct ReviveTask_Request_ // alias to use template instance with default allocator using ReviveTask_Request = rmf_task_msgs::srv::ReviveTask_Request_<std::allocator<void>>; // constant definitions } // namespace srv } // namespace rmf_task_msgs #ifndef _WIN32 # define DEPRECATED__rmf_task_msgs__srv__ReviveTask_Response __attribute__((deprecated)) #else # define DEPRECATED__rmf_task_msgs__srv__ReviveTask_Response __declspec(deprecated) #endif namespace rmf_task_msgs { namespace srv { // message struct template<class ContainerAllocator> struct ReviveTask_Response_ { using Type = ReviveTask_Response_<ContainerAllocator>; explicit ReviveTask_Response_(rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) { if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->success = false; } } explicit ReviveTask_Response_(const ContainerAllocator & _alloc, rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) { (void)_alloc; if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->success = false; } } // field types and members using _success_type = bool; _success_type success; // setters for named parameter idiom Type & set__success( const bool & _arg) { this->success = _arg; return *this; } // constant declarations // pointer types using RawPtr = rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator> *; using ConstRawPtr = const rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator> const>; template<typename Deleter = std::default_delete< rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete< rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED__rmf_task_msgs__srv__ReviveTask_Response std::shared_ptr<rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator>> Ptr; typedef DEPRECATED__rmf_task_msgs__srv__ReviveTask_Response std::shared_ptr<rmf_task_msgs::srv::ReviveTask_Response_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const ReviveTask_Response_ & other) const { if (this->success != other.success) { return false; } return true; } bool operator!=(const ReviveTask_Response_ & other) const { return !this->operator==(other); } }; // struct ReviveTask_Response_ // alias to use template instance with default allocator using ReviveTask_Response = rmf_task_msgs::srv::ReviveTask_Response_<std::allocator<void>>; // constant definitions } // namespace srv } // namespace rmf_task_msgs namespace rmf_task_msgs { namespace srv { struct ReviveTask { using Request = rmf_task_msgs::srv::ReviveTask_Request; using Response = rmf_task_msgs::srv::ReviveTask_Response; }; } // namespace srv } // namespace rmf_task_msgs #endif // RMF_TASK_MSGS__SRV__DETAIL__REVIVE_TASK__STRUCT_HPP_
31.278986
164
0.760222
[ "vector" ]
aba8fb217a48b78efc1eb0a15d6daf7f89088870
1,675
cpp
C++
tests/graphics/CGraphicsLayersInfoTests.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-15T01:14:15.000Z
2019-07-15T01:14:15.000Z
tests/graphics/CGraphicsLayersInfoTests.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
76
2018-10-27T16:59:36.000Z
2022-03-30T17:40:39.000Z
tests/graphics/CGraphicsLayersInfoTests.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-29T02:02:08.000Z
2019-07-29T02:02:08.000Z
#include <catch2/catch.hpp> #include <TDEngine2.h> #include <climits> #include <tuple> using namespace TDEngine2; TEST_CASE("CGraphicsLayersInfo Tests") { E_RESULT_CODE result = RC_OK; IGraphicsLayersInfo* pGraphicsLayersInfo = CreateGraphicsLayersInfo(result); REQUIRE(result == RC_OK); SECTION("TestGetLayerIndex_WithSingleLayer_AlwaysReturnsZero") { F32 testSamples[] { (std::numeric_limits<F32>::min)(), 0.0f, 1000.0f ,(std::numeric_limits<F32>::max)() }; for (F32 currTestSample : testSamples) { REQUIRE(pGraphicsLayersInfo->GetLayerIndex(currTestSample) == 0); } } SECTION("TestGetLayerIndex_AddLayersAndRetrieveTheirIndices_ReturnsCorrectIndices") { std::vector<std::pair<F32, U32>> testSet { { -(std::numeric_limits<F32>::infinity)(), 0 }, { 1.0f, 1 }, { 10.0f, 1 }, { 64.0f, 2 }, { 256.0f, 3 }, { 1024.0f, 4 }, }; F32 graphicsLayersBounds[] { 0.0f, 10.0f, 100.0f, 500.0f }; for (F32 currLayerRightBound : graphicsLayersBounds) { REQUIRE(pGraphicsLayersInfo->AddLayer(currLayerRightBound) == RC_OK); } for (auto iter = testSet.cbegin(); iter != testSet.cend(); ++iter) { REQUIRE(pGraphicsLayersInfo->GetLayerIndex((*iter).first) == (*iter).second); } } SECTION("TestAddLayer_IncorrectDefinitionsOrder_AddLayerReturnsError") { std::vector<std::pair<F32, E_RESULT_CODE>> testSet { { 0.0f, RC_OK }, { 10.0f, RC_OK }, { 5.0f, RC_INVALID_ARGS }, { 15.0f, RC_OK }, }; for (auto iter = testSet.cbegin(); iter != testSet.cend(); ++iter) { REQUIRE(pGraphicsLayersInfo->AddLayer((*iter).first) == (*iter).second); } } REQUIRE(pGraphicsLayersInfo->Free() == RC_OK); }
23.928571
108
0.674627
[ "vector" ]
abb030426f1716f056eea972259621e3cbabbfef
14,506
cpp
C++
SurgSim/Physics/Fem3DRepresentation.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
24
2015-01-19T16:18:59.000Z
2022-03-13T03:29:11.000Z
SurgSim/Physics/Fem3DRepresentation.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
3
2018-12-21T14:54:08.000Z
2022-03-14T12:38:07.000Z
SurgSim/Physics/Fem3DRepresentation.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
8
2015-04-10T19:45:36.000Z
2022-02-02T17:00:59.000Z
// This file is a part of the OpenSurgSim project. // Copyright 2013-2016, SimQuest Solutions 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 "SurgSim/DataStructures/IndexedLocalCoordinate.h" #include "SurgSim/DataStructures/Location.h" #include "SurgSim/Framework/Assert.h" #include "SurgSim/Framework/Asset.h" #include "SurgSim/Math/MeshShape.h" #include "SurgSim/Math/OdeState.h" #include "SurgSim/Math/SparseMatrix.h" #include "SurgSim/Physics/DeformableCollisionRepresentation.h" #include "SurgSim/Physics/Fem3DElementCube.h" #include "SurgSim/Physics/Fem3DElementTetrahedron.h" #include "SurgSim/Physics/Fem3DLocalization.h" #include "SurgSim/Physics/Fem3DRepresentation.h" #include "SurgSim/Physics/FemElement.h" #include "SurgSim/Physics/Localization.h" namespace { void transformVectorByBlockOf3(const SurgSim::Math::RigidTransform3d& transform, SurgSim::Math::Vector* x, bool rotationOnly = false) { Eigen::Index numNodes = x->size() / 3; SURGSIM_ASSERT(numNodes * 3 == x->size()) << "Unexpected number of dof in a Fem3D state vector (not a multiple of 3)"; for (Eigen::Index nodeId = 0; nodeId < numNodes; nodeId++) { SurgSim::Math::Vector3d xi = x->segment<3>(3 * nodeId); x->segment<3>(3 * nodeId) = (rotationOnly) ? transform.linear() * xi : transform * xi; } } } namespace SurgSim { namespace Physics { SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::Fem3DRepresentation, Fem3DRepresentation); Fem3DRepresentation::Fem3DRepresentation(const std::string& name) : FemRepresentation(name) { SURGSIM_ADD_SERIALIZABLE_PROPERTY(Fem3DRepresentation, std::shared_ptr<SurgSim::Framework::Asset>, Fem, getFem, setFem); SURGSIM_ADD_SETTER(Fem3DRepresentation, std::string, FemFileName, loadFem) // Reminder: m_numDofPerNode is held by DeformableRepresentation // but needs to be set by all concrete derived classes m_numDofPerNode = 3; m_fem = std::make_shared<Fem3D>(); } Fem3DRepresentation::~Fem3DRepresentation() { } void Fem3DRepresentation::loadFem(const std::string& fileName) { auto mesh = std::make_shared<Fem3D>(); mesh->load(fileName); setFem(mesh); } void Fem3DRepresentation::setFem(std::shared_ptr<Framework::Asset> mesh) { SURGSIM_ASSERT(!isInitialized()) << "The Fem cannot be set after initialization"; SURGSIM_ASSERT(mesh != nullptr) << "Mesh for Fem3DRepresentation cannot be a nullptr"; auto femMesh = std::dynamic_pointer_cast<Fem3D>(mesh); SURGSIM_ASSERT(femMesh != nullptr) << "Mesh for Fem3DRepresentation needs to be a SurgSim::Physics::Fem3D"; m_fem = femMesh; auto state = std::make_shared<Math::OdeState>(); state->setNumDof(getNumDofPerNode(), m_fem->getNumVertices()); for (size_t i = 0; i < m_fem->getNumVertices(); i++) { state->getPositions().segment<3>(getNumDofPerNode() * i) = m_fem->getVertexPosition(i); } for (auto boundaryCondition : m_fem->getBoundaryConditions()) { state->addBoundaryCondition(boundaryCondition); } // If we have elements, ensure that they are all of the same nature if (femMesh->getNumElements() > 0) { const auto& e0 = femMesh->getElement(0); for (auto const& e : femMesh->getElements()) { SURGSIM_ASSERT(e->nodeIds.size() == e0->nodeIds.size()) << "Cannot mix and match elements of different nature." << " Found an element with " << e->nodeIds.size() << " nodes but was expecting " << e0->nodeIds.size(); } // If the FemElement types hasn't been registered yet, let's set a default one if (getFemElementType().empty()) { if (e0->nodeIds.size() == 4) { Fem3DElementTetrahedron tetrahdron; setFemElementType(tetrahdron.getClassName()); } else if (e0->nodeIds.size() == 8) { Fem3DElementCube cube; setFemElementType(cube.getClassName()); } } } setInitialState(state); } std::shared_ptr<Fem3D> Fem3DRepresentation::getFem() const { return m_fem; } void Fem3DRepresentation::addExternalGeneralizedForce(std::shared_ptr<Localization> localization, const Math::Vector& generalizedForce, const Math::Matrix& K, const Math::Matrix& D) { using Math::SparseMatrix; const size_t dofPerNode = getNumDofPerNode(); const Eigen::Index expectedSize = static_cast<const Eigen::Index>(dofPerNode); SURGSIM_ASSERT(localization != nullptr) << "Invalid localization (nullptr)"; SURGSIM_ASSERT(generalizedForce.size() == expectedSize) << "Generalized force has an invalid size of " << generalizedForce.size() << ". Expected " << dofPerNode; SURGSIM_ASSERT(K.size() == 0 || (K.rows() == expectedSize && K.cols() == expectedSize)) << "Stiffness matrix K has an invalid size (" << K.rows() << "," << K.cols() << ") was expecting a square matrix of size " << dofPerNode; SURGSIM_ASSERT(D.size() == 0 || (D.rows() == expectedSize && D.cols() == expectedSize)) << "Damping matrix D has an invalid size (" << D.rows() << "," << D.cols() << ") was expecting a square matrix of size " << dofPerNode; std::shared_ptr<Fem3DLocalization> localization3D = std::dynamic_pointer_cast<Fem3DLocalization>(localization); SURGSIM_ASSERT(localization3D != nullptr) << "Invalid localization type (not a Fem3DLocalization)"; const size_t elementId = localization3D->getLocalPosition().index; const Math::Vector& coordinate = localization3D->getLocalPosition().coordinate; std::shared_ptr<FemElement> element = getFemElement(elementId); size_t index = 0; for (auto nodeId : element->getNodeIds()) { m_externalGeneralizedForce.segment(dofPerNode * nodeId, dofPerNode).noalias() += generalizedForce * coordinate[index]; index++; } if (K.size() != 0 || D.size() != 0) { size_t index1 = 0; for (auto nodeId1 : element->getNodeIds()) { size_t index2 = 0; for (auto nodeId2 : element->getNodeIds()) { if (K.size() != 0) { Math::addSubMatrix(coordinate[index1] * coordinate[index2] * K, static_cast<Eigen::Index>(nodeId1), static_cast<Eigen::Index>(nodeId2), &m_externalGeneralizedStiffness); } if (D.size() != 0) { Math::addSubMatrix(coordinate[index1] * coordinate[index2] * D, static_cast<Eigen::Index>(nodeId1), static_cast<Eigen::Index>(nodeId2), &m_externalGeneralizedDamping); } index2++; } index1++; } } m_externalGeneralizedStiffness.makeCompressed(); m_externalGeneralizedDamping.makeCompressed(); m_hasExternalGeneralizedForce = true; } std::unordered_map<size_t, size_t> Fem3DRepresentation::createTriangleIdToElementIdMap( std::shared_ptr<const Math::MeshShape> mesh) { std::unordered_map<size_t, size_t> result; // An Fem3DElementCube/Fem3DElementTetrahedron element has 8/4 nodes. // A triangle has 3 nodes. // If all the nodes of a triangle are present in a Fem3DElement*** node, then a row in the map is created. // The nodes are identified using their ids. // std::includes(...) is used to find whether a given list of triangle node ids are present in the supplied list // of femElement node ids. This function requires the lists of node ids to be sorted. // Get the list of fem elements with their node ids. std::vector<std::vector<size_t>> femElements; femElements.reserve(getNumFemElements()); for (size_t i = 0; i < getNumFemElements(); ++i) { auto elementNodeIds = getFemElement(i)->getNodeIds(); std::sort(elementNodeIds.begin(), elementNodeIds.end()); femElements.push_back(elementNodeIds); } std::array<size_t, 3> triangleSorted; auto doesIncludeTriangle = [&triangleSorted](const std::vector<size_t>& femElementSorted) { return std::includes(femElementSorted.begin(), femElementSorted.end(), triangleSorted.begin(), triangleSorted.end()); }; auto& meshTriangles = mesh->getTriangles(); for (auto triangle = meshTriangles.cbegin(); triangle != meshTriangles.cend(); ++triangle) { if (! triangle->isValid) { continue; } triangleSorted = triangle->verticesId; std::sort(triangleSorted.begin(), triangleSorted.end()); // Find the femElement that contains all the node ids of this triangle. std::vector<std::vector<size_t>>::iterator foundFemElement = std::find_if(femElements.begin(), femElements.end(), doesIncludeTriangle); // Assert to make sure that a triangle doesn't end up not having a femElement mapped to it. SURGSIM_ASSERT(foundFemElement != femElements.end()) << "A triangle in the given mesh of an Fem3DRepresentation does not have a corresponding" << " femElement."; // Add a row to the mapping (triangleId, elementId). // std::distance gives the index of the iterator within the container (by finding the distance // from the beginning of the container). result[std::distance(meshTriangles.begin(), triangle)] = std::distance(femElements.begin(), foundFemElement); } return result; } bool Fem3DRepresentation::doWakeUp() { if (!FemRepresentation::doWakeUp()) { return false; } auto deformableCollision = std::dynamic_pointer_cast<DeformableCollisionRepresentation>(m_collisionRepresentation); if (deformableCollision != nullptr) { auto mesh = std::dynamic_pointer_cast<Math::MeshShape>(deformableCollision->getShape()); m_triangleIdToElementIdMap = createTriangleIdToElementIdMap(mesh); } return true; } bool Fem3DRepresentation::doInitialize() { for (auto& element : m_fem->getElements()) { std::shared_ptr<FemElement> femElement; femElement = FemElement::getFactory().create(getFemElementType(), element); m_femElements.push_back(femElement); } return FemRepresentation::doInitialize(); } std::shared_ptr<Localization> Fem3DRepresentation::createNodeLocalization(size_t nodeId) { DataStructures::IndexedLocalCoordinate coordinate; SURGSIM_ASSERT(nodeId >= 0 && nodeId < getCurrentState()->getNumNodes()) << "Invalid node id"; // Look for any element that contains this node bool foundNodeId = false; for (size_t elementId = 0; elementId < getNumFemElements(); elementId++) { auto element = getFemElement(elementId); auto found = std::find(element->getNodeIds().begin(), element->getNodeIds().end(), nodeId); if (found != element->getNodeIds().end()) { coordinate.index = elementId; coordinate.coordinate.setZero(element->getNumNodes()); coordinate.coordinate[found - element->getNodeIds().begin()] = 1.0; foundNodeId = true; break; } } SURGSIM_ASSERT(foundNodeId) << "Could not find any element containing the node " << nodeId; // Fem3DLocalization will verify the coordinate (2nd parameter) based on // the Fem3DRepresentation passed as 1st parameter. return std::make_shared<Fem3DLocalization>( std::static_pointer_cast<Physics::Representation>(getSharedPtr()), coordinate); } std::shared_ptr<Localization> Fem3DRepresentation::createTriangleLocalization( const DataStructures::IndexedLocalCoordinate& location) { DataStructures::IndexedLocalCoordinate coordinate; size_t triangleId = location.index; const Math::Vector& triangleCoord = location.coordinate; auto deformableCollision = std::dynamic_pointer_cast<DeformableCollisionRepresentation>(m_collisionRepresentation); SURGSIM_ASSERT(deformableCollision != nullptr) << "Triangle localization cannot be created if the DeformableCollisionRepresentation is not correctly set."; // Find the vertex ids of the triangle. auto mesh = std::dynamic_pointer_cast<Math::MeshShape>(deformableCollision->getShape()); auto triangleVertices = mesh->getTriangle(triangleId).verticesId; // Find the vertex ids of the corresponding FemNode. // Get FemElement id from the triangle id. SURGSIM_ASSERT(m_triangleIdToElementIdMap.count(triangleId) == 1) << "Triangle must be mapped to an fem element."; size_t elementId = m_triangleIdToElementIdMap[triangleId]; std::shared_ptr<FemElement> element = getFemElement(elementId); auto elementVertices = element->getNodeIds(); // Find the mapping between triangleVertices and elementVertices. std::vector<size_t> indices; indices.reserve(elementVertices.size()); for (size_t i = 0; i < elementVertices.size(); ++i) { indices.push_back(3); for (int j = 0; j < 3; ++j) { if (triangleVertices[j] == elementVertices[i]) { indices[i] = j; break; } } } // Create the natural coordinate. Math::Vector4d barycentricCoordinate(triangleCoord[0], triangleCoord[1], triangleCoord[2], 0.0); coordinate.index = elementId; coordinate.coordinate.resize(elementVertices.size()); for (size_t i = 0; i < elementVertices.size(); ++i) { coordinate.coordinate[i] = barycentricCoordinate[indices[i]]; } // Fem3DLocalization will verify the coordinate (2nd parameter) based on // the Fem3DRepresentation passed as 1st parameter. return std::make_shared<Fem3DLocalization>( std::static_pointer_cast<Physics::Representation>(getSharedPtr()), coordinate); } std::shared_ptr<Localization> Fem3DRepresentation::createElementLocalization( const DataStructures::IndexedLocalCoordinate& location) { return std::make_shared<Fem3DLocalization>( std::static_pointer_cast<Physics::Representation>(getSharedPtr()), location); } std::shared_ptr<Localization> Fem3DRepresentation::createLocalization(const DataStructures::Location& location) { if (location.index.hasValue()) { return createNodeLocalization(*location.index); } else if (location.triangleMeshLocalCoordinate.hasValue()) { return createTriangleLocalization(*location.triangleMeshLocalCoordinate); } else if (location.elementMeshLocalCoordinate.hasValue()) { return createElementLocalization(*location.elementMeshLocalCoordinate); } SURGSIM_FAILURE() << "Localization cannot be created without a mesh-based location (node, triangle or element)."; return nullptr; } void Fem3DRepresentation::transformState(std::shared_ptr<Math::OdeState> state, const Math::RigidTransform3d& transform) { transformVectorByBlockOf3(transform, &state->getPositions()); transformVectorByBlockOf3(transform, &state->getVelocities(), true); } } // namespace Physics } // namespace SurgSim
35.553922
116
0.733283
[ "mesh", "vector", "transform" ]
abb4887f985f04f620215ad135574b8f8f2beca6
2,015
cpp
C++
apps/common/ospray_testing/transferFunction/Jet.cpp
burlen/ospray
e041b985dc53a2339a90a5735a22d0489b730df0
[ "Apache-2.0" ]
null
null
null
apps/common/ospray_testing/transferFunction/Jet.cpp
burlen/ospray
e041b985dc53a2339a90a5735a22d0489b730df0
[ "Apache-2.0" ]
null
null
null
apps/common/ospray_testing/transferFunction/Jet.cpp
burlen/ospray
e041b985dc53a2339a90a5735a22d0489b730df0
[ "Apache-2.0" ]
null
null
null
// ======================================================================== // // Copyright 2009-2019 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "TransferFunction.h" // stl #include <vector> // ospcommon #include "ospcommon/box.h" using namespace ospcommon; namespace ospray { namespace testing { struct Jet : public TransferFunction { Jet(); ~Jet() override = default; }; // Inlined definitions //////////////////////////////////////////////////// Jet::Jet() { colors.emplace_back(0 , 0, 0.562493); colors.emplace_back(0 , 0, 1 ); colors.emplace_back(0 , 1, 1 ); colors.emplace_back(0.500008, 1, 0.500008); colors.emplace_back(1 , 1, 0 ); colors.emplace_back(1 , 0, 0 ); colors.emplace_back(0.500008, 0, 0 ); } OSP_REGISTER_TESTING_TRANSFER_FUNCTION(Jet, jet); } // namespace testing } // namespace ospray
40.3
79
0.443672
[ "vector" ]
abb5e8a12e90a094a37385f1ca8d7357503c580e
7,080
cpp
C++
od/graphics/sampling/SliceList.cpp
bapch/er-301
e652eb9253009897747b0de7cfc57a27ac0cde1a
[ "MIT" ]
1
2021-06-29T19:26:35.000Z
2021-06-29T19:26:35.000Z
od/graphics/sampling/SliceList.cpp
bapch/er-301
e652eb9253009897747b0de7cfc57a27ac0cde1a
[ "MIT" ]
1
2021-04-28T07:54:41.000Z
2021-04-28T07:54:41.000Z
od/graphics/sampling/SliceList.cpp
bapch/er-301
e652eb9253009897747b0de7cfc57a27ac0cde1a
[ "MIT" ]
1
2021-03-02T21:32:52.000Z
2021-03-02T21:32:52.000Z
/* * SliceList.cpp * * Created on: 22 Oct 2016 * Author: clarkson */ #include <od/graphics/sampling/SliceList.h> #include <stdio.h> extern "C" { #include <od/graphics/fonts.h> } namespace od { SliceList::SliceList(int left, int bottom, int width, int height) : Graphic(left, bottom, width, height) { mHeightInLines = mHeight / mTextSize; mCursorState.orientation = cursorRight; } SliceList::~SliceList() { if (mpSlices) { mpSlices->release(); mpSlices = 0; } } void SliceList::setSlices(Slices *slices) { if (mpSlices != slices) { if (mpSlices) { mpSlices->release(); } mpSlices = slices; if (mpSlices) { mpSlices->attach(); } mSelectIndex = mTopIndex = 0; sync(); } } static void timeString(int i, float totalSecs, char *result, int n) { int hours = totalSecs / 3600; totalSecs -= hours * 3600; int mins = totalSecs / 60; totalSecs -= mins * 60; int secs = totalSecs; totalSecs -= secs; int ms = 1000 * totalSecs; snprintf(result, n, "%03d - %02d:%02d.%03d", i, mins, secs, ms); } void SliceList::draw(FrameBuffer &fb) { Graphic::draw(fb); int y; int left, bottom, right, top, textLeft; left = mWorldLeft; bottom = mWorldBottom; right = left + mWidth; top = bottom + mHeight; textLeft = left + mLeftMargin; if (fb.mIsMonoChrome) { // make room for selection triangle textLeft += 3; } if (mpSlices == 0 || mpSlices->size() == 0) { fb.text(mForeground, textLeft, bottom + mHeight / 2 + mTextSize / 2, "No slices."); return; } sync(); // draw selection if (mShowSelection) { int y0, y1; y0 = top - (mSelectIndex - mTopIndex + 1) * mTextSize; y1 = y0 + mTextSize - 1; mCursorState.x = left; mCursorState.y = (y0 + y1) / 2; if (mHasFocus) { if (fb.mIsMonoChrome) { fb.drawRightTriangle(WHITE, left, (y0 + y1) / 2, 5); } else { fb.fill(GRAY3, left + 2, y0, right - 4, y1); } } else { if (fb.mIsMonoChrome) { fb.box(WHITE, left, y0, left + 3, y1); } else { fb.box(GRAY3, left + 2, y0, right - 4, y1); } } } // render from the top and progress down until we leave the bounding box int i, j, n = (int)mpSlices->size(); char tmp[32]; for (i = mTopIndex, j = 0, y = top - mTextSize / 2; i < n && y >= bottom; i++, j++, y -= mTextSize) { float secs = mpSlices->getPositionInSeconds(i); timeString(i, secs, tmp, sizeof(tmp)); fb.text(mForeground, textLeft, y, tmp, mTextSize, ALIGN_MIDDLE); } // draw scroll bar float scrollSize, scrollPos; //scrollSize = (j - 1) / (float) mContents.size(); scrollSize = j / (float)n; scrollPos = mTopIndex / (float)n; int scroll0, scroll1; scroll0 = top - scrollPos * mHeight; scroll1 = scroll0 - scrollSize * mHeight; fb.line(mForeground, right - 2, scroll0, right - 2, scroll1); } void SliceList::scrollUp() { if (mpSlices == 0 || mpSlices->size() == 0) return; if (mSelectIndex > 0) { mSelectIndex--; if ((mSelectIndex - mTopIndex < mHeightInLines / 2) && (mTopIndex > 0)) { mTopIndex--; } } } void SliceList::scrollDown() { if (mpSlices == 0 || mpSlices->size() == 0) return; if (mSelectIndex + 1 < (int)mpSlices->size()) { mSelectIndex++; if ((mSelectIndex - mTopIndex >= mHeightInLines / 2) && (mTopIndex + mHeightInLines < (int)mpSlices->size())) { mTopIndex++; } } } void SliceList::scrollToBottom() { if (mpSlices == 0 || mpSlices->size() == 0) return; while (mSelectIndex + 1 < (int)mpSlices->size()) { scrollDown(); } } void SliceList::scrollToTop() { if (mpSlices == 0 || mpSlices->size() == 0) return; mSelectIndex = mTopIndex = 0; } // Make sure the selection is still valid in the case of changes in the Slices data. void SliceList::sync() { if (mpSlices) { if (mSelectIndex >= (int)(mpSlices->size())) { mSelectIndex = mTopIndex = 0; scrollToBottom(); } } } bool SliceList::encoder(int change, bool shifted, int threshold) { mEncoderSum += change; if (mEncoderSum > threshold) { mEncoderSum = 0; if (shifted) { scrollToBottom(); } else { scrollDown(); } return true; } else if (mEncoderSum < -threshold) { mEncoderSum = 0; if (shifted) { scrollToTop(); } else { scrollUp(); } return true; } return false; } uint32_t SliceList::getSelectedPosition() { if (mpSlices) { Slice *slice = mpSlices->get(mSelectIndex); if (slice) { return slice->mStart; } } return 0; } void SliceList::selectNearest(uint32_t position) { if (mpSlices) { SlicesIterator i = mpSlices->findNearest(position); if (i != mpSlices->end()) { mSelectIndex = (int)(i - mpSlices->begin()); if (mpSlices->size() < mHeightInLines) { mTopIndex = 0; } else { mTopIndex = MIN(mSelectIndex, mpSlices->size() - mHeightInLines); } } } } } /* namespace od */
25.745455
122
0.42161
[ "render" ]
abb76083468ae029e6094b62eb0a1271fd00e6b2
186
hpp
C++
approach_boost_code_generation/codegen_macro.hpp
noahleft/serialization
731ebcee68339960308a86b25cf3c11ba815043e
[ "MIT" ]
null
null
null
approach_boost_code_generation/codegen_macro.hpp
noahleft/serialization
731ebcee68339960308a86b25cf3c11ba815043e
[ "MIT" ]
null
null
null
approach_boost_code_generation/codegen_macro.hpp
noahleft/serialization
731ebcee68339960308a86b25cf3c11ba815043e
[ "MIT" ]
null
null
null
#ifndef CODEGEN_MACRO_HPP #define CODEGEN_MACRO_HPP #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/vector.hpp> #endif
31
42
0.833333
[ "vector" ]
abb90539e67ada120deb8335b36f1f373708ff53
92,307
cpp
C++
Source/NyxParticles.cpp
Gosenca/axionyx_1.0
7e2a723e00e6287717d6d81b23db32bcf6c3521a
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/NyxParticles.cpp
Gosenca/axionyx_1.0
7e2a723e00e6287717d6d81b23db32bcf6c3521a
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/NyxParticles.cpp
Gosenca/axionyx_1.0
7e2a723e00e6287717d6d81b23db32bcf6c3521a
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <iomanip> #include <Nyx.H> #ifdef GRAVITY #include <Gravity.H> #include <Gravity_F.H> //needed for get_grav_constant, but there might be a better way #endif #include <Nyx_F.H> #ifdef FDM #include "fdm_F.H" #endif using namespace amrex; namespace { bool virtual_particles_set = false; std::string ascii_particle_file; std::string binary_particle_file; std::string sph_particle_file; #ifdef AGN std::string agn_particle_file; #endif #ifdef NEUTRINO_PARTICLES std::string neutrino_particle_file; #endif #ifdef FDM std::string fdm_particle_file; #endif // const std::string chk_particle_file("DM"); const std::string dm_chk_particle_file("DM"); const std::string agn_chk_particle_file("AGN"); #ifdef FDM const std::string fdm_chk_particle_file("FDM"); #endif // // We want to call this routine when on exit to clean up particles. // // // Array of containers for all active particles // Vector<NyxParticleContainerBase*> ActiveParticles; // // Array of containers for all virtual particles // Vector<NyxParticleContainerBase*> VirtualParticles; // // Array of containers for all ghost particles // Vector<NyxParticleContainerBase*> GhostParticles; // // Containers for the real "active" Particles // DarkMatterParticleContainer* DMPC = 0; StellarParticleContainer* SPC = 0; #ifdef AGN AGNParticleContainer* APC = 0; #endif #ifdef NEUTRINO_PARTICLES #ifdef NEUTRINO_DARK_PARTICLES DarkMatterParticleContainer* NPC = 0; #else NeutrinoParticleContainer* NPC = 0; #endif #endif #ifdef FDM FDMwkbParticleContainer* FDMwkbPC = 0; FDMParticleContainer* FDMPC = 0; FDMphaseParticleContainer* FDMphasePC = 0; #endif // // This is only used as a temporary container for // reading in SPH particles and using them to // initialize the density and velocity field on the // grids. // DarkMatterParticleContainer* SPHPC = 0; // // Container for temporary, virtual Particles // DarkMatterParticleContainer* VirtPC = 0; StellarParticleContainer* VirtSPC = 0; #ifdef AGN AGNParticleContainer* VirtAPC = 0; #endif #ifdef NEUTRINO_PARTICLES #ifdef NEUTRINO_DARK_PARTICLES DarkMatterParticleContainer* VirtNPC = 0; #else NeutrinoParticleContainer* VirtNPC = 0; #endif #endif #ifdef FDM FDMwkbParticleContainer* VirtFDMwkbPC = 0; FDMParticleContainer* VirtFDMPC = 0; FDMphaseParticleContainer* VirtFDMphasePC = 0; #endif // // Container for temporary, ghost Particles // DarkMatterParticleContainer* GhostPC = 0; StellarParticleContainer* GhostSPC = 0; #ifdef AGN AGNParticleContainer* GhostAPC = 0; #endif #ifdef NEUTRINO_PARTICLES #ifdef NEUTRINO_DARK_PARTICLES DarkMatterParticleContainer* GhostNPC = 0; #else NeutrinoParticleContainer* GhostNPC = 0; #endif #endif #ifdef FDM FDMwkbParticleContainer* GhostFDMwkbPC = 0; FDMParticleContainer* GhostFDMPC = 0; FDMphaseParticleContainer* GhostFDMphasePC = 0; #endif void RemoveParticlesOnExit () { for (int i = 0; i < ActiveParticles.size(); i++) { delete ActiveParticles[i]; ActiveParticles[i] = 0; } for (int i = 0; i < GhostParticles.size(); i++) { delete GhostParticles[i]; GhostParticles[i] = 0; } for (int i = 0; i < VirtualParticles.size(); i++) { delete VirtualParticles[i]; VirtualParticles[i] = 0; } #ifdef FDM if(FDMwkbPC) delete FDMwkbPC; if(GhostFDMwkbPC) delete GhostFDMwkbPC; if(VirtFDMwkbPC) delete VirtFDMwkbPC; if(FDMPC) delete FDMPC; if(GhostFDMPC) delete GhostFDMPC; if(VirtFDMPC) delete VirtFDMPC; if(FDMphasePC) delete FDMphasePC; if(GhostFDMphasePC) delete GhostFDMphasePC; if(VirtFDMphasePC) delete VirtFDMphasePC; #endif } } bool Nyx::do_dm_particles = false; int Nyx::num_particle_ghosts = 1; int Nyx::particle_skip_factor = 1; std::string Nyx::particle_init_type = ""; std::string Nyx::particle_move_type = ""; // Allows us to output particles in the plotfile // in either single (IEEE32) or double (NATIVE) precision. // Particles are always written in double precision // in the checkpoint files. bool Nyx::particle_initrandom_serialize = false; Real Nyx::particle_initrandom_mass; long Nyx::particle_initrandom_count; long Nyx::particle_initrandom_count_per_box; int Nyx::particle_initrandom_iseed; int Nyx::particle_verbose = 1; int Nyx::write_particle_density_at_init = 0; int Nyx::write_coarsened_particles = 0; Real Nyx::particle_cfl = 0.5; #ifdef NEUTRINO_PARTICLES Real Nyx::neutrino_cfl = 0.5; #endif #ifdef FDM long Nyx::num_particle_fdm = 0; long Nyx::num_particle_dm = 0; #endif IntVect Nyx::Nrep; Vector<NyxParticleContainerBase*>& Nyx::theActiveParticles () { return ActiveParticles; } Vector<NyxParticleContainerBase*>& Nyx::theGhostParticles () { return GhostParticles; } Vector<NyxParticleContainerBase*>& Nyx::theVirtualParticles () { return VirtualParticles; } DarkMatterParticleContainer* Nyx::theDMPC () { return DMPC; } DarkMatterParticleContainer* Nyx::theVirtPC () { return VirtPC; } DarkMatterParticleContainer* Nyx::theGhostPC () { return GhostPC; } StellarParticleContainer* Nyx::theSPC () { return SPC; } StellarParticleContainer* Nyx::theVirtSPC () { return VirtSPC; } StellarParticleContainer* Nyx::theGhostSPC () { return GhostSPC; } #ifdef AGN AGNParticleContainer* Nyx::theAPC () { return APC; } AGNParticleContainer* Nyx::theVirtAPC () { return VirtAPC; } AGNParticleContainer* Nyx::theGhostAPC () { return GhostAPC; } #endif #ifdef NEUTRINO_PARTICLES #ifdef NEUTRINO_DARK_PARTICLES DarkMatterParticleContainer* Nyx::theNPC () { return NPC; } DarkMatterParticleContainer* Nyx::theVirtNPC () { return VirtNPC; } DarkMatterParticleContainer* Nyx::theGhostNPC () { return GhostNPC; } #else NeutrinoParticleContainer* Nyx::theNPC () { return NPC; } NeutrinoParticleContainer* Nyx::theVirtNPC () { return VirtNPC; } NeutrinoParticleContainer* Nyx::theGhostNPC () { return GhostNPC; } #endif #endif #ifdef FDM FDMParticleContainer* Nyx::theFDMPC () { return FDMPC; } FDMParticleContainer* Nyx::theVirtFDMPC () { return VirtFDMPC; } FDMParticleContainer* Nyx::theGhostFDMPC () { return GhostFDMPC; } FDMwkbParticleContainer* Nyx::theFDMwkbPC () { return FDMwkbPC; } FDMwkbParticleContainer* Nyx::theVirtFDMwkbPC () { return VirtFDMwkbPC; } FDMwkbParticleContainer* Nyx::theGhostFDMwkbPC () { return GhostFDMwkbPC; } FDMphaseParticleContainer* Nyx::theFDMphasePC () { return FDMphasePC; } FDMphaseParticleContainer* Nyx::theVirtFDMphasePC () { return VirtFDMphasePC; } FDMphaseParticleContainer* Nyx::theGhostFDMphasePC () { return GhostFDMphasePC; } #endif void Nyx::read_particle_params () { ParmParse pp("nyx"); pp.query("do_dm_particles", do_dm_particles); #ifdef FDM if(partlevel) //If Gaussian Beam Method is chosen for FDM evolution, we need dm_particles for the construction of the gravitational potential. do_dm_particles = 1; #endif #ifdef AGN pp.get("particle_init_type", particle_init_type); pp.get("particle_move_type", particle_move_type); #else if (do_dm_particles) { pp.get("particle_init_type", particle_init_type); pp.get("particle_move_type", particle_move_type); pp.query("init_with_sph_particles", init_with_sph_particles); } #endif #ifdef GRAVITY if (!do_grav && particle_move_type == "Gravitational") { if (ParallelDescriptor::IOProcessor()) std::cerr << "ERROR:: doesnt make sense to have do_grav=false but move_type = Gravitational" << std::endl; amrex::Error(); } #endif pp.query("particle_initrandom_serialize", particle_initrandom_serialize); pp.query("particle_initrandom_count", particle_initrandom_count); pp.query("particle_initrandom_count_per_box", particle_initrandom_count_per_box); pp.query("particle_initrandom_mass", particle_initrandom_mass); pp.query("particle_initrandom_iseed", particle_initrandom_iseed); pp.query("particle_skip_factor", particle_skip_factor); pp.query("ascii_particle_file", ascii_particle_file); // Input error check if (do_dm_particles && !ascii_particle_file.empty() && particle_init_type != "AsciiFile") { if (ParallelDescriptor::IOProcessor()) std::cerr << "ERROR::particle_init_type is not AsciiFile but you specified ascii_particle_file" << std::endl;; amrex::Error(); } pp.query("sph_particle_file", sph_particle_file); // Input error check if (init_with_sph_particles != 1 && !sph_particle_file.empty()) { if (ParallelDescriptor::IOProcessor()) std::cerr << "ERROR::init_with_sph_particles is not 1 but you specified sph_particle_file" << std::endl;; amrex::Error(); } // Input error check if (init_with_sph_particles == 1 && sph_particle_file.empty()) { if (ParallelDescriptor::IOProcessor()) std::cerr << "ERROR::init_with_sph_particles is 1 but you did not specify sph_particle_file" << std::endl;; amrex::Error(); } pp.query("binary_particle_file", binary_particle_file); // Input error check if (!binary_particle_file.empty() && (particle_init_type != "BinaryFile" && particle_init_type != "BinaryMetaFile" && particle_init_type != "BinaryMortonFile")) { if (ParallelDescriptor::IOProcessor()) std::cerr << "ERROR::particle_init_type is not BinaryFile, BinaryMetaFile, or BinaryMortonFile but you specified binary_particle_file" << std::endl; amrex::Error(); } #ifdef AGN pp.query("agn_particle_file", agn_particle_file); if (!agn_particle_file.empty() && particle_init_type != "AsciiFile") { if (ParallelDescriptor::IOProcessor()) std::cerr << "ERROR::particle_init_type is not AsciiFile but you specified agn_particle_file" << std::endl;; amrex::Error(); } #endif #ifdef NEUTRINO_PARTICLES pp.query("neutrino_particle_file", neutrino_particle_file); if (!neutrino_particle_file.empty() && (particle_init_type != "AsciiFile"&& particle_init_type != "BinaryMetaFile" && particle_init_type != "BinaryFile" )) { if (ParallelDescriptor::IOProcessor()) std::cerr << "ERROR::particle_init_type is not AsciiFile or BinaryFile but you specified neutrino_particle_file" << std::endl;; amrex::Error(); } #endif #ifdef FDM // pp.get("num_particle_dm", num_particle_dm); if(partlevel){ pp.get("num_particle_fdm", num_particle_fdm); pp.get("num_particle_dm", num_particle_dm); } #endif pp.query("write_particle_density_at_init", write_particle_density_at_init); pp.query("write_coarsened_particles", write_coarsened_particles); // // Control the verbosity of the Particle class // ParmParse ppp("particles"); ppp.query("v", particle_verbose); for (int i = 0; i < BL_SPACEDIM; i++) Nrep[i] = 1; // Initialize to one (no replication) ppp.query("replicate",Nrep); // // Set the cfl for particle motion (fraction of cell that a particle can // move in a timestep). // ppp.query("cfl", particle_cfl); #ifdef NEUTRINO_PARTICLES ppp.query("neutrino_cfl", neutrino_cfl); #endif } void Nyx::init_particles () { BL_PROFILE("Nyx::init_particles()"); if (level > 0) return; #ifdef FDM const Real a = get_comoving_a(state[Axion_Type].curTime()); #endif // // Need to initialize particles before defining gravity. // if (do_dm_particles) { BL_ASSERT (DMPC == 0); DMPC = new DarkMatterParticleContainer(parent); ActiveParticles.push_back(DMPC); if (init_with_sph_particles == 1) SPHPC = new DarkMatterParticleContainer(parent); #ifndef FDM if (parent->subCycle()) #endif { VirtPC = new DarkMatterParticleContainer(parent); VirtualParticles.push_back(VirtPC); GhostPC = new DarkMatterParticleContainer(parent); GhostParticles.push_back(GhostPC); } // // Make sure to call RemoveParticlesOnExit() on exit. // amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // DMPC->SetVerbose(particle_verbose); DarkMatterParticleContainer::ParticleInitData pdata = {particle_initrandom_mass}; if (particle_init_type == "Random") { if (particle_initrandom_count <= 0) { amrex::Abort("Nyx::init_particles(): particle_initrandom_count must be > 0"); } if (particle_initrandom_iseed <= 0) { amrex::Abort("Nyx::init_particles(): particle_initrandom_iseed must be > 0"); } if (verbose) { amrex::Print() << "\nInitializing DM with cloud of " << particle_initrandom_count << " random particles with initial seed: " << particle_initrandom_iseed << "\n\n"; } DMPC->InitRandom(particle_initrandom_count, particle_initrandom_iseed, pdata, particle_initrandom_serialize); } else if (particle_init_type == "RandomPerBox") { if (particle_initrandom_count_per_box <= 0) { amrex::Abort("Nyx::init_particles(): particle_initrandom_count_per_box must be > 0"); } if (particle_initrandom_iseed <= 0) { amrex::Abort("Nyx::init_particles(): particle_initrandom_iseed must be > 0"); } if (verbose) amrex::Print() << "\nInitializing DM with of " << particle_initrandom_count_per_box << " random particles per box with initial seed: " << particle_initrandom_iseed << "\n\n"; DMPC->InitRandomPerBox(particle_initrandom_count_per_box, particle_initrandom_iseed, pdata); } else if (particle_init_type == "RandomPerCell") { if (verbose) amrex::Print() << "\nInitializing DM with 1 random particle per cell " << "\n"; int n_per_cell = 1; DMPC->InitNRandomPerCell(n_per_cell, pdata); } else if (particle_init_type == "AsciiFile") { if (verbose) { amrex::Print() << "\nInitializing DM particles from \"" << ascii_particle_file << "\" ...\n\n"; if (init_with_sph_particles == 1) amrex::Print() << "\nInitializing SPH particles from ascii \"" << sph_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. // DMPC->InitFromAsciiFile(ascii_particle_file, BL_SPACEDIM + 1, &Nrep); if (init_with_sph_particles == 1) SPHPC->InitFromAsciiFile(ascii_particle_file, BL_SPACEDIM + 1, &Nrep); } else if (particle_init_type == "BinaryFile") { if (verbose) { amrex::Print() << "\nInitializing DM particles from \"" << binary_particle_file << "\" ...\n\n"; if (init_with_sph_particles == 1) amrex::Print() << "\nInitializing SPH particles from binary \"" << sph_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. // DMPC->InitFromBinaryFile(binary_particle_file, BL_SPACEDIM + 1); if (init_with_sph_particles == 1) SPHPC->InitFromBinaryFile(ascii_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMetaFile") { if (verbose) { amrex::Print() << "\nInitializing DM particles from meta file\"" << binary_particle_file << "\" ...\n\n"; if (init_with_sph_particles == 1) amrex::Print() << "\nInitializing SPH particles from meta file\"" << sph_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. // DMPC->InitFromBinaryMetaFile(binary_particle_file, BL_SPACEDIM + 1); if (init_with_sph_particles == 1) SPHPC->InitFromBinaryMetaFile(sph_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMortonFile") { if (verbose) { amrex::Print() << "\nInitializing DM particles from morton-ordered binary file\"" << binary_particle_file << "\" ...\n\n"; if (init_with_sph_particles == 1) amrex::Error("Morton-ordered input is not supported for sph particles."); } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. // DMPC->InitFromBinaryMortonFile(binary_particle_file, BL_SPACEDIM + 1, particle_skip_factor); } else if (particle_init_type == "Cosmological") { // moved to Nyx_initcosmo.cpp } #ifdef FDM else if (particle_init_type == "GaussianBeams")// && partlevel) { if (verbose) { amrex::Print() << "\nInitializing DM particles for FDM gravitational potential...\n\n"; if (init_with_sph_particles == 1) amrex::Error("FDM computations are not supported for sph particles."); } if(num_particle_dm > 0) DMPC->InitGaussianBeams(num_particle_dm, level, parent->initialBaLevels()+1, meandens, alpha_fdm, a); // else // amrex::Error("\nNeed num_particle_dm > 0 for DM InitGaussianBeams!\n\n"); } else if (particle_init_type == "SphericalCollapse")// && partlevel) { if (verbose) { amrex::Print() << "\nInitializing DM particles for mixed FDM/CDM spherical collaps...\n\n"; if (init_with_sph_particles == 1) amrex::Error("FDM computations are not supported for sph particles."); } DMPC->InitSphericalCollapse(get_level(level).get_new_data(Axion_Type), level, parent->initialBaLevels()+1,Nyx::AxDens,ratio_fdm); } #endif else { amrex::Error("not a valid input for nyx.particle_init_type"); } if (write_coarsened_particles) { DMPC->WriteCoarsenedAsciiFile("coarse_particle_file.ascii"); exit(0); } } #ifdef AGN { // Note that we don't initialize any actual AGN particles here, we just create the container. BL_ASSERT (APC == 0); APC = new AGNParticleContainer(parent, num_particle_ghosts); ActiveParticles.push_back(APC); if (parent->subCycle()) { VirtAPC = new AGNParticleContainer(parent, num_particle_ghosts); VirtualParticles.push_back(VirtAPC); GhostAPC = new AGNParticleContainer(parent, num_particle_ghosts); GhostParticles.push_back(GhostAPC); } // // 2 gives more stuff than 1. // APC->SetVerbose(particle_verbose); } #endif #ifdef NEUTRINO_PARTICLES { BL_ASSERT (NPC == 0); #ifdef NEUTRINO_DARK_PARTICLES NPC = new DarkMatterParticleContainer(parent); ActiveParticles.push_back(NPC); #else NPC = new NeutrinoParticleContainer(parent); ActiveParticles.push_back(NPC); // Set the relativistic flag to 1 so that the density will be gamma-weighted // when returned by AssignDensity calls. NPC->SetRelativistic(1); // We must set the value for csquared which is used in computing gamma = 1 / sqrt(1-vsq/csq) // Obviously this value is just a place-holder for now. NPC->SetCSquared(1.); #endif if (parent->subCycle()) { #ifdef NEUTRINO_DARK_PARTICLES VirtNPC = new DarkMatterParticleContainer(parent); VirtualParticles.push_back(VirtNPC); #else VirtNPC = new NeutrinoParticleContainer(parent); VirtualParticles.push_back(VirtNPC); // Set the relativistic flag to 1 so that the density will be gamma-weighted // when returned by AssignDensity calls. VirtNPC->SetRelativistic(1); #endif #ifdef NEUTRINO_DARK_PARTICLES GhostNPC = new DarkMatterParticleContainer(parent); GhostParticles.push_back(GhostNPC); #else GhostNPC = new NeutrinoParticleContainer(parent); GhostParticles.push_back(GhostNPC); // Set the relativistic flag to 1 so that the density will be gamma-weighted // when returned by AssignDensity calls. GhostNPC->SetRelativistic(1); #endif } // // Make sure to call RemoveParticlesOnExit() on exit. // (if do_dm_particles then we have already called ExecOnFinalize) // if (!do_dm_particles) amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // NPC->SetVerbose(particle_verbose); if (particle_init_type == "AsciiFile") { if (verbose) amrex::Print() << "\nInitializing Neutrino particles from \"" << neutrino_particle_file << "\" ...\n\n"; // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass, velocity and angles. // #ifdef NEUTRINO_DARK_PARTICLES NPC->InitFromAsciiFile(neutrino_particle_file, BL_SPACEDIM + 1, &Nrep); #else NPC->InitFromAsciiFile(neutrino_particle_file, 2*BL_SPACEDIM + 1, &Nrep); #endif } else if (particle_init_type == "BinaryFile") { if (verbose) { amrex::Print() << "\nInitializing Neutrino particles from \"" << neutrino_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. // NPC->InitFromBinaryFile(neutrino_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMetaFile") { if (verbose) { amrex::Print() << "\nInitializing NPC particles from meta file\"" << neutrino_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. // NPC->InitFromBinaryMetaFile(neutrino_particle_file, BL_SPACEDIM + 1); } else { amrex::Error("for right now we only init Neutrino particles with ascii or binary"); } } if (write_particle_density_at_init == 1) { Vector<std::unique_ptr<MultiFab> > particle_mf;//(new MultiFab(grids,dmap,1,1)); DMPC->AssignDensity(particle_mf,0,1,0,4); writeMultiFabAsPlotFile("ParticleDensity", *particle_mf[0], "density"); #ifdef NEUTRINO_PARTICLES Vector<std::unique_ptr<MultiFab> > particle_npc_mf;//(new MultiFab(grids,dmap,1,1)); // DMPC->AssignDensitySingleLevel(particle_mf,0,1,0,0); NPC->AssignDensity(particle_npc_mf,0,1,0,0); writeMultiFabAsPlotFile("ParticleNPCDensity", *particle_npc_mf[0], "density"); #endif exit(0); } #endif #ifdef FDM if(partlevel){ // if(false){ if(wkb_approx) { BL_ASSERT (FDMwkbPC == 0); FDMwkbPC = new FDMwkbParticleContainer(parent); // if (parent->subCycle()) { VirtFDMwkbPC = new FDMwkbParticleContainer(parent); GhostFDMwkbPC = new FDMwkbParticleContainer(parent); } // // Make sure to call RemoveParticlesOnExit() on exit. // (if do_dm_particles then we have already called ExecOnFinalize) // if (!do_dm_particles) amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // FDMwkbPC->SetVerbose(particle_verbose); if (particle_init_type == "AsciiFile") { if (verbose && ParallelDescriptor::IOProcessor()) { amrex::Print() << "\nInitializing FDM particles from \"" << ascii_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. This might have to be extended to all Gauss // Beam arguments. FDMwkbPC->InitFromAsciiFile(ascii_particle_file, BL_SPACEDIM + 1, &Nrep); } else if (particle_init_type == "BinaryFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from \"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. This might have to be extended to all Gauss // Beam arguments. FDMwkbPC->InitFromBinaryFile(binary_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMetaFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from meta file\"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. This might // have to be extended to all Gauss Beam arguments. FDMwkbPC->InitFromBinaryMetaFile(binary_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMortonFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from morton-ordered binary file\"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. This might // have to be extended to all Gauss Beam arguments. FDMwkbPC->InitFromBinaryMortonFile(binary_particle_file, BL_SPACEDIM + 1, particle_skip_factor); } else if (particle_init_type == "Cosmological") { // moved to Nyx_initcosmo.cpp } //do init // else if(particle_init_type == "Bosonstar") // { // const int initDataDim = 4; //FIXME: depends on setup... I guess // const Real * dx = geom.CellSize(); // const Real cur_time = state[State_Type].curTime(); // MultiFab InitData(grids,dmap,initDataDim,0); // for (MFIter mfi(InitData); mfi.isValid(); ++mfi) // { // RealBox gridloc = RealBox(grids[mfi.index()], geom.CellSize(), geom.ProbLo()); // const Box& box = mfi.validbox(); // const int* lo = box.loVect(); // const int* hi = box.hiVect(); // // BL_FORT_PROC_CALL(INITPART, initpart) // initpart(&level, &cur_time, // lo, hi, // &initDataDim, BL_TO_FORTRAN(InitData[mfi]), // dx, gridloc.lo(), gridloc.hi()); // } // BoxArray baWhereNot; // if (level < parent->initialBaLevels()) // baWhereNot = parent->initialBa(level+1); // BoxArray myBaWhereNot(baWhereNot.size()); // for (int i=0; i < baWhereNot.size(); i++) // myBaWhereNot.set(i, baWhereNot[i]); // if (level < parent->initialBaLevels()) // myBaWhereNot.coarsen(parent->refRatio(level)); // if(num_particle_fdm > 0) // FDMwkbPC->InitVarCount(InitData, num_particle_fdm, myBaWhereNot, level, parent->initialBaLevels()+1); // else // amrex::Error("\nNeed num_particle_fdm > 0 for InitVarCount!\n\n"); // } else if(particle_init_type == "GaussianBeams") { if (!do_dm_particles) amrex::Print() << "\n DM particles are needed for the construction of the gravitational potential!!\n\n"; if(num_particle_fdm > 0) FDMwkbPC->InitGaussianBeams(num_particle_fdm, level, parent->initialBaLevels()+1, hbaroverm, sigma_fdm, gamma_fdm, meandens, alpha_fdm, a); // else // amrex::Error("\nNeed num_particle_fdm > 0 for InitGaussianBeams!\n\n"); MultiFab& Ax_new = get_level(level).get_new_data(Axion_Type); Ax_new.setVal(0.); // if(levelmethod[level]==GBlevel){ // //Define neccessary number of ghost cells // int ng = ceil(Nyx::sigma_fdm*Nyx::theta_fdm/get_level(level).Geom().CellSize()[0]); // //Initialize MultiFabs // MultiFab fdmreal(Ax_new.boxArray(), Ax_new.DistributionMap(), 1, ng); // fdmreal.setVal(0.); // MultiFab fdmimag(Ax_new.boxArray(), Ax_new.DistributionMap(), 1, ng); // fdmimag.setVal(0.); // const Real cur_time = state[State_Type].curTime(); // const Real a_new = get_comoving_a(cur_time); // //Deposit Gaussian Beams // if(Nyx::theFDMPC()) // Nyx::theFDMPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theGhostFDMPC()) // Nyx::theGhostFDMPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theVirtFDMPC()) // Nyx::theVirtFDMPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theFDMwkbPC()) // Nyx::theFDMwkbPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theGhostFDMwkbPC()) // Nyx::theGhostFDMwkbPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theVirtFDMwkbPC()) // Nyx::theVirtFDMwkbPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // //Update real part in FDM state // Ax_new.ParallelCopy(fdmreal, 0, Nyx::AxRe, 1, fdmreal.nGrow(), // Ax_new.nGrow(), parent->Geom(level).periodicity(),FabArrayBase::ADD); // //Update imaginary part in FDM state // Ax_new.ParallelCopy(fdmimag, 0, Nyx::AxIm, 1, fdmimag.nGrow(), // Ax_new.nGrow(), parent->Geom(level).periodicity(),FabArrayBase::ADD); // //Update density in FDM state // AmrLevel* amrlev = &parent->getLevel(level); // for (amrex::FillPatchIterator fpi(*amrlev,Ax_new); fpi.isValid(); ++fpi) // { // if (Ax_new[fpi].contains_nan()) // amrex::Abort("Nans in state just before FDM density update"); // BL_FORT_PROC_CALL(FORT_FDM_FIELDS, fort_fdm_fields) // (BL_TO_FORTRAN(Ax_new[fpi])); // if (Ax_new[fpi].contains_nan()) // amrex::Abort("Nans in state just after FDM density update"); // } // } } else { //FIXME std::cout << "multilevel init not implemented, yet!" << std::endl; } }else if(phase_approx) { BL_ASSERT (FDMphasePC == 0); FDMphasePC = new FDMphaseParticleContainer(parent); // if (parent->subCycle()) { VirtFDMphasePC = new FDMphaseParticleContainer(parent); GhostFDMphasePC = new FDMphaseParticleContainer(parent); } // // Make sure to call RemoveParticlesOnExit() on exit. // (if do_dm_particles then we have already called ExecOnFinalize) // if (!do_dm_particles) amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // FDMphasePC->SetVerbose(particle_verbose); if (particle_init_type == "AsciiFile") { if (verbose && ParallelDescriptor::IOProcessor()) { amrex::Print() << "\nInitializing FDM particles from \"" << ascii_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. This might have to be extended to all Gauss // Beam arguments. FDMphasePC->InitFromAsciiFile(ascii_particle_file, BL_SPACEDIM + 1, &Nrep); } else if (particle_init_type == "BinaryFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from \"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. This might have to be extended to all Gauss // Beam arguments. FDMphasePC->InitFromBinaryFile(binary_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMetaFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from meta file\"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. This might // have to be extended to all Gauss Beam arguments. FDMphasePC->InitFromBinaryMetaFile(binary_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMortonFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from morton-ordered binary file\"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. This might // have to be extended to all Gauss Beam arguments. FDMphasePC->InitFromBinaryMortonFile(binary_particle_file, BL_SPACEDIM + 1, particle_skip_factor); } else if (particle_init_type == "Cosmological") { // moved to Nyx_initcosmo.cpp } //do init // else if(particle_init_type == "Bosonstar") // { // const int initDataDim = 4; //FIXME: depends on setup... I guess // const Real * dx = geom.CellSize(); // const Real cur_time = state[State_Type].curTime(); // MultiFab InitData(grids,dmap,initDataDim,0); // for (MFIter mfi(InitData); mfi.isValid(); ++mfi) // { // RealBox gridloc = RealBox(grids[mfi.index()], geom.CellSize(), geom.ProbLo()); // const Box& box = mfi.validbox(); // const int* lo = box.loVect(); // const int* hi = box.hiVect(); // // BL_FORT_PROC_CALL(INITPART, initpart) // initpart(&level, &cur_time, // lo, hi, // &initDataDim, BL_TO_FORTRAN(InitData[mfi]), // dx, gridloc.lo(), gridloc.hi()); // } // BoxArray baWhereNot; // if (level < parent->initialBaLevels()) // baWhereNot = parent->initialBa(level+1); // BoxArray myBaWhereNot(baWhereNot.size()); // for (int i=0; i < baWhereNot.size(); i++) // myBaWhereNot.set(i, baWhereNot[i]); // if (level < parent->initialBaLevels()) // myBaWhereNot.coarsen(parent->refRatio(level)); // if(num_particle_fdm > 0) // FDMphasePC->InitVarCount(InitData, num_particle_fdm, myBaWhereNot, level, parent->initialBaLevels()+1); // else // amrex::Error("\nNeed num_particle_fdm > 0 for InitVarCount!\n\n"); // } else { //FIXME std::cout << "multilevel init not implemented, yet!" << std::endl; } }else{ BL_ASSERT (FDMPC == 0); FDMPC = new FDMParticleContainer(parent); // if (parent->subCycle()) { VirtFDMPC = new FDMParticleContainer(parent); GhostFDMPC = new FDMParticleContainer(parent); } // // Make sure to call RemoveParticlesOnExit() on exit. // (if do_dm_particles then we have already called ExecOnFinalize) // if (!do_dm_particles) amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // FDMPC->SetVerbose(particle_verbose); if (particle_init_type == "AsciiFile") { if (verbose && ParallelDescriptor::IOProcessor()) { amrex::Print() << "\nInitializing FDM particles from \"" << ascii_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. This might have to be extended to all Gauss // Beam arguments. FDMPC->InitFromAsciiFile(ascii_particle_file, BL_SPACEDIM + 1, &Nrep); } else if (particle_init_type == "BinaryFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from \"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]`. Here we're reading in the particle // mass and velocity. This might have to be extended to all Gauss // Beam arguments. FDMPC->InitFromBinaryFile(binary_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMetaFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from meta file\"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. This might // have to be extended to all Gauss Beam arguments. FDMPC->InitFromBinaryMetaFile(binary_particle_file, BL_SPACEDIM + 1); } else if (particle_init_type == "BinaryMortonFile") { if (verbose) { amrex::Print() << "\nInitializing FDM particles from morton-ordered binary file\"" << binary_particle_file << "\" ...\n\n"; } // // The second argument is how many Reals we read into `m_data[]` // after reading in `m_pos[]` in each of the binary particle files. // Here we're reading in the particle mass and velocity. This might // have to be extended to all Gauss Beam arguments. FDMPC->InitFromBinaryMortonFile(binary_particle_file, BL_SPACEDIM + 1, particle_skip_factor); } else if (particle_init_type == "Cosmological") { // moved to Nyx_initcosmo.cpp } //do init // else if(particle_init_type == "Bosonstar") // { // const int initDataDim = 4; //FIXME: depends on setup... I guess // const Real * dx = geom.CellSize(); // const Real cur_time = state[State_Type].curTime(); // MultiFab InitData(grids,dmap,initDataDim,0); // for (MFIter mfi(InitData); mfi.isValid(); ++mfi) // { // RealBox gridloc = RealBox(grids[mfi.index()], geom.CellSize(), geom.ProbLo()); // const Box& box = mfi.validbox(); // const int* lo = box.loVect(); // const int* hi = box.hiVect(); // // BL_FORT_PROC_CALL(INITPART, initpart) // initpart(&level, &cur_time, // lo, hi, // &initDataDim, BL_TO_FORTRAN(InitData[mfi]), // dx, gridloc.lo(), gridloc.hi()); // } // BoxArray baWhereNot; // if (level < parent->initialBaLevels()) // baWhereNot = parent->initialBa(level+1); // BoxArray myBaWhereNot(baWhereNot.size()); // for (int i=0; i < baWhereNot.size(); i++) // myBaWhereNot.set(i, baWhereNot[i]); // if (level < parent->initialBaLevels()) // myBaWhereNot.coarsen(parent->refRatio(level)); // if(num_particle_fdm > 0) // FDMPC->InitVarCount(InitData, num_particle_fdm, myBaWhereNot, level, parent->initialBaLevels()+1); // else // amrex::Error("\nNeed num_particle_fdm > 0 for InitVarCount!\n\n"); // } else if(particle_init_type == "GaussianBeams") { if (!do_dm_particles) amrex::Print() << "\n DM particles are needed for the construction of the gravitational potential!!\n\n"; if(num_particle_fdm > 0) FDMPC->InitGaussianBeams(num_particle_fdm, level, parent->initialBaLevels()+1, hbaroverm, sigma_fdm, gamma_fdm, meandens, alpha_fdm, a); // else // amrex::Error("\nNeed num_particle_fdm > 0 for InitGaussianBeams!\n\n"); MultiFab& Ax_new = get_level(level).get_new_data(Axion_Type); Ax_new.setVal(0.); // if(levelmethod[level]==GBlevel){ // //Define neccessary number of ghost cells // int ng = ceil(Nyx::sigma_fdm*Nyx::theta_fdm/get_level(level).Geom().CellSize()[0]); // //Initialize MultiFabs // MultiFab fdmreal(Ax_new.boxArray(), Ax_new.DistributionMap(), 1, ng); // fdmreal.setVal(0.); // MultiFab fdmimag(Ax_new.boxArray(), Ax_new.DistributionMap(), 1, ng); // fdmimag.setVal(0.); // const Real cur_time = state[State_Type].curTime(); // const Real a_new = get_comoving_a(cur_time); // //Deposit Gaussian Beams // if(Nyx::theFDMPC()) // Nyx::theFDMPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theGhostFDMPC()) // Nyx::theGhostFDMPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theVirtFDMPC()) // Nyx::theVirtFDMPC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theFDMphasePC()) // Nyx::theFDMphasePC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theGhostFDMphasePC()) // Nyx::theGhostFDMphasePC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // if(Nyx::theVirtFDMphasePC()) // Nyx::theVirtFDMphasePC()->DepositFDMParticles(fdmreal,fdmimag,level,a_new); // //Update real part in FDM state // Ax_new.ParallelCopy(fdmreal, 0, Nyx::AxRe, 1, fdmreal.nGrow(), // Ax_new.nGrow(), parent->Geom(level).periodicity(),FabArrayBase::ADD); // //Update imaginary part in FDM state // Ax_new.ParallelCopy(fdmimag, 0, Nyx::AxIm, 1, fdmimag.nGrow(), // Ax_new.nGrow(), parent->Geom(level).periodicity(),FabArrayBase::ADD); // //Update density in FDM state // AmrLevel* amrlev = &parent->getLevel(level); // for (amrex::FillPatchIterator fpi(*amrlev,Ax_new); fpi.isValid(); ++fpi) // { // if (Ax_new[fpi].contains_nan()) // amrex::Abort("Nans in state just before FDM density update"); // BL_FORT_PROC_CALL(FORT_FDM_FIELDS, fort_fdm_fields) // (BL_TO_FORTRAN(Ax_new[fpi])); // if (Ax_new[fpi].contains_nan()) // amrex::Abort("Nans in state just after FDM density update"); // } // } } else { //FIXME std::cout << "multilevel init not implemented, yet!" << std::endl; } } } #endif } #ifdef GRAVITY #ifndef NO_HYDRO void Nyx::init_santa_barbara (int init_sb_vels) { BL_PROFILE("Nyx::init_santa_barbara()"); Real cur_time = state[State_Type].curTime(); Real a = old_a; amrex::Print() << "... time and comoving a when data is initialized at level " << level << " " << cur_time << " " << a << '\n'; if (level == 0) { Real frac_for_hydro = comoving_OmB / comoving_OmM; Real omfrac = 1.0 - frac_for_hydro; if ( (init_with_sph_particles == 0) && (frac_for_hydro != 1.0) ) { DMPC->MultiplyParticleMass(level, omfrac); } Vector<std::unique_ptr<MultiFab> > particle_mf(1); if (init_sb_vels == 1) { if (init_with_sph_particles == 1) { SPHPC->AssignDensityAndVels(particle_mf); } else { DMPC->AssignDensityAndVels(particle_mf); } } else { if (init_with_sph_particles == 1) { SPHPC->AssignDensity(particle_mf); } else { DMPC->AssignDensity(particle_mf); } } // As soon as we have used the SPH particles to define the density // and velocity on the grid, we can go ahead and destroy them. if (init_with_sph_particles == 1) { delete SPHPC; } for (int lev = parent->finestLevel()-1; lev >= 0; lev--) { amrex::average_down(*particle_mf[lev+1], *particle_mf[lev], parent->Geom(lev+1), parent->Geom(lev), 0, 1, parent->refRatio(lev)); } // Only multiply the density, not the velocities if (init_with_sph_particles == 0) { if (frac_for_hydro == 1.0) { particle_mf[level]->mult(0,0,1); } else { particle_mf[level]->mult(frac_for_hydro / omfrac,0,1); } } const Real * dx = geom.CellSize(); MultiFab& S_new = get_new_data(State_Type); MultiFab& D_new = get_new_data(DiagEOS_Type); #ifdef FDM MultiFab& Ax_new = get_new_data(Axion_Type); int na = Ax_new.nComp(); #endif int ns = S_new.nComp(); int nd = D_new.nComp(); for (MFIter mfi(S_new); mfi.isValid(); ++mfi) { RealBox gridloc = RealBox(grids[mfi.index()], geom.CellSize(), geom.ProbLo()); const Box& box = mfi.validbox(); const int* lo = box.loVect(); const int* hi = box.hiVect(); // Temp unused for GammaLaw, set it here so that pltfiles have // defined numbers D_new[mfi].setVal(0, Temp_comp); D_new[mfi].setVal(0, Ne_comp); fort_initdata (level, cur_time, lo, hi, ns,BL_TO_FORTRAN(S_new[mfi]), #ifdef FDM na, BL_TO_FORTRAN(Ax_new[mfi]), #endif nd,BL_TO_FORTRAN(D_new[mfi]), dx, gridloc.lo(), gridloc.hi(), geom.Domain().loVect(), geom.Domain().hiVect()); } if (inhomo_reion) init_zhi(); // Add the particle density to the gas density MultiFab::Add(S_new, *particle_mf[level], 0, Density, 1, S_new.nGrow()); if (init_sb_vels == 1) { // Convert velocity to momentum for (int i = 0; i < BL_SPACEDIM; ++i) { MultiFab::Multiply(*particle_mf[level], *particle_mf[level], 0, 1+i, 1, 0); } // Add the particle momenta to the gas momenta (initially zero) MultiFab::Add(S_new, *particle_mf[level], 1, Xmom, BL_SPACEDIM, S_new.nGrow()); } } else { MultiFab& S_new = get_new_data(State_Type); FillCoarsePatch(S_new, 0, cur_time, State_Type, 0, S_new.nComp()); MultiFab& D_new = get_new_data(DiagEOS_Type); FillCoarsePatch(D_new, 0, cur_time, DiagEOS_Type, 0, D_new.nComp()); MultiFab& Phi_new = get_new_data(PhiGrav_Type); FillCoarsePatch(Phi_new, 0, cur_time, PhiGrav_Type, 0, Phi_new.nComp()); // Convert (rho X)_i to X_i before calling init_e_from_T if (use_const_species == 0) { for (int i = 0; i < NumSpec; ++i) { MultiFab::Divide(S_new, S_new, Density, FirstSpec+i, 1, 0); } } } // Make sure we've finished initializing the density before calling this. MultiFab& S_new = get_new_data(State_Type); MultiFab& D_new = get_new_data(DiagEOS_Type); int ns = S_new.nComp(); int nd = D_new.nComp(); #ifdef _OPENMP #pragma omp parallel #endif for (MFIter mfi(S_new,true); mfi.isValid(); ++mfi) { const Box& box = mfi.tilebox(); const int* lo = box.loVect(); const int* hi = box.hiVect(); fort_init_e_from_t (BL_TO_FORTRAN(S_new[mfi]), &ns, BL_TO_FORTRAN(D_new[mfi]), &nd, lo, hi, &a); } // Convert X_i to (rho X)_i if (use_const_species == 0) { for (int i = 0; i < NumSpec; ++i) { MultiFab::Multiply(S_new, S_new, Density, FirstSpec+i, 1, 0); } } } #endif #endif void Nyx::particle_post_restart (const std::string& restart_file, bool is_checkpoint) { BL_PROFILE("Nyx::particle_post_restart()"); if (level > 0) return; if (do_dm_particles) { BL_ASSERT(DMPC == 0); DMPC = new DarkMatterParticleContainer(parent); ActiveParticles.push_back(DMPC); #ifndef FDM if (parent->subCycle()) #endif { VirtPC = new DarkMatterParticleContainer(parent); VirtualParticles.push_back(VirtPC); GhostPC = new DarkMatterParticleContainer(parent); GhostParticles.push_back(GhostPC); } // // Make sure to call RemoveParticlesOnExit() on exit. // amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // DMPC->SetVerbose(particle_verbose); DMPC->Restart(restart_file, dm_chk_particle_file, is_checkpoint); // // We want the ability to write the particles out to an ascii file. // ParmParse pp("particles"); std::string dm_particle_output_file; pp.query("dm_particle_output_file", dm_particle_output_file); if (!dm_particle_output_file.empty()) { DMPC->WriteAsciiFile(dm_particle_output_file); } } #ifdef AGN { BL_ASSERT(APC == 0); APC = new AGNParticleContainer(parent, num_particle_ghosts); ActiveParticles.push_back(APC); if (parent->subCycle()) { VirtAPC = new AGNParticleContainer(parent, num_particle_ghosts); VirtualParticles.push_back(VirtAPC); GhostAPC = new AGNParticleContainer(parent, num_particle_ghosts); GhostParticles.push_back(GhostAPC); } // // Make sure to call RemoveParticlesOnExit() on exit. // amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // APC->SetVerbose(particle_verbose); APC->Restart(restart_file, agn_chk_particle_file, is_checkpoint); // // We want the ability to write the particles out to an ascii file. // ParmParse pp("particles"); std::string agn_particle_output_file; pp.query("agn_particle_output_file", agn_particle_output_file); if (!agn_particle_output_file.empty()) { APC->WriteAsciiFile(agn_particle_output_file); } } #endif #ifdef FDM { if(partlevel){ if(wkb_approx){ BL_ASSERT (FDMwkbPC == 0); FDMwkbPC = new FDMwkbParticleContainer(parent); // ActiveParticles.push_back(FDMwkbPC); // if (parent->subCycle()) { VirtFDMwkbPC = new FDMwkbParticleContainer(parent); // VirtualParticles.push_back(VirtFDMwkbPC); GhostFDMwkbPC = new FDMwkbParticleContainer(parent); // GhostParticles.push_back(GhostFDMwkbPC); } // // Make sure to call RemoveParticlesOnExit() on exit. // (if do_dm_particles then we have already called ExecOnFinalize) // if (!do_dm_particles) amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // FDMwkbPC->SetVerbose(particle_verbose); FDMwkbPC->Restart(restart_file, fdm_chk_particle_file, is_checkpoint); // // We want the ability to write the particles out to an ascii file. // ParmParse pp("particles"); std::string fdm_particle_output_file; pp.query("fdm_particle_output_file", fdm_particle_output_file); if (!fdm_particle_output_file.empty()) { FDMwkbPC->WriteAsciiFile(fdm_particle_output_file); } }else if(phase_approx){ BL_ASSERT (FDMphasePC == 0); FDMphasePC = new FDMphaseParticleContainer(parent); // ActiveParticles.push_back(FDMphasePC); // if (parent->subCycle()) { VirtFDMphasePC = new FDMphaseParticleContainer(parent); // VirtualParticles.push_back(VirtFDMphasePC); GhostFDMphasePC = new FDMphaseParticleContainer(parent); // GhostParticles.push_back(GhostFDMphasePC); } // // Make sure to call RemoveParticlesOnExit() on exit. // (if do_dm_particles then we have already called ExecOnFinalize) // if (!do_dm_particles) amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // FDMphasePC->SetVerbose(particle_verbose); FDMphasePC->Restart(restart_file, fdm_chk_particle_file, is_checkpoint); // // We want the ability to write the particles out to an ascii file. // ParmParse pp("particles"); std::string fdm_particle_output_file; pp.query("fdm_particle_output_file", fdm_particle_output_file); if (!fdm_particle_output_file.empty()) { FDMphasePC->WriteAsciiFile(fdm_particle_output_file); } }else{ BL_ASSERT (FDMPC == 0); FDMPC = new FDMParticleContainer(parent); // ActiveParticles.push_back(FDMPC); // if (parent->subCycle()) { VirtFDMPC = new FDMParticleContainer(parent); // VirtualParticles.push_back(VirtFDMPC); GhostFDMPC = new FDMParticleContainer(parent); // GhostParticles.push_back(GhostFDMPC); } // // Make sure to call RemoveParticlesOnExit() on exit. // (if do_dm_particles then we have already called ExecOnFinalize) // if (!do_dm_particles) amrex::ExecOnFinalize(RemoveParticlesOnExit); // // 2 gives more stuff than 1. // FDMPC->SetVerbose(particle_verbose); FDMPC->Restart(restart_file, fdm_chk_particle_file, is_checkpoint); // // We want the ability to write the particles out to an ascii file. // ParmParse pp("particles"); std::string fdm_particle_output_file; pp.query("fdm_particle_output_file", fdm_particle_output_file); if (!fdm_particle_output_file.empty()) { FDMPC->WriteAsciiFile(fdm_particle_output_file); } } } } #endif } #ifdef GRAVITY void Nyx::particle_est_time_step (Real& est_dt) { BL_PROFILE("Nyx::particle_est_time_step()"); const Real cur_time = state[PhiGrav_Type].curTime(); const Real a = get_comoving_a(cur_time); MultiFab& grav = get_new_data(Gravity_Type); if (DMPC && particle_move_type == "Gravitational") { const Real est_dt_particle = DMPC->estTimestep(grav, a, level, particle_cfl); if (est_dt_particle > 0) { est_dt = std::min(est_dt, est_dt_particle); } if (verbose) { if (est_dt_particle > 0) { amrex::Print() << "...estdt from particles at level " << level << ": " << est_dt_particle << '\n'; } else { amrex::Print() << "...there are no particles at level " << level << '\n'; } } } #ifdef NEUTRINO_PARTICLES if (NPC && particle_move_type == "Gravitational") { const Real est_dt_neutrino = NPC->estTimestep(grav, a, level, neutrino_cfl); if (est_dt_neutrino > 0) { est_dt = std::min(est_dt, est_dt_neutrino); } if (verbose) { if (est_dt_neutrino > 0) { amrex::Print() << "...estdt from neutrinos at level " << level << ": " << est_dt_neutrino << '\n'; } else { amrex::Print() << "...there are no neutrinos at level " << level << '\n'; } } } #endif #ifdef FDM if (FDMwkbPC && particle_move_type == "Gravitational") { Real est_dt_fdm; //This condition is specific to the agora runs and has to be changed right after !!!!! if(level>=5){ //if(false){ const Real est_dt_fdm1 = FDMwkbPC->estTimestep(grav, a, level, particle_cfl); MultiFab& phi = get_new_data(PhiGrav_Type); Real beam_cfl_reduced = beam_cfl*2.0*M_PI*hbaroverm; const Real est_dt_fdm2 = FDMwkbPC->estTimestepFDM(phi, a, level, beam_cfl_reduced); est_dt_fdm = std::min(est_dt_fdm1 ,est_dt_fdm2); // }else // est_dt_fdm = FDMwkbPC->estTimestep(grav, a, level, particle_cfl); if (est_dt_fdm > 0) est_dt = std::min(est_dt, est_dt_fdm); if (verbose) { if (est_dt_fdm > 0) { amrex::Print() << "...estdt from FDMwkb at level " << level << ": " << est_dt_fdm << '\n'; } else { amrex::Print() << "...there are no FDMwkb beams at level " << level << '\n'; } } } } if (FDMPC && particle_move_type == "Gravitational") { const Real est_dt_fdm1 = FDMPC->estTimestep(grav, a, level, particle_cfl); MultiFab& phi = get_new_data(PhiGrav_Type); Real beam_cfl_reduced = beam_cfl*2.0*M_PI*hbaroverm; const Real est_dt_fdm2 = FDMPC->estTimestepFDM(phi, a, level, beam_cfl_reduced); const Real est_dt_fdm = std::min(est_dt_fdm1 ,est_dt_fdm2); // const Real est_dt_fdm = FDMPC->estTimestep(grav, a, level, particle_cfl); if (est_dt_fdm > 0) est_dt = std::min(est_dt, est_dt_fdm); if (verbose) { if (est_dt_fdm > 0) { amrex::Print() << "...estdt from FDM at level " << level << ": " << est_dt_fdm << '\n'; } else { amrex::Print() << "...there are no FDM beams at level " << level << '\n'; } } } if (FDMphasePC && particle_move_type == "Gravitational") { Real est_dt_fdm; //This condition is specific to the agora runs and has to be changed right after !!!!! if(level>=5){ //if(false){ const Real est_dt_fdm1 = FDMphasePC->estTimestep(grav, a, level, particle_cfl); MultiFab& phi = get_new_data(PhiGrav_Type); Real beam_cfl_reduced = beam_cfl*2.0*M_PI*hbaroverm; const Real est_dt_fdm2 = FDMphasePC->estTimestepFDM(phi, a, level, beam_cfl_reduced); est_dt_fdm = std::min(est_dt_fdm1 ,est_dt_fdm2); // }else // est_dt_fdm = FDMphasePC->estTimestep(grav, a, level, particle_cfl); if (est_dt_fdm > 0) est_dt = std::min(est_dt, est_dt_fdm); if (verbose) { if (est_dt_fdm > 0) { amrex::Print() << "...estdt from FDMphase at level " << level << ": " << est_dt_fdm << '\n'; } else { amrex::Print() << "...there are no FDMphase beams at level " << level << '\n'; } } } } #endif } #endif void Nyx::particle_redistribute (int lbase, int iteration, bool my_init) { BL_PROFILE("Nyx::particle_redistribute()"); #ifdef FDM if (DMPC || FDMPC || FDMwkbPC || FDMphasePC) #else if (DMPC) #endif { // // If we are calling with my_init = true, then we want to force the redistribute // without checking whether the grids have changed. // if (my_init) { #ifdef FDM if(DMPC) DMPC->Redistribute(lbase, DMPC->finestLevel(), iteration); if(FDMPC) FDMPC->Redistribute(lbase, FDMPC->finestLevel(), iteration); if(FDMwkbPC) FDMwkbPC->Redistribute(lbase, FDMwkbPC->finestLevel(), iteration); if(FDMphasePC) FDMphasePC->Redistribute(lbase, FDMphasePC->finestLevel(), iteration); #else DMPC->Redistribute(lbase, DMPC->finestLevel(),iteration); #endif return; } // // These are usually the BoxArray and DMap from the last regridding. // static Vector<BoxArray> ba; static Vector<DistributionMapping> dm; bool changed = false; bool dm_changed = false; bool ba_changed = false; bool ba_size_changed = false; int flev = parent->finestLevel(); while ( parent->getAmrLevels()[flev] == nullptr ) { flev--; } if (ba.size() != flev+1) { amrex::Print() << "BA SIZE " << ba.size() << std::endl; amrex::Print() << "FLEV " << flev << std::endl; ba.resize(flev+1); dm.resize(flev+1); changed = true; ba_size_changed = true; } else { for (int i = 0; i <= flev && !changed; i++) { if (ba[i] != parent->boxArray(i)) { // // The BoxArrays have changed in the regridding. // changed = true; ba_changed = true; } if ( ! changed) { if (dm[i] != parent->getLevel(i).get_new_data(0).DistributionMap()) { // // The DistributionMaps have changed in the regridding. // changed = true; dm_changed = true; } } } } if (changed) { // // We only need to call Redistribute if the BoxArrays or DistMaps have changed. // We also only call it for particles >= lbase. This is // because of we called redistribute during a subcycle, there may be particles not in // the proper position on coarser levels. // if (verbose) { if (ba_size_changed) amrex::Print() << "Calling redistribute because the size of BoxArray changed " << '\n'; else if (ba_changed) amrex::Print() << "Calling redistribute because BoxArray changed " << '\n'; else if (dm_changed) amrex::Print() << "Calling redistribute because DistMap changed " << '\n'; } #ifdef FDM if(DMPC) DMPC->Redistribute(lbase, -1, parent->levelCount(lbase)); if(FDMPC) FDMPC->Redistribute(lbase, -1, parent->levelCount(lbase)); if(FDMwkbPC) FDMwkbPC->Redistribute(lbase, -1, parent->levelCount(lbase)); if(FDMphasePC) FDMphasePC->Redistribute(lbase, -1, parent->levelCount(lbase)); #else DMPC->Redistribute(lbase, -1, parent->levelCount(lbase)); #endif // // Use the new BoxArray and DistMap to define ba and dm for next time. // for (int i = 0; i <= flev; i++) { ba[i] = parent->boxArray(i); dm[i] = parent->getLevel(i).get_new_data(0).DistributionMap(); } } else { if (verbose) amrex::Print() << "NOT calling redistribute because NOT changed " << '\n'; } } } void Nyx::particle_move_random () { BL_PROFILE("Nyx::particle_move_random()"); if (DMPC && particle_move_type == "Random") { BL_ASSERT(level == 0); DMPC->MoveRandom(); } } void Nyx::setup_virtual_particles() { BL_PROFILE("Nyx::setup_virtual_particles()"); if(!virtual_particles_set) { if(Nyx::theDMPC() != 0){ DarkMatterParticleContainer::AoS virts; if (level < parent->finestLevel()) { get_level(level + 1).setup_virtual_particles(); Nyx::theVirtPC()->CreateVirtualParticles(level+1, virts); Nyx::theVirtPC()->AddParticlesAtLevel(virts, level); Nyx::theDMPC()->CreateVirtualParticles(level+1, virts); Nyx::theVirtPC()->AddParticlesAtLevel(virts, level); } } #ifdef FDM if(Nyx::theFDMPC() != 0){ FDMParticleContainer::AoS virts; if (level < parent->finestLevel()) { if(Nyx::theDMPC() == 0) get_level(level + 1).setup_virtual_particles(); Nyx::theVirtFDMPC()->CreateVirtualParticles(level+1, virts); Nyx::theVirtFDMPC()->AddParticlesAtLevel(virts, level); Nyx::theFDMPC()->CreateVirtualParticles(level+1, virts); Nyx::theVirtFDMPC()->AddParticlesAtLevel(virts, level); } } if(Nyx::theFDMwkbPC() != 0){ FDMwkbParticleContainer::AoS virts; if (level < parent->finestLevel()) { if(Nyx::theDMPC() == 0 && Nyx::theFDMPC() == 0) get_level(level + 1).setup_virtual_particles(); Nyx::theVirtFDMwkbPC()->CreateVirtualParticles(level+1, virts); Nyx::theVirtFDMwkbPC()->AddParticlesAtLevel(virts, level); Nyx::theFDMwkbPC()->CreateVirtualParticles(level+1, virts); Nyx::theVirtFDMwkbPC()->AddParticlesAtLevel(virts, level); } } if(Nyx::theFDMphasePC() != 0){ FDMphaseParticleContainer::AoS virts; if (level < parent->finestLevel()) { if(Nyx::theDMPC() == 0 && Nyx::theFDMPC() == 0) get_level(level + 1).setup_virtual_particles(); Nyx::theVirtFDMphasePC()->CreateVirtualParticles(level+1, virts); Nyx::theVirtFDMphasePC()->AddParticlesAtLevel(virts, level); Nyx::theFDMphasePC()->CreateVirtualParticles(level+1, virts); Nyx::theVirtFDMphasePC()->AddParticlesAtLevel(virts, level); } } #endif virtual_particles_set = true; } } void Nyx::remove_virtual_particles() { BL_PROFILE("Nyx::remove_virtual_particles()"); for (int i = 0; i < VirtualParticles.size(); i++) { if (VirtualParticles[i] != 0) VirtualParticles[i]->RemoveParticlesAtLevel(level); virtual_particles_set = false; } #ifdef FDM if(theVirtFDMPC()){ theVirtFDMPC()->RemoveParticlesAtLevel(level); virtual_particles_set = false; } if(theVirtFDMwkbPC()){ theVirtFDMwkbPC()->RemoveParticlesAtLevel(level); virtual_particles_set = false; } if(theVirtFDMphasePC()){ theVirtFDMphasePC()->RemoveParticlesAtLevel(level); virtual_particles_set = false; } #endif } void Nyx::setup_ghost_particles(int ngrow) { BL_PROFILE("Nyx::setup_ghost_particles()"); BL_ASSERT(level < parent->finestLevel()); if(Nyx::theDMPC() != 0) { DarkMatterParticleContainer::AoS ghosts; Nyx::theDMPC()->CreateGhostParticles(level, ngrow, ghosts); Nyx::theGhostPC()->AddParticlesAtLevel(ghosts, level+1, ngrow); } #ifdef AGN if(Nyx::theAPC() != 0) { AGNParticleContainer::AoS ghosts; Nyx::theAPC()->CreateGhostParticles(level, ngrow, ghosts); Nyx::theGhostAPC()->AddParticlesAtLevel(ghosts, level+1, ngrow); } #endif #ifdef NEUTRINO_PARTICLES if(Nyx::theNPC() != 0) { #ifdef NEUTRINO_DARK_PARTICLES DarkMatterParticleContainer::AoS ghosts; #else NeutrinoParticleContainer::AoS ghosts; #endif Nyx::theNPC()->CreateGhostParticles(level, ngrow, ghosts); Nyx::theGhostNPC()->AddParticlesAtLevel(ghosts, level+1, ngrow); } #endif #ifdef FDM // if(Nyx::theFDMPC() != 0 && levelmethod[level+1]==GBlevel) // { // FDMParticleContainer::AoS ghosts; // int ng = parent->nCycle(level+1)+ceil(sigma_fdm*theta_fdm/parent->Geom(level+1).CellSize()[0]); // Nyx::theFDMPC()->CreateGhostParticles(level, ng, ghosts); // Nyx::theGhostFDMPC()->AddParticlesAtLevel(ghosts, level+1, ng); // } // if(Nyx::theFDMwkbPC() != 0 && levelmethod[level+1]==GBlevel) // { // FDMwkbParticleContainer::AoS ghosts; // int ng = parent->nCycle(level+1)+ceil(sigma_fdm*theta_fdm/parent->Geom(level+1).CellSize()[0]); // Nyx::theFDMwkbPC()->CreateGhostParticles(level, ng, ghosts); // Nyx::theGhostFDMwkbPC()->AddParticlesAtLevel(ghosts, level+1, ng); // } if(Nyx::theFDMPC() != 0) { for (int lev = level+1; lev <= parent->finestLevel(); lev++){ if(levelmethod[lev]==GBlevel){ FDMParticleContainer::AoS ghosts; int ng = parent->nCycle(lev)+ceil(sigma_fdm*theta_fdm/parent->Geom(lev).CellSize()[0]); Nyx::theFDMPC()->CreateGhostParticlesFDM(level, lev, ng, ghosts); Nyx::theGhostFDMPC()->AddParticlesAtLevel(ghosts, lev, ng); } } } if(Nyx::theFDMwkbPC() != 0) { for (int lev = level+1; lev <= parent->finestLevel(); lev++){ if(levelmethod[lev]==GBlevel){ FDMwkbParticleContainer::AoS ghosts; int ng = parent->nCycle(lev)+ceil(sigma_fdm*theta_fdm/parent->Geom(lev).CellSize()[0]); Nyx::theFDMwkbPC()->CreateGhostParticlesFDM(level, lev, ng, ghosts); Nyx::theGhostFDMwkbPC()->AddParticlesAtLevel(ghosts, lev, ng); } } } if(Nyx::theFDMphasePC() != 0) { for (int lev = level+1; lev <= parent->finestLevel(); lev++){ if(levelmethod[lev]==GBlevel || levelmethod[lev]==CWlevel){ FDMphaseParticleContainer::AoS ghosts; int ng = parent->nCycle(lev)+ceil(sigma_fdm*theta_fdm/parent->Geom(lev).CellSize()[0]); Nyx::theFDMphasePC()->CreateGhostParticlesFDM(level, lev, ng, ghosts); Nyx::theGhostFDMphasePC()->AddParticlesAtLevel(ghosts, lev, ng); } } } #endif } void Nyx::remove_ghost_particles() { BL_PROFILE("Nyx::remove_ghost_particles()"); for (int i = 0; i < GhostParticles.size(); i++) { if (GhostParticles[i] != 0) GhostParticles[i]->RemoveParticlesAtLevel(level); } #ifdef FDM if(theGhostFDMPC()) theGhostFDMPC()->RemoveParticlesAtLevel(level); if(theGhostFDMwkbPC()) theGhostFDMwkbPC()->RemoveParticlesAtLevel(level); if(theGhostFDMphasePC()) theGhostFDMphasePC()->RemoveParticlesAtLevel(level); #endif } //NyxParticleContainerBase::~NyxParticleContainerBase() {}
41.692412
212
0.466151
[ "vector" ]
abb963b984984877a25d6b29ed4f53203fe5f794
41,483
hpp
C++
src/TNL/Matrices/Sandbox/SparseSandboxMatrix.hpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
src/TNL/Matrices/Sandbox/SparseSandboxMatrix.hpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
src/TNL/Matrices/Sandbox/SparseSandboxMatrix.hpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
// Copyright (c) 2004-2022 Tomáš Oberhuber et al. // // This file is part of TNL - Template Numerical Library (https://tnl-project.org/) // // SPDX-License-Identifier: MIT #pragma once #include <functional> #include <sstream> #include <TNL/Algorithms/reduce.h> #include <TNL/Matrices/Sandbox/SparseSandboxMatrix.h> namespace TNL { namespace Matrices { namespace Sandbox { template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::SparseSandboxMatrix( const RealAllocatorType& realAllocator, const IndexAllocatorType& indexAllocator ) : BaseType( realAllocator ), columnIndexes( indexAllocator ), rowPointers( (IndexType) 1, (IndexType) 0, indexAllocator ) { this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Index_t, std::enable_if_t< std::is_integral< Index_t >::value, int > > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::SparseSandboxMatrix( const Index_t rows, const Index_t columns, const RealAllocatorType& realAllocator, const IndexAllocatorType& indexAllocator ) : BaseType( rows, columns, realAllocator ), columnIndexes( indexAllocator ), rowPointers( rows + 1, (IndexType) 0, indexAllocator ) { this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename ListIndex > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::SparseSandboxMatrix( const std::initializer_list< ListIndex >& rowCapacities, const IndexType columns, const RealAllocatorType& realAllocator, const IndexAllocatorType& indexAllocator ) : BaseType( rowCapacities.size(), columns, realAllocator ), columnIndexes( indexAllocator ), rowPointers( rowCapacities.size() + 1, (IndexType) 0, indexAllocator ) { this->setRowCapacities( RowsCapacitiesType( rowCapacities ) ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename RowCapacitiesVector, std::enable_if_t< TNL::IsArrayType< RowCapacitiesVector >::value, int > > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::SparseSandboxMatrix( const RowCapacitiesVector& rowCapacities, const IndexType columns, const RealAllocatorType& realAllocator, const IndexAllocatorType& indexAllocator ) : BaseType( rowCapacities.getSize(), columns, realAllocator ), columnIndexes( indexAllocator ), rowPointers( rowCapacities.getSize() + 1, (IndexType) 0, indexAllocator ) { this->setRowCapacities( rowCapacities ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::SparseSandboxMatrix( const IndexType rows, const IndexType columns, const std::initializer_list< std::tuple< IndexType, IndexType, RealType > >& data, const RealAllocatorType& realAllocator, const IndexAllocatorType& indexAllocator ) : BaseType( rows, columns, realAllocator ), columnIndexes( indexAllocator ), rowPointers( rows + 1, (IndexType) 0, indexAllocator ) { this->setElements( data ); this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename MapIndex, typename MapValue > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::SparseSandboxMatrix( const IndexType rows, const IndexType columns, const std::map< std::pair< MapIndex, MapIndex >, MapValue >& map, const RealAllocatorType& realAllocator, const IndexAllocatorType& indexAllocator ) : BaseType( rows, columns, realAllocator ), columnIndexes( indexAllocator ), rowPointers( rows + 1, (IndexType) 0, indexAllocator ) { this->setDimensions( rows, columns ); this->setElements( map ); this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > auto SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getView() const -> ViewType { return ViewType( this->getRows(), this->getColumns(), const_cast< SparseSandboxMatrix* >( this )->getValues().getView(), // TODO: remove const_cast const_cast< SparseSandboxMatrix* >( this )->columnIndexes.getView(), const_cast< SparseSandboxMatrix* >( this )->rowPointers.getView() ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > auto SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getConstView() const -> ConstViewType { return ConstViewType( this->getRows(), this->getColumns(), this->getValues().getConstView(), this->columnIndexes.getConstView(), this->segments.getConstView() ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > std::string SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getSerializationType() { return ViewType::getSerializationType(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > std::string SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getSerializationTypeVirtual() const { return this->getSerializationType(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::setDimensions( const IndexType rows, const IndexType columns ) { BaseType::setDimensions( rows, columns ); this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Matrix_ > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::setLike( const Matrix_& matrix ) { BaseType::setLike( matrix ); // SANDBOX_TODO: Replace the following line with assignment of metadata required by your format. // Do not assign matrix elements here. this->rowPointers = matrix.rowPointers; this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename RowsCapacitiesVector > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::setRowCapacities( const RowsCapacitiesVector& rowsCapacities ) { TNL_ASSERT_EQ( rowsCapacities.getSize(), this->getRows(), "Number of matrix rows does not fit with rowCapacities vector size." ); using RowsCapacitiesVectorDevice = typename RowsCapacitiesVector::DeviceType; // SANDBOX_TODO: Replace the following lines with the setup of your sparse matrix format based on // `rowsCapacities`. This container has the same number of elements as is the number of // rows of this matrix. Each element says how many nonzero elements the user needs to have // in each row. This number can be increased if the sparse matrix format uses padding zeros. this->rowPointers.setSize( this->getRows() + 1 ); if( std::is_same< DeviceType, RowsCapacitiesVectorDevice >::value ) { // GOTCHA: when this->getRows() == 0, getView returns a full view with size == 1 if( this->getRows() > 0 ) { auto view = this->rowPointers.getView( 0, this->getRows() ); view = rowsCapacities; } } else { RowsCapacitiesType thisRowsCapacities; thisRowsCapacities = rowsCapacities; if( this->getRows() > 0 ) { auto view = this->rowPointers.getView( 0, this->getRows() ); view = thisRowsCapacities; } } this->rowPointers.setElement( this->getRows(), 0 ); Algorithms::inplaceExclusiveScan( this->rowPointers ); // this->rowPointers.template scan< Algorithms::ScanType::Exclusive >(); // End of sparse matrix format initiation. // SANDBOX_TODO: Compute number of all elements that need to be allocated by your format. const auto storageSize = rowPointers.getElement( this->getRows() ); // The rest of this methods needs no changes. if( ! isBinary() ) { this->values.setSize( storageSize ); this->values = (RealType) 0; } this->columnIndexes.setSize( storageSize ); this->columnIndexes = this->getPaddingIndex(); this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Vector > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getRowCapacities( Vector& rowCapacities ) const { this->view.getRowCapacities( rowCapacities ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::setElements( const std::initializer_list< std::tuple< IndexType, IndexType, RealType > >& data ) { const auto& rows = this->getRows(); const auto& columns = this->getColumns(); Containers::Vector< IndexType, Devices::Host, IndexType > rowCapacities( rows, 0 ); for( const auto& i : data ) { if( std::get< 0 >( i ) >= rows ) { std::stringstream s; s << "Wrong row index " << std::get< 0 >( i ) << " in an initializer list"; throw std::logic_error( s.str() ); } rowCapacities[ std::get< 0 >( i ) ]++; } SparseSandboxMatrix< Real, Devices::Host, Index, MatrixType > hostMatrix( rows, columns ); hostMatrix.setRowCapacities( rowCapacities ); for( const auto& i : data ) { if( std::get< 1 >( i ) >= columns ) { std::stringstream s; s << "Wrong column index " << std::get< 1 >( i ) << " in an initializer list"; throw std::logic_error( s.str() ); } hostMatrix.setElement( std::get< 0 >( i ), std::get< 1 >( i ), std::get< 2 >( i ) ); } ( *this ) = hostMatrix; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename MapIndex, typename MapValue > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::setElements( const std::map< std::pair< MapIndex, MapIndex >, MapValue >& map ) { Containers::Vector< IndexType, Devices::Host, IndexType > rowsCapacities( this->getRows(), 0 ); for( auto element : map ) rowsCapacities[ element.first.first ]++; if( ! std::is_same< DeviceType, Devices::Host >::value ) { SparseSandboxMatrix< Real, Devices::Host, Index, MatrixType > hostMatrix( this->getRows(), this->getColumns() ); hostMatrix.setRowCapacities( rowsCapacities ); for( auto element : map ) hostMatrix.setElement( element.first.first, element.first.second, element.second ); *this = hostMatrix; } else { this->setRowCapacities( rowsCapacities ); for( auto element : map ) this->setElement( element.first.first, element.first.second, element.second ); } } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Vector > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getCompressedRowLengths( Vector& rowLengths ) const { this->view.getCompressedRowLengths( rowLengths ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > __cuda_callable__ Index SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getRowCapacity( const IndexType row ) const { return this->view.getRowCapacity( row ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > Index SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getNonzeroElementsCount() const { return this->view.getNonzeroElementsCount(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::reset() { BaseType::reset(); this->columnIndexes.reset(); // SANDBOX_TODO: Reset the metadata required by your format here. this->rowPointers.reset(); this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > __cuda_callable__ auto SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getRow( const IndexType& rowIdx ) const -> const ConstRowView { return this->view.getRow( rowIdx ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > __cuda_callable__ auto SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getRow( const IndexType& rowIdx ) -> RowView { return this->view.getRow( rowIdx ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > __cuda_callable__ void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::setElement( const IndexType row, const IndexType column, const RealType& value ) { this->view.setElement( row, column, value ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > __cuda_callable__ void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::addElement( const IndexType row, const IndexType column, const RealType& value, const RealType& thisElementMultiplicator ) { this->view.addElement( row, column, value, thisElementMultiplicator ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > __cuda_callable__ auto SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getElement( const IndexType row, const IndexType column ) const -> RealType { return this->view.getElement( row, column ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename InVector, typename OutVector > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::vectorProduct( const InVector& inVector, OutVector& outVector, RealType matrixMultiplicator, RealType outVectorMultiplicator, IndexType firstRow, IndexType lastRow ) const { this->view.vectorProduct( inVector, outVector, matrixMultiplicator, outVectorMultiplicator, firstRow, lastRow ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Fetch, typename Reduce, typename Keep, typename FetchValue > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::reduceRows( IndexType begin, IndexType end, Fetch& fetch, const Reduce& reduce, Keep& keep, const FetchValue& zero ) { this->view.reduceRows( begin, end, fetch, reduce, keep, zero ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Fetch, typename Reduce, typename Keep, typename FetchValue > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::reduceRows( IndexType begin, IndexType end, Fetch& fetch, const Reduce& reduce, Keep& keep, const FetchValue& zero ) const { this->view.reduceRows( begin, end, fetch, reduce, keep, zero ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Fetch, typename Reduce, typename Keep, typename FetchReal > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::reduceAllRows( Fetch&& fetch, const Reduce&& reduce, Keep&& keep, const FetchReal& zero ) { this->reduceRows( 0, this->getRows(), fetch, reduce, keep, zero ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Fetch, typename Reduce, typename Keep, typename FetchReal > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::reduceAllRows( Fetch& fetch, const Reduce& reduce, Keep& keep, const FetchReal& zero ) const { this->reduceRows( 0, this->getRows(), fetch, reduce, keep, zero ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::forElements( IndexType begin, IndexType end, Function&& function ) const { this->view.forElements( begin, end, function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::forElements( IndexType begin, IndexType end, Function&& function ) { this->view.forElements( begin, end, function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::forAllElements( Function&& function ) const { this->forElements( 0, this->getRows(), function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::forAllElements( Function&& function ) { this->forElements( 0, this->getRows(), function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::forRows( IndexType begin, IndexType end, Function&& function ) { this->getView().forRows( begin, end, function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::forRows( IndexType begin, IndexType end, Function&& function ) const { this->getConstView().forRows( begin, end, function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::forAllRows( Function&& function ) { this->getView().forAllRows( function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::forAllRows( Function&& function ) const { this->getConsView().forAllRows( function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::sequentialForRows( IndexType begin, IndexType end, Function& function ) const { this->view.sequentialForRows( begin, end, function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::sequentialForRows( IndexType first, IndexType last, Function& function ) { this->view.sequentialForRows( first, last, function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::sequentialForAllRows( Function& function ) const { this->sequentialForRows( 0, this->getRows(), function ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Function > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::sequentialForAllRows( Function& function ) { this->sequentialForRows( 0, this->getRows(), function ); } /*template< typename Real, template< typename, typename, typename > class Segments, typename Device, typename Index, typename RealAllocator, typename IndexAllocator > template< typename Real2, template< typename, typename > class Segments2, typename Index2, typename RealAllocator2, typename IndexAllocator2 > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >:: addMatrix( const SparseSandboxMatrix< Real2, Segments2, Device, Index2, RealAllocator2, IndexAllocator2 >& matrix, const RealType& matrixMultiplicator, const RealType& thisMatrixMultiplicator ) { } template< typename Real, template< typename, typename, typename > class Segments, typename Device, typename Index, typename RealAllocator, typename IndexAllocator > template< typename Real2, typename Index2 > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >:: getTransposition( const SparseSandboxMatrix< Real2, Device, Index2 >& matrix, const RealType& matrixMultiplicator ) { }*/ template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Vector1, typename Vector2 > bool SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::performSORIteration( const Vector1& b, const IndexType row, Vector2& x, const RealType& omega ) const { return false; } // copy assignment template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >& SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::operator=( const SparseSandboxMatrix& matrix ) { Matrix< Real, Device, Index >::operator=( matrix ); this->columnIndexes = matrix.columnIndexes; // SANDBOX_TODO: Replace the following line with an assignment of metadata required by you sparse matrix format. this->rowPointers = matrix.rowPointers; this->view = this->getView(); return *this; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Device_ > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >& SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::operator=( const SparseSandboxMatrix< RealType, Device_, IndexType, MatrixType, RealAllocator, IndexAllocator >& matrix ) { Matrix< Real, Device, Index >::operator=( matrix ); this->columnIndexes = matrix.columnIndexes; // SANDBOX_TODO: Replace the following line with an assignment of metadata required by you sparse matrix format. this->rowPointers = matrix.rowPointers; this->view = this->getView(); return *this; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Real_, typename Device_, typename Index_, ElementsOrganization Organization, typename RealAllocator_ > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >& SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::operator=( const DenseMatrix< Real_, Device_, Index_, Organization, RealAllocator_ >& matrix ) { using RHSMatrix = DenseMatrix< Real_, Device_, Index_, Organization, RealAllocator_ >; using RHSIndexType = typename RHSMatrix::IndexType; using RHSRealType = typename RHSMatrix::RealType; using RHSDeviceType = typename RHSMatrix::DeviceType; using RHSRealAllocatorType = typename RHSMatrix::RealAllocatorType; Containers::Vector< RHSIndexType, RHSDeviceType, RHSIndexType > rowLengths; matrix.getCompressedRowLengths( rowLengths ); this->setLike( matrix ); this->setRowCapacities( rowLengths ); Containers::Vector< IndexType, DeviceType, IndexType > rowLocalIndexes( matrix.getRows() ); rowLocalIndexes = 0; // TODO: use getConstView when it works const auto matrixView = const_cast< RHSMatrix& >( matrix ).getView(); const IndexType paddingIndex = this->getPaddingIndex(); auto columns_view = this->columnIndexes.getView(); auto values_view = this->values.getView(); auto rowLocalIndexes_view = rowLocalIndexes.getView(); columns_view = paddingIndex; if( std::is_same< DeviceType, RHSDeviceType >::value ) { const auto segments_view = this->segments.getView(); auto f = [ = ] __cuda_callable__( RHSIndexType rowIdx, RHSIndexType localIdx, RHSIndexType columnIdx, const RHSRealType& value ) mutable { if( value != 0.0 ) { IndexType thisGlobalIdx = segments_view.getGlobalIndex( rowIdx, rowLocalIndexes_view[ rowIdx ]++ ); columns_view[ thisGlobalIdx ] = columnIdx; if( ! isBinary() ) values_view[ thisGlobalIdx ] = value; } }; matrix.forAllElements( f ); } else { const IndexType maxRowLength = matrix.getColumns(); const IndexType bufferRowsCount( 128 ); const size_t bufferSize = bufferRowsCount * maxRowLength; Containers::Vector< RHSRealType, RHSDeviceType, RHSIndexType, RHSRealAllocatorType > matrixValuesBuffer( bufferSize ); Containers::Vector< RealType, DeviceType, IndexType, RealAllocatorType > thisValuesBuffer( bufferSize ); Containers::Vector< IndexType, DeviceType, IndexType, IndexAllocatorType > thisColumnsBuffer( bufferSize ); auto matrixValuesBuffer_view = matrixValuesBuffer.getView(); auto thisValuesBuffer_view = thisValuesBuffer.getView(); IndexType baseRow( 0 ); const IndexType rowsCount = this->getRows(); while( baseRow < rowsCount ) { const IndexType lastRow = min( baseRow + bufferRowsCount, rowsCount ); thisColumnsBuffer = paddingIndex; //// // Copy matrix elements into buffer auto f1 = [ = ] __cuda_callable__( RHSIndexType rowIdx, RHSIndexType localIdx, RHSIndexType columnIndex, const RHSRealType& value ) mutable { const IndexType bufferIdx = ( rowIdx - baseRow ) * maxRowLength + localIdx; matrixValuesBuffer_view[ bufferIdx ] = value; }; matrix.forElements( baseRow, lastRow, f1 ); //// // Copy the source matrix buffer to this matrix buffer thisValuesBuffer_view = matrixValuesBuffer_view; //// // Copy matrix elements from the buffer to the matrix and ignoring // zero matrix elements. const IndexType matrix_columns = this->getColumns(); auto f2 = [ = ] __cuda_callable__( IndexType rowIdx, IndexType localIdx, IndexType & columnIndex, RealType & value ) mutable { RealType inValue( 0.0 ); IndexType bufferIdx, column( rowLocalIndexes_view[ rowIdx ] ); while( inValue == 0.0 && column < matrix_columns ) { bufferIdx = ( rowIdx - baseRow ) * maxRowLength + column++; inValue = thisValuesBuffer_view[ bufferIdx ]; } rowLocalIndexes_view[ rowIdx ] = column; if( inValue == 0.0 ) { columnIndex = paddingIndex; value = 0.0; } else { columnIndex = column - 1; value = inValue; } }; this->forElements( baseRow, lastRow, f2 ); baseRow += bufferRowsCount; } // std::cerr << "This matrix = " << std::endl << *this << std::endl; } this->view = this->getView(); return *this; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename RHSMatrix > SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >& SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::operator=( const RHSMatrix& matrix ) { using RHSIndexType = typename RHSMatrix::IndexType; using RHSRealType = typename RHSMatrix::RealType; using RHSDeviceType = typename RHSMatrix::DeviceType; using RHSRealAllocatorType = typename RHSMatrix::RealAllocatorType; Containers::Vector< RHSIndexType, RHSDeviceType, RHSIndexType > rowCapacities; matrix.getRowCapacities( rowCapacities ); this->setDimensions( matrix.getRows(), matrix.getColumns() ); this->setRowCapacities( rowCapacities ); Containers::Vector< IndexType, DeviceType, IndexType > rowLocalIndexes( matrix.getRows() ); rowLocalIndexes = 0; // TODO: use getConstView when it works const auto matrixView = const_cast< RHSMatrix& >( matrix ).getView(); const IndexType paddingIndex = this->getPaddingIndex(); auto columns_view = this->columnIndexes.getView(); auto values_view = this->values.getView(); auto rowLocalIndexes_view = rowLocalIndexes.getView(); columns_view = paddingIndex; // SANDBOX_TODO: Modify the follwoing accoring to your format auto row_pointers_view = this->rowPointers.getView(); if( std::is_same< DeviceType, RHSDeviceType >::value ) { auto f = [ = ] __cuda_callable__( RHSIndexType rowIdx, RHSIndexType localIdx_, RHSIndexType columnIndex, const RHSRealType& value ) mutable { IndexType localIdx( rowLocalIndexes_view[ rowIdx ] ); IndexType thisRowBegin = row_pointers_view[ rowIdx ]; if( value != 0.0 && columnIndex != paddingIndex ) { IndexType thisGlobalIdx = thisRowBegin + localIdx++; columns_view[ thisGlobalIdx ] = columnIndex; if( ! isBinary() ) values_view[ thisGlobalIdx ] = value; rowLocalIndexes_view[ rowIdx ] = localIdx; } }; matrix.forAllElements( f ); } else { const IndexType maxRowLength = max( rowCapacities ); const IndexType bufferRowsCount( 128 ); const size_t bufferSize = bufferRowsCount * maxRowLength; Containers::Vector< RHSRealType, RHSDeviceType, RHSIndexType, RHSRealAllocatorType > matrixValuesBuffer( bufferSize ); Containers::Vector< RHSIndexType, RHSDeviceType, RHSIndexType > matrixColumnsBuffer( bufferSize ); Containers::Vector< RealType, DeviceType, IndexType, RealAllocatorType > thisValuesBuffer( bufferSize ); Containers::Vector< IndexType, DeviceType, IndexType > thisColumnsBuffer( bufferSize ); Containers::Vector< IndexType, DeviceType, IndexType > thisRowLengths; Containers::Vector< RHSIndexType, RHSDeviceType, RHSIndexType > rhsRowLengths; matrix.getCompressedRowLengths( rhsRowLengths ); thisRowLengths = rhsRowLengths; auto matrixValuesBuffer_view = matrixValuesBuffer.getView(); auto matrixColumnsBuffer_view = matrixColumnsBuffer.getView(); auto thisValuesBuffer_view = thisValuesBuffer.getView(); auto thisColumnsBuffer_view = thisColumnsBuffer.getView(); matrixValuesBuffer_view = 0.0; IndexType baseRow( 0 ); const IndexType rowsCount = this->getRows(); while( baseRow < rowsCount ) { const IndexType lastRow = min( baseRow + bufferRowsCount, rowsCount ); thisColumnsBuffer = paddingIndex; matrixColumnsBuffer_view = paddingIndex; //// // Copy matrix elements into buffer auto f1 = [ = ] __cuda_callable__( RHSIndexType rowIdx, RHSIndexType localIdx, RHSIndexType columnIndex, const RHSRealType& value ) mutable { if( columnIndex != paddingIndex ) { TNL_ASSERT_LT( rowIdx - baseRow, bufferRowsCount, "" ); TNL_ASSERT_LT( localIdx, maxRowLength, "" ); const IndexType bufferIdx = ( rowIdx - baseRow ) * maxRowLength + localIdx; TNL_ASSERT_LT( bufferIdx, (IndexType) bufferSize, "" ); matrixColumnsBuffer_view[ bufferIdx ] = columnIndex; matrixValuesBuffer_view[ bufferIdx ] = value; } }; matrix.forElements( baseRow, lastRow, f1 ); //// // Copy the source matrix buffer to this matrix buffer thisValuesBuffer_view = matrixValuesBuffer_view; thisColumnsBuffer_view = matrixColumnsBuffer_view; //// // Copy matrix elements from the buffer to the matrix and ignoring // zero matrix elements // const IndexType matrix_columns = this->getColumns(); const auto thisRowLengths_view = thisRowLengths.getConstView(); auto f2 = [ = ] __cuda_callable__( IndexType rowIdx, IndexType localIdx, IndexType & columnIndex, RealType & value ) mutable { RealType inValue( 0.0 ); size_t bufferIdx; IndexType bufferLocalIdx( rowLocalIndexes_view[ rowIdx ] ); while( inValue == 0.0 && localIdx < thisRowLengths_view[ rowIdx ] ) { bufferIdx = ( rowIdx - baseRow ) * maxRowLength + bufferLocalIdx++; TNL_ASSERT_LT( bufferIdx, bufferSize, "" ); inValue = thisValuesBuffer_view[ bufferIdx ]; } rowLocalIndexes_view[ rowIdx ] = bufferLocalIdx; if( inValue == 0.0 ) { columnIndex = paddingIndex; value = 0.0; } else { columnIndex = thisColumnsBuffer_view[ bufferIdx ]; // column - 1; value = inValue; } }; this->forElements( baseRow, lastRow, f2 ); baseRow += bufferRowsCount; } } this->view = this->getView(); return *this; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Matrix > bool SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::operator==( const Matrix& m ) const { return view == m; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > template< typename Matrix > bool SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::operator!=( const Matrix& m ) const { return view != m; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::save( File& file ) const { this->view.save( file ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::load( File& file ) { Matrix< RealType, DeviceType, IndexType >::load( file ); file >> this->columnIndexes; // SANDBOX_TODO: Replace the following line with loading of metadata required by your sparse matrix format. file >> rowPointers; this->view = this->getView(); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::save( const String& fileName ) const { Object::save( fileName ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::load( const String& fileName ) { Object::load( fileName ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > void SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::print( std::ostream& str ) const { this->view.print( str ); } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > __cuda_callable__ Index SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getPaddingIndex() const { return -1; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > auto SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getColumnIndexes() const -> const ColumnsIndexesVectorType& { return this->columnIndexes; } template< typename Real, typename Device, typename Index, typename MatrixType, typename RealAllocator, typename IndexAllocator > auto SparseSandboxMatrix< Real, Device, Index, MatrixType, RealAllocator, IndexAllocator >::getColumnIndexes() -> ColumnsIndexesVectorType& { return this->columnIndexes; } } // namespace Sandbox } // namespace Matrices } // namespace TNL
46.041065
128
0.690596
[ "object", "vector" ]
abc78d507c3663a53904bbfb2a1e851cc3c84136
3,697
hpp
C++
source/Animation.hpp
Amaranese/mario-bros-cplusplus
b5aefffbd3650cfa0ff5e846f43748efde8666c5
[ "Unlicense" ]
1
2021-08-15T00:37:29.000Z
2021-08-15T00:37:29.000Z
source/Animation.hpp
Amaranese/mario-bros-cplusplus
b5aefffbd3650cfa0ff5e846f43748efde8666c5
[ "Unlicense" ]
null
null
null
source/Animation.hpp
Amaranese/mario-bros-cplusplus
b5aefffbd3650cfa0ff5e846f43748efde8666c5
[ "Unlicense" ]
null
null
null
#ifndef ANIMATION_HPP #define ANIMATION_HPP #include <vector> /** * A renderable graphic made up of one or more Frames. */ class Animation { public: /** * Represents an individual Frame of an Animation. */ struct Frame { // Texture atlas position: double left; double right; double bottom; double top; // Rendering parameters: double xOffset; double yOffset; double width; double height; }; /** * Default constructor. */ Animation(); /** * Create an animation with set orientations. */ Animation( bool horizontalOrientation, bool verticalOrientation ); /** * Add a new frame to the animation. * * @param left the left texture coordinate. * @param right the right texture coordinate. * @param bottom the bottom texture coordinate. * @param top the top texture coordinate. * @param xOffset how far left/right to render off-center. * @param yOffset how far up/down to render off-center. * @param width the width of the frame, in world units. * @param height the height of the frame, in world units. * @param the duration of the frame, in game frames (60 fps). */ void addFrame( double left, double right, double bottom, double top, double xOffset, double yOffset, double width, double height, int duration = 1 ); /** * Add a new frame to the animation. * * @param frame the Frame to add. * @param duration the duration of the frame. */ void addFrame( const Frame& frame, int duration = 1 ); /** * Get a frame from the animation. * * @param frameNumber the sequence number of the frame, starting at zero. * This loops/wraps around by default if the number is larger than the * total number of frames. * @see addFrame for documentation on other parameters. */ void getFrame( int frameNumber, double& left, double& right, double& bottom, double& top, double& xOffset, double& yOffset, double& width, double& height ) const; /** * Get the duration of the animation, in seconds. */ double getDuration() const; /** * Get a frame from the animation. * * @see the other version of getFrame for documentation. */ const Frame& getFrame(int frameNumber) const; /** * Get a frame by its absolute sequence in the Animation. */ const Frame& getFrameBySequence( int sequence ) const; /** * Get the horizontal orientation of the animation. * * @retval false for left (default). * @retval true for right. */ bool getHorizontalOrientation() const; /** * Get the length of the Animation, in frames. */ int getLength() const; /** * Get the vertical orientation of the animation. * * @retval false for down. * @retval true for up (default). */ bool getVerticalOrientation() const; /** * Render a frame of the animation. * * @param frame the Frame of the animation to render. * @param mirrorX whether mirroring should be performed in the x direction. * @param mirrorY whether mirroring should be performed in the y direction. * @note this assumes that the current projection has positive y facing up, * and that one unit = one pixel. */ void renderFrame( const Frame& frame, bool mirrorX = false, bool mirrorY = false ) const; /** * Render a frame of the animation. * * @see getFrame() for frameNumber parameter documentation. * @see renderFrame() for mirrorX and mirrorY parameter documentation. */ void renderFrame( int frameNumber = 0, bool mirrorX = false, bool mirrorY = false ) const; private: std::vector<Frame> frames; bool horizontalOrientation; /**< False for left, true for right. */ bool verticalOrientation; /**< False for down, true for up. */ }; #endif // ANIMATION_HPP
23.547771
91
0.687855
[ "render", "vector" ]
abc7bd697ef065c07b902426684eb14adf5045af
7,132
cpp
C++
Editor/editor.cpp
NinjaDanz3r/NinjaOctopushBurgersOfDoom
3b89f02d13504e4790fd655889b0cba261d4dbc6
[ "MIT" ]
1
2016-05-23T18:31:29.000Z
2016-05-23T18:31:29.000Z
Editor/editor.cpp
NinjaDanz3r/NinjaOctopushBurgersOfDoom
3b89f02d13504e4790fd655889b0cba261d4dbc6
[ "MIT" ]
25
2015-01-03T01:17:45.000Z
2015-03-23T09:37:52.000Z
Editor/editor.cpp
NinjaDanz3r/NinjaOctopushBurgersOfDoom
3b89f02d13504e4790fd655889b0cba261d4dbc6
[ "MIT" ]
null
null
null
#include "editor.h" #include <QtWidgets/QFileDialog> #include <QtWidgets/QInputDialog> #include <OBJModel.h> #include <Project.h> #include "convert.h" #include <ModelResource.h> #include <TextureResource.h> #include <SceneResource.h> #include "TexturePreview.h" #include "ModelPreview.h" Editor::Editor(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect(ui.actionNew, SIGNAL(triggered()), this, SLOT(newProject())); connect(ui.actionOpen, SIGNAL(triggered()), this, SLOT(openProject())); connect(ui.actionSave, SIGNAL(triggered()), this, SLOT(saveProject())); connect(ui.actionClose, SIGNAL(triggered()), this, SLOT(closeProject())); connect(ui.actionImportModel, SIGNAL(triggered()), this, SLOT(importModel())); connect(ui.actionImportTexture, SIGNAL(triggered()), this, SLOT(importTexture())); connect(ui.actionNew_Scene, SIGNAL(triggered()), this, SLOT(newScene())); connect(ui.treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(selectionChanged())); connect(ui.applySceneButton, SIGNAL(released()), this, SLOT(applyScene())); texturesRoot = addTreeRoot("Textures"); modelsRoot = addTreeRoot("Models"); scenesRoot = addTreeRoot("Scenes"); } Editor::~Editor() { if (activeProject != nullptr) delete activeProject; deleteChildren(modelsRoot); delete modelsRoot; deleteChildren(texturesRoot); delete texturesRoot; deleteChildren(scenesRoot); delete scenesRoot; } void Editor::newProject() { QString filename = QFileDialog::getSaveFileName(this, tr("Save Project"), "", tr("Project (*.proj);;All Files (*)")); if (filename.isEmpty()) { return; } closeProject(); activeProject = new Project(); activeProject->setFilename(filename.toStdString()); enableActions(true); } void Editor::openProject() { QString filename = QFileDialog::getOpenFileName(this, tr("Open Project"), "", tr("Project (*.proj);;All Files (*)")); if (filename.isEmpty()) { return; } closeProject(); activeProject = new Project(); activeProject->setFilename(filename.toStdString()); activeProject->load(); enableActions(true); for (auto texture : *activeProject->resources()->textureResources()) { QTreeWidgetItem *treeItem = new QTreeWidgetItem(); treeItem->setText(0, QString::fromStdString(texture.first)); texturesRoot->addChild(treeItem); } for (auto model : *activeProject->resources()->modelResources()) { QTreeWidgetItem *treeItem = new QTreeWidgetItem(); treeItem->setText(0, QString::fromStdString(model.first)); modelsRoot->addChild(treeItem); } for (auto scene : *activeProject->resources()->sceneResources()) { QTreeWidgetItem *treeItem = new QTreeWidgetItem(); treeItem->setText(0, QString::fromStdString(scene.first)); scenesRoot->addChild(treeItem); } } void Editor::saveProject() { activeProject->save(); } void Editor::closeProject() { if (activeProject != nullptr) { delete activeProject; activeProject = nullptr; } deleteChildren(modelsRoot); deleteChildren(texturesRoot); deleteChildren(scenesRoot); enableActions(false); ui.previewWidget->texturePreview()->setTexture(nullptr); ui.previewWidget->modelPreview()->setModel(nullptr); ui.previewWidget->repaint(); ui.stackedWidget->setCurrentIndex(EMPTY_PAGE); activeSceneResource = nullptr; } void Editor::importModel() { QString filename = QFileDialog::getOpenFileName(this, tr("Import Model"), "", tr("OBJ Model (*.obj);;All Files (*)")); if (filename.isEmpty()) { return; } QString name = QInputDialog::getText(this, tr("Enter Model Name"), tr("Model name:")); if (name.isEmpty()) { return; } ModelResource* model = new ModelResource(name.toStdString(), new OBJModel(filename.toStdString().c_str())); (*activeProject->resources()->modelResources())[model->name] = model; QTreeWidgetItem *treeItem = new QTreeWidgetItem(); treeItem->setText(0, name); modelsRoot->addChild(treeItem); } void Editor::importTexture() { QString filename = QFileDialog::getOpenFileName(this, tr("Import Texture"), "", tr("Image Files (*.png *.jpg *.jpeg *.tga *.bmp);;All Files (*)")); if (filename.isEmpty()) { return; } QString name = QInputDialog::getText(this, tr("Enter Texture Name"), tr("Texture name:")); if (name.isEmpty()) { return; } convert::convertImage(filename.toStdString().c_str(), (activeProject->directory() + "/Textures/" + name.toStdString() + ".tga").c_str()); TextureResource* texture = new TextureResource(name.toStdString(), activeProject->directory() + "/Textures"); (*activeProject->resources()->textureResources())[texture->name] = texture; QTreeWidgetItem *treeItem = new QTreeWidgetItem(); treeItem->setText(0, name); texturesRoot->addChild(treeItem); } void Editor::newScene() { QString name = QInputDialog::getText(this, tr("Enter Scene Name"), tr("Scene name:")); if (name.isEmpty()) { return; } SceneResource* scene = new SceneResource(name.toStdString()); (*activeProject->resources()->sceneResources())[scene->name] = scene; QTreeWidgetItem *treeItem = new QTreeWidgetItem(); treeItem->setText(0, name); scenesRoot->addChild(treeItem); } void Editor::selectionChanged() { if (ui.treeWidget->selectedItems().length() > 0) { QTreeWidgetItem* selected = ui.treeWidget->selectedItems()[0]; if (selected->parent() == texturesRoot) { ui.previewWidget->setPreview(ui.previewWidget->texturePreview()); ui.previewWidget->texturePreview()->setTexture((*activeProject->resources()->textureResources())[selected->text(0).toStdString()]->texture()); ui.previewWidget->repaint(); } else if (selected->parent() == modelsRoot) { ui.previewWidget->setPreview(ui.previewWidget->modelPreview()); ui.previewWidget->modelPreview()->setModel((*activeProject->resources()->modelResources())[selected->text(0).toStdString()]->model()); ui.previewWidget->repaint(); } else if (selected->parent() == scenesRoot) { ui.stackedWidget->setCurrentIndex(SCENE_PAGE); activeSceneResource = (*activeProject->resources()->sceneResources())[selected->text(0).toStdString()]; ui.playerXLineEdit->setText(QString::number(activeSceneResource->playerPosition.x)); ui.playerYLineEdit->setText(QString::number(activeSceneResource->playerPosition.y)); ui.playerZLineEdit->setText(QString::number(activeSceneResource->playerPosition.z)); } } } void Editor::applyScene() { activeSceneResource->playerPosition.x = ui.playerXLineEdit->text().toFloat(); activeSceneResource->playerPosition.y = ui.playerYLineEdit->text().toFloat(); activeSceneResource->playerPosition.z = ui.playerZLineEdit->text().toFloat(); } void Editor::enableActions(bool enabled) { ui.actionSave->setEnabled(enabled); ui.actionClose->setEnabled(enabled); ui.actionImportModel->setEnabled(enabled); ui.actionImportTexture->setEnabled(enabled); ui.actionNew_Scene->setEnabled(enabled); } QTreeWidgetItem* Editor::addTreeRoot(QString name) { QTreeWidgetItem* treeItem = new QTreeWidgetItem(ui.treeWidget); treeItem->setText(0, name); return treeItem; } void Editor::deleteChildren(QTreeWidgetItem* item) { QList<QTreeWidgetItem*> children = item->takeChildren(); for (auto child : children) { delete child; } }
32.271493
148
0.727706
[ "model" ]
abcbe33cd308655ea75abe321f95afc049d62345
11,837
hpp
C++
include/System/Security/Cryptography/RSACryptoServiceProvider.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Security/Cryptography/RSACryptoServiceProvider.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Security/Cryptography/RSACryptoServiceProvider.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Security.Cryptography.RSA #include "System/Security/Cryptography/RSA.hpp" // Including type: System.Security.Cryptography.CspProviderFlags #include "System/Security/Cryptography/CspProviderFlags.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: Mono::Security::Cryptography namespace Mono::Security::Cryptography { // Forward declaring type: KeyPairPersistence class KeyPairPersistence; // Forward declaring type: RSAManaged class RSAManaged; } // Forward declaring namespace: System::Security::Cryptography namespace System::Security::Cryptography { // Forward declaring type: HashAlgorithmName struct HashAlgorithmName; // Forward declaring type: CspParameters class CspParameters; // Forward declaring type: HashAlgorithm class HashAlgorithm; // Forward declaring type: RSASignaturePadding class RSASignaturePadding; // Forward declaring type: RSAParameters struct RSAParameters; } // Forward declaring namespace: System namespace System { // Forward declaring type: Exception class Exception; // Forward declaring type: EventArgs class EventArgs; } // Completed forward declares // Type namespace: System.Security.Cryptography namespace System::Security::Cryptography { // Size: 0x38 #pragma pack(push, 1) // Autogenerated type: System.Security.Cryptography.RSACryptoServiceProvider // [ComVisibleAttribute] Offset: D7DACC class RSACryptoServiceProvider : public System::Security::Cryptography::RSA { public: // private Mono.Security.Cryptography.KeyPairPersistence store // Size: 0x8 // Offset: 0x20 Mono::Security::Cryptography::KeyPairPersistence* store; // Field size check static_assert(sizeof(Mono::Security::Cryptography::KeyPairPersistence*) == 0x8); // private System.Boolean persistKey // Size: 0x1 // Offset: 0x28 bool persistKey; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean persisted // Size: 0x1 // Offset: 0x29 bool persisted; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean privateKeyExportable // Size: 0x1 // Offset: 0x2A bool privateKeyExportable; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean m_disposed // Size: 0x1 // Offset: 0x2B bool m_disposed; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: m_disposed and: rsa char __padding4[0x4] = {}; // private Mono.Security.Cryptography.RSAManaged rsa // Size: 0x8 // Offset: 0x30 Mono::Security::Cryptography::RSAManaged* rsa; // Field size check static_assert(sizeof(Mono::Security::Cryptography::RSAManaged*) == 0x8); // Creating value type constructor for type: RSACryptoServiceProvider RSACryptoServiceProvider(Mono::Security::Cryptography::KeyPairPersistence* store_ = {}, bool persistKey_ = {}, bool persisted_ = {}, bool privateKeyExportable_ = {}, bool m_disposed_ = {}, Mono::Security::Cryptography::RSAManaged* rsa_ = {}) noexcept : store{store_}, persistKey{persistKey_}, persisted{persisted_}, privateKeyExportable{privateKeyExportable_}, m_disposed{m_disposed_}, rsa{rsa_} {} // Get static field: static private System.Security.Cryptography.CspProviderFlags s_UseMachineKeyStore static System::Security::Cryptography::CspProviderFlags _get_s_UseMachineKeyStore(); // Set static field: static private System.Security.Cryptography.CspProviderFlags s_UseMachineKeyStore static void _set_s_UseMachineKeyStore(System::Security::Cryptography::CspProviderFlags value); // static public System.Boolean get_UseMachineKeyStore() // Offset: 0x1AC9500 static bool get_UseMachineKeyStore(); // static private System.Int32 GetAlgorithmId(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) // Offset: 0x1AC95AC static int GetAlgorithmId(System::Security::Cryptography::HashAlgorithmName hashAlgorithm); // static private System.Exception PaddingModeNotSupported() // Offset: 0x1AC9970 static System::Exception* PaddingModeNotSupported(); // public System.Void .ctor(System.Security.Cryptography.CspParameters parameters) // Offset: 0x1AC9AC8 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RSACryptoServiceProvider* New_ctor(System::Security::Cryptography::CspParameters* parameters) { static auto ___internal__logger = ::Logger::get().WithContext("System::Security::Cryptography::RSACryptoServiceProvider::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RSACryptoServiceProvider*, creationType>(parameters))); } // public System.Void .ctor(System.Int32 dwKeySize) // Offset: 0x1AC9A8C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RSACryptoServiceProvider* New_ctor(int dwKeySize) { static auto ___internal__logger = ::Logger::get().WithContext("System::Security::Cryptography::RSACryptoServiceProvider::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RSACryptoServiceProvider*, creationType>(dwKeySize))); } // public System.Void .ctor(System.Int32 dwKeySize, System.Security.Cryptography.CspParameters parameters) // Offset: 0x1AC9AD4 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RSACryptoServiceProvider* New_ctor(int dwKeySize, System::Security::Cryptography::CspParameters* parameters) { static auto ___internal__logger = ::Logger::get().WithContext("System::Security::Cryptography::RSACryptoServiceProvider::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RSACryptoServiceProvider*, creationType>(dwKeySize, parameters))); } // private System.Void Common(System.Int32 dwKeySize, System.Boolean parameters) // Offset: 0x1AC9B40 void Common(int dwKeySize, bool parameters); // private System.Void Common(System.Security.Cryptography.CspParameters p) // Offset: 0x1AC9D1C void Common(System::Security::Cryptography::CspParameters* p); // public System.Boolean get_PublicOnly() // Offset: 0x1AC9ECC bool get_PublicOnly(); // static private System.Security.Cryptography.HashAlgorithm InternalHashToHashAlgorithm(System.Int32 calgHash) // Offset: 0x1ACA0F4 static System::Security::Cryptography::HashAlgorithm* InternalHashToHashAlgorithm(int calgHash); // private System.Boolean VerifyHash(System.Byte[] rgbHash, System.Int32 calgHash, System.Byte[] rgbSignature) // Offset: 0x1AC99EC bool VerifyHash(::Array<uint8_t>* rgbHash, int calgHash, ::Array<uint8_t>* rgbSignature); // private System.Void OnKeyGenerated(System.Object sender, System.EventArgs e) // Offset: 0x1ACA394 void OnKeyGenerated(::Il2CppObject* sender, System::EventArgs* e); // protected override System.Byte[] HashData(System.Byte[] data, System.Int32 offset, System.Int32 count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) // Offset: 0x1AC955C // Implemented from: System.Security.Cryptography.RSA // Base method: System.Byte[] RSA::HashData(System.Byte[] data, System.Int32 offset, System.Int32 count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) ::Array<uint8_t>* HashData(::Array<uint8_t>* data, int offset, int count, System::Security::Cryptography::HashAlgorithmName hashAlgorithm); // public override System.Boolean VerifyHash(System.Byte[] hash, System.Byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) // Offset: 0x1AC9728 // Implemented from: System.Security.Cryptography.RSA // Base method: System.Boolean RSA::VerifyHash(System.Byte[] hash, System.Byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) bool VerifyHash(::Array<uint8_t>* hash, ::Array<uint8_t>* signature, System::Security::Cryptography::HashAlgorithmName hashAlgorithm, System::Security::Cryptography::RSASignaturePadding* padding); // public System.Void .ctor() // Offset: 0x1AC85C4 // Implemented from: System.Security.Cryptography.RSA // Base method: System.Void RSA::.ctor() // Base method: System.Void AsymmetricAlgorithm::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RSACryptoServiceProvider* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Security::Cryptography::RSACryptoServiceProvider::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RSACryptoServiceProvider*, creationType>())); } // protected override System.Void Finalize() // Offset: 0x1AC9E38 // Implemented from: System.Object // Base method: System.Void Object::Finalize() void Finalize(); // public override System.Int32 get_KeySize() // Offset: 0x1AC9EAC // Implemented from: System.Security.Cryptography.AsymmetricAlgorithm // Base method: System.Int32 AsymmetricAlgorithm::get_KeySize() int get_KeySize(); // public override System.Byte[] EncryptValue(System.Byte[] rgb) // Offset: 0x1AC9EE8 // Implemented from: System.Security.Cryptography.RSA // Base method: System.Byte[] RSA::EncryptValue(System.Byte[] rgb) ::Array<uint8_t>* EncryptValue(::Array<uint8_t>* rgb); // public override System.Security.Cryptography.RSAParameters ExportParameters(System.Boolean includePrivateParameters) // Offset: 0x1AC9F0C // Implemented from: System.Security.Cryptography.RSA // Base method: System.Security.Cryptography.RSAParameters RSA::ExportParameters(System.Boolean includePrivateParameters) System::Security::Cryptography::RSAParameters ExportParameters(bool includePrivateParameters); // public override System.Void ImportParameters(System.Security.Cryptography.RSAParameters parameters) // Offset: 0x1ACA09C // Implemented from: System.Security.Cryptography.RSA // Base method: System.Void RSA::ImportParameters(System.Security.Cryptography.RSAParameters parameters) void ImportParameters(System::Security::Cryptography::RSAParameters parameters); // protected override System.Void Dispose(System.Boolean disposing) // Offset: 0x1ACA334 // Implemented from: System.Security.Cryptography.AsymmetricAlgorithm // Base method: System.Void AsymmetricAlgorithm::Dispose(System.Boolean disposing) void Dispose(bool disposing); }; // System.Security.Cryptography.RSACryptoServiceProvider #pragma pack(pop) static check_size<sizeof(RSACryptoServiceProvider), 48 + sizeof(Mono::Security::Cryptography::RSAManaged*)> __System_Security_Cryptography_RSACryptoServiceProviderSizeCheck; static_assert(sizeof(RSACryptoServiceProvider) == 0x38); } DEFINE_IL2CPP_ARG_TYPE(System::Security::Cryptography::RSACryptoServiceProvider*, "System.Security.Cryptography", "RSACryptoServiceProvider");
58.59901
403
0.741235
[ "object" ]
abcc23c5b0a5fbc0cc377abbf20670f7b338e80c
6,786
cpp
C++
engine/source/engine/ecs/component-systems/Body3DComSys.cpp
yhyu13/Engine2021
6ded548caa45bf980d88e09bed59431b61f5337e
[ "MIT" ]
null
null
null
engine/source/engine/ecs/component-systems/Body3DComSys.cpp
yhyu13/Engine2021
6ded548caa45bf980d88e09bed59431b61f5337e
[ "MIT" ]
null
null
null
engine/source/engine/ecs/component-systems/Body3DComSys.cpp
yhyu13/Engine2021
6ded548caa45bf980d88e09bed59431b61f5337e
[ "MIT" ]
null
null
null
#include "engine-precompiled-header.h" #include "Body3DComSys.h" #include "Scene3DComSys.h" #include "engine/events/engineEvents/EngineCustomEvent.h" longmarch::Body3DComSys::Body3DComSys() { m_systemSignature.AddComponent<Transform3DCom>(); m_systemSignature.AddComponent<Body3DCom>(); } longmarch::Body3DComSys::~Body3DComSys() { PhysicsManager::GetInstance()->DeleteScene(m_scene); } void longmarch::Body3DComSys::Init() { { auto queue = EventQueue<EngineEventType>::GetInstance(); ManageEventSubHandle(queue->Subscribe<Body3DComSys>(this, EngineEventType::GC, &Body3DComSys::_ON_GC)); ManageEventSubHandle(queue->Subscribe<Body3DComSys>(this, EngineEventType::GC_RECURSIVE, &Body3DComSys::_ON_GC_RECURSIVE)); } // store ptr to physics manager for updating bodies if (!m_scene) { m_scene = PhysicsManager::GetInstance()->CreateScene(); const auto& engineConfiguration = FileSystem::GetCachedJsonCPP("$root:engine-config.json"); if (auto& gravity = engineConfiguration["physics"]["gravity"]; !gravity.isNull()) { m_scene->SetGravity(Vec3f(gravity[0].asFloat(), gravity[1].asFloat(), gravity[2].asFloat())); } else { m_scene->SetGravity(Vec3f(0, 0, -9.8)); } } else { PhysicsManager::GetInstance()->AddScene(m_scene); } m_scene->SetGameWorld(m_parentWorld); } void longmarch::Body3DComSys::PreRenderUpdate(double dt) { EARLY_RETURN(dt); /************************************************************** * Initialize bounding volume **************************************************************/ /* The reason to only init BV here is because PreRenderUpdate() is always called after all Update() are finished, inlcuding the creation of entities in this frame. So we are guranteed that the bounding volume could be initialized before it is rendered. Seocondly, an optional optimization in the MeshData class would destory all vertices data after data has been transfered to the GPU. So we need to initialze the bounding volume before it is rendered. */ auto entities = m_bufferedRegisteredEntities; ParEach( [this](EntityDecorator e) { // Generate view frustum culling BV if possible auto scene = e.GetComponent<Scene3DCom>(); auto body = e.GetComponent<Body3DCom>(); auto trans = e.GetComponent<Transform3DCom>(); if (auto bv = body->GetBoundingVolume(); !bv) { if (scene.Valid()) { if (const auto& data = scene->GetSceneData(false); data) { auto& meshes = data->GetAllMesh(); body->CreateBoundingVolume<AABB>(meshes); body->GetBoundingVolume()->SetOwnerEntity(e); } } } if (auto bv = body->GetBoundingVolume(); bv) { // Update view frustum culling BV bv->SetModelTrAndUpdate(trans->GetModelTr()); } // check to see if there is a corresponding rigid body in the scene, if not then assign one and update with body info if (!body->HasRigidBody() && body->m_bodyInfo.type != RBType::noCollision) { // Generate rigid body BV if possible auto body = e.GetComponent<Body3DCom>(); auto trans = e.GetComponent<Transform3DCom>(); if (auto aabbPtr = std::dynamic_pointer_cast<AABB>(body->GetBoundingVolume()); aabbPtr) { std::shared_ptr<RigidBody> newRB = m_scene->CreateRigidBody(); switch (body->m_bodyInfo.type) { case RBType::dynamicBody: { newRB->SetAwake(); newRB->SetRBType(RBType::dynamicBody); newRB->SetMass(body->m_bodyInfo.mass); } break; case RBType::staticBody: { newRB->SetRBType(RBType::staticBody); newRB->SetMass(1e8); } break; default: ENGINE_EXCEPT(L"Logic error!"); break; } newRB->SetFriction(body->m_bodyInfo.friction); newRB->SetRestitution(body->m_bodyInfo.restitution); newRB->SetLinearDamping(body->m_bodyInfo.linearDamping); const float scale = body->m_bodyInfo.colliderDimensionExtent; newRB->SetAABBShape(aabbPtr->GetOriginalMin() * scale, aabbPtr->GetOriginalMax() * scale); newRB->SetEntity(e.GetEntity()); newRB->m_entityTypeIngoreSet.AddIndex(body->m_bodyInfo.entityTypeIngoreSet); body->AssignRigidBody(newRB); } } if (body->HasRigidBody()) { // Update rigid body BV // Assign transformCom to rigid body body->m_body->SetRBTrans(trans->GetModelTr()); body->m_body->SetLinearVelocity(trans->GetGlobalVel()); body->UpdateBody3DCom(); body->UpdateRigidBody(); } } ).wait(); } void longmarch::Body3DComSys::Update(double dt) { EARLY_RETURN(dt); // Update physical scene here instead from PhysicsManager if (m_scene->IsUpdateEnabled()) { m_scene->Step(dt); } ParEach( [this](EntityDecorator e) { auto body = e.GetComponent<Body3DCom>(); auto trans = e.GetComponent<Transform3DCom>(); if (body->HasRigidBody()) { // Assign simulated rigid body back to transformCom const RBTransform& rbTrans = body->GetRBTrans(); trans->SetGlobalPos(rbTrans.m_pos); //trans->SetGlobalRot(rbTrans.m_rot); // Rotation is not implemented in the physics engine trans->SetGlobalVel(body->m_body->GetLinearVelocity()); } } ).wait(); } void longmarch::Body3DComSys::Render() { if (m_enableDebugDraw) { // For debugging purposes m_scene->RenderDebug(); } } std::shared_ptr<BaseComponentSystem> longmarch::Body3DComSys::Copy() const { LOCK_GUARD_NC(); auto ret = MemoryManager::Make_shared<Body3DComSys>(); ret->m_bufferedRegisteredEntities = m_bufferedRegisteredEntities; // Must copy ret->m_systemSignature = m_systemSignature; // Must copy ret->m_scene = MemoryManager::Make_shared<Scene>(*m_scene); // Custom variables return ret; } void longmarch::Body3DComSys::_ON_GC(EventQueue<EngineEventType>::EventPtr e) { LOCK_GUARD_NC(); auto event = std::static_pointer_cast<EngineGCEvent>(e); if (event->m_entity.Valid() && m_parentWorld == event->m_entity.GetWorld()) { if (auto body = event->m_entity.GetComponent<Body3DCom>(); body.Valid()) { m_scene->RemoveRigidBody(body->m_body); } } } void longmarch::Body3DComSys::_ON_GC_RECURSIVE(EventQueue<EngineEventType>::EventPtr e) { LOCK_GUARD_NC(); auto event = std::static_pointer_cast<EngineGCRecursiveEvent>(e); if (event->m_entity.Valid() && m_parentWorld == event->m_entity.GetWorld()) { GCRecursive(event->m_entity); } } void longmarch::Body3DComSys::GCRecursive(EntityDecorator e) { if (auto body = e.GetComponent<Body3DCom>(); body.Valid()) { m_scene->RemoveRigidBody(body->m_body); } for (auto& child : m_parentWorld->GetComponent<ChildrenCom>(e)->GetChildren()) { GCRecursive(EntityDecorator{ child ,e.GetWorld() }); } }
31.562791
154
0.679045
[ "render" ]
abd0dd254ea7b61eebd7fe1a39c25069009f4416
3,696
cpp
C++
2020/qualification_round/sol.cpp
divinerecursors/hashcode
f48ecae0378c9969811f5e14f002e60c925fdf03
[ "MIT" ]
null
null
null
2020/qualification_round/sol.cpp
divinerecursors/hashcode
f48ecae0378c9969811f5e14f002e60c925fdf03
[ "MIT" ]
null
null
null
2020/qualification_round/sol.cpp
divinerecursors/hashcode
f48ecae0378c9969811f5e14f002e60c925fdf03
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <sstream> #include <fstream> #include <string> #include <algorithm> using namespace std; vector<string> split(const string& s, char delimiter) { vector<string> tokens; string token; istringstream tokenStream(s); while (getline(tokenStream, token, delimiter)){ tokens.push_back(token); } return tokens; } vector<string> readFile(string filename){ vector<string> data; ifstream fin; fin.open(filename); string line; while(fin){ getline(fin, line); data.push_back(line); } return data; } typedef struct LIB_S { int64_t index; //original index of library obtained from input int64_t n; // no of books in lib int64_t m; // the number of books that can be shipped from library int64_t t; // the number of days it takes to finish the library signup process vector<vector<int64_t>> id_and_scores; //list of (id, scores) } library; bool ascend(const library& p1, const library& p2) { return p1.t < p2.t; } bool descend(const vector<int64_t>& p1, vector<int64_t>& p2) { return p1[1] > p2[1]; } int main(){ string filename = "input_data/b_read_on.txt"; vector<string> file_data = readFile(filename); vector<string> scores_string_arr = split(file_data[1], ' '); int64_t no_of_books, no_of_libs, days; no_of_books = atoi(split(file_data[0], ' ')[0].c_str()); no_of_libs = atoi(split(file_data[0],' ')[1].c_str()); days = atoi(split(file_data[0], ' ')[2].c_str()); int64_t* scores = new int64_t[no_of_books]; // scores of books for(int64_t i=0; i<no_of_books; i++){ scores[i] = atoi(scores_string_arr[i].c_str()); } library library_structure[no_of_libs]; // the library structure for(int64_t i=0, j=2; i<no_of_libs; i++, j+=2){ vector<string> first_line = split(file_data[j], ' '); vector<string> second_line = split(file_data[j+1], ' '); library_structure[i].index = i; library_structure[i].n = atoi(first_line[0].c_str()); library_structure[i].t = atoi(first_line[1].c_str()); library_structure[i].m = atoi(first_line[2].c_str()); for(string book: second_line){ vector<int64_t> k; k.push_back(atoi(book.c_str())); k.push_back(scores[atoi(book.c_str())]); library_structure[i].id_and_scores.push_back(k); } } sort(library_structure,library_structure+no_of_libs,ascend); for(int64_t i=0;i<no_of_libs;i++){ sort(library_structure[i].id_and_scores.begin(),library_structure[i].id_and_scores.end(),descend); } int64_t n=0; int64_t x; for(x=0;x<=no_of_libs;x++){ if(n<days){ n=n+library_structure[x].t; } else{ break; } } int64_t sum=0; x--; for(int64_t i=0;i<x;i++){ sum=sum+library_structure[i].t; if(days-sum <= 0) break; cout << library_structure[i].index <<' '; if (library_structure[i].n>((days-sum)*library_structure[i].m)) { cout<<(days-sum)*library_structure[i].m<<endl; for(int64_t k=0;k<(days-sum)*library_structure[i].m;k++){ cout << library_structure[i].id_and_scores[k][0]<<' '; } cout<<endl; } else { cout<<library_structure[i].n <<endl; for(auto k: library_structure[i].id_and_scores) cout << k[0] << ' '; cout<<endl; /* code */ } } return 0; }
25.666667
106
0.579545
[ "vector" ]
abd1de7464b88283f8cf10b27dac33ec6693e219
36,813
cc
C++
sandboxed_api/sandbox2/monitor.cc
disconnect3d/sandboxed-api
177b969e8cf96b6254fa9195e4c501dc12a82de9
[ "Apache-2.0" ]
null
null
null
sandboxed_api/sandbox2/monitor.cc
disconnect3d/sandboxed-api
177b969e8cf96b6254fa9195e4c501dc12a82de9
[ "Apache-2.0" ]
null
null
null
sandboxed_api/sandbox2/monitor.cc
disconnect3d/sandboxed-api
177b969e8cf96b6254fa9195e4c501dc12a82de9
[ "Apache-2.0" ]
1
2019-11-29T06:42:02.000Z
2019-11-29T06:42:02.000Z
// Copyright 2019 Google LLC. 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. // Implementation file for the sandbox2::Monitor class. #include "sandboxed_api/sandbox2/monitor.h" #include <linux/posix_types.h> // NOLINT: Needs to come before linux/ipc.h #include <linux/ipc.h> #include <sched.h> #include <sys/mman.h> #include <sys/ptrace.h> #include <sys/time.h> #include <sys/wait.h> #include <syscall.h> #include <unistd.h> #include <algorithm> #include <atomic> #include <cerrno> #include <csignal> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <memory> #include <set> #include <sstream> #include <string> #include <glog/logging.h> #include "sandboxed_api/util/flag.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" #include "sandboxed_api/sandbox2/client.h" #include "sandboxed_api/sandbox2/comms.h" #include "sandboxed_api/sandbox2/executor.h" #include "sandboxed_api/sandbox2/limits.h" #include "sandboxed_api/sandbox2/mounts.h" #include "sandboxed_api/sandbox2/namespace.h" #include "sandboxed_api/sandbox2/policy.h" #include "sandboxed_api/sandbox2/regs.h" #include "sandboxed_api/sandbox2/result.h" #include "sandboxed_api/sandbox2/sanitizer.h" #include "sandboxed_api/sandbox2/stack-trace.h" #include "sandboxed_api/sandbox2/syscall.h" #include "sandboxed_api/sandbox2/util.h" ABSL_FLAG(bool, sandbox2_report_on_sandboxee_signal, true, "Report sandbox2 sandboxee deaths caused by signals"); ABSL_FLAG(bool, sandbox2_report_on_sandboxee_timeout, true, "Report sandbox2 sandboxee timeouts"); ABSL_DECLARE_FLAG(bool, sandbox2_danger_danger_permit_all); ABSL_DECLARE_FLAG(string, sandbox2_danger_danger_permit_all_and_log); namespace sandbox2 { namespace { // We could use the ProcMapsIterator, however we want the full file content. std::string ReadProcMaps(pid_t pid) { std::ifstream input(absl::StrCat("/proc/", pid, "/maps"), std::ios_base::in | std::ios_base::binary); std::ostringstream contents; contents << input.rdbuf(); return contents.str(); } } // namespace Monitor::Monitor(Executor* executor, Policy* policy, Notify* notify) : executor_(executor), notify_(notify), policy_(policy), comms_(executor_->ipc()->comms()), ipc_(executor_->ipc()), setup_counter_(new absl::BlockingCounter(1)), done_(false), wait_for_execve_(executor->enable_sandboxing_pre_execve_) { std::string path = absl::GetFlag(FLAGS_sandbox2_danger_danger_permit_all_and_log); if (!path.empty()) { log_file_ = std::fopen(path.c_str(), "a+"); PCHECK(log_file_ != nullptr) << "Failed to open log file '" << path << "'"; } } Monitor::~Monitor() { CleanUpTimer(); if (log_file_) { std::fclose(log_file_); } } void Monitor::Run() { using DecrementCounter = decltype(setup_counter_); std::unique_ptr<DecrementCounter, std::function<void(DecrementCounter*)>> decrement_count{&setup_counter_, [](DecrementCounter* counter) { (*counter)->DecrementCount(); }}; struct MonitorCleanup { ~MonitorCleanup() { getrusage(RUSAGE_THREAD, capture->result_.GetRUsageMonitor()); capture->notify_->EventFinished(capture->result_); capture->ipc_->InternalCleanupFdMap(); absl::MutexLock lock(&capture->done_mutex_); capture->done_.store(true, std::memory_order_release); } Monitor* capture; } monitor_cleanup{this}; if (!InitSetupTimer()) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_TIMERS); return; } // It'd be costly to initialize the sigset_t for each sigtimedwait() // invocation, so do it once per Monitor. sigset_t sigtimedwait_sset; if (!InitSetupSignals(&sigtimedwait_sset)) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_SIGNALS); return; } // Don't trace the child: it will allow to use 'strace -f' with the whole // sandbox master/monitor, which ptrace_attach'es to the child. int clone_flags = CLONE_UNTRACED; // Get PID of the sandboxee. pid_t init_pid = 0; pid_ = executor_->StartSubProcess(clone_flags, policy_->GetNamespace(), policy_->GetCapabilities(), &init_pid); if (init_pid < 0) { // TODO(hamacher): does this require additional handling here? LOG(ERROR) << "Spawning init process failed"; } else if (init_pid > 0) { PCHECK(ptrace(PTRACE_SEIZE, init_pid, 0, PTRACE_O_EXITKILL) == 0); } if (pid_ < 0) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_SUBPROCESS); return; } if (!notify_->EventStarted(pid_, comms_)) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_NOTIFY); return; } if (!InitAcceptConnection()) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_CONNECTION); return; } if (!InitSendIPC()) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_IPC); return; } if (!InitSendCwd()) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_CWD); return; } if (!InitSendPolicy()) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_POLICY); return; } if (!WaitForSandboxReady()) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_WAIT); return; } if (!InitApplyLimits()) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_LIMITS); return; } // This call should be the last in the init sequence, because it can cause the // sandboxee to enter ptrace-stopped state, in which it will not be able to // send any messages over the Comms channel. if (!InitPtraceAttach()) { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_PTRACE); return; } // Tell the parent thread (Sandbox2 object) that we're done with the initial // set-up process of the sandboxee. decrement_count.reset(); MainLoop(&sigtimedwait_sset); // Disarm the timer: it will be deleted in ~Monitor, but the Monitor object // lifetime is controlled by owner of Sandbox2, and we don't want to leave any // timers behind (esp. armed ones) in the meantime. TimerArm(absl::ZeroDuration()); } bool Monitor::IsActivelyMonitoring() { // If we're still waiting for execve(), then we allow all syscalls. return !wait_for_execve_; } void Monitor::SetActivelyMonitoring() { wait_for_execve_ = false; } void Monitor::MainSignals(int signo, siginfo_t* si) { VLOG(3) << "Signal '" << strsignal(signo) << "' (" << signo << ") received from PID: " << si->si_pid; // SIGCHLD is received frequently due to ptrace() events being sent by child // processes; return early to avoid costly syscalls. if (signo == SIGCHLD) { return; } // We should only receive signals from the same process (thread group). Other // signals are suspicious (esp. if coming from a sandboxed process) Using // syscall(__NR_getpid) here because getpid() is cached in glibc, and it // might return previous pid if bare syscall(__NR_fork) was used instead of // fork(). // // The notable exception are signals caused by timer_settime which are sent // by the kernel. if (signo != Monitor::kTimerWallTimeSignal && si->si_pid != util::Syscall(__NR_getpid)) { LOG(ERROR) << "Monitor received signal '" << strsignal(signo) << "' (" << signo << ") from PID " << si->si_pid << " which is not in the current thread group"; return; } switch (signo) { case Monitor::kExternalKillSignal: VLOG(1) << "Will kill the main pid"; ActionProcessKill(pid_, Result::EXTERNAL_KILL, 0); break; case Monitor::kTimerWallTimeSignal: VLOG(1) << "Sandbox process hit timeout due to the walltime timer"; ActionProcessKill(pid_, Result::TIMEOUT, 0); break; case Monitor::kTimerSetSignal: VLOG(1) << "Will set the walltime timer to " << si->si_value.sival_int << " seconds"; TimerArm(absl::Seconds(si->si_value.sival_int)); break; case Monitor::kDumpStackSignal: VLOG(1) << "Dump the main pid's stack"; should_dump_stack_ = true; PidInterrupt(pid_); break; default: LOG(ERROR) << "Unknown signal received: " << signo; break; } } // Not defined in glibc. #define __WPTRACEEVENT(x) ((x & 0xff0000) >> 16) bool Monitor::MainWait() { // All possible process status change event must be checked as SIGCHLD // is reported once only for all events that arrived at the same time. for (;;) { int status; // It should be a non-blocking operation (hence WNOHANG), so this function // returns quickly if there are no events to be processed. int ret = waitpid(-1, &status, __WNOTHREAD | __WALL | WUNTRACED | WNOHANG); // No traced processes have changed their status yet. if (ret == 0) { return false; } if (ret == -1 && errno == ECHILD) { LOG(ERROR) << "PANIC(). The main process has not exited yet, " << "yet we haven't seen its exit event"; // We'll simply exit which will kill all remaining processes (if // there are any) because of the PTRACE_O_EXITKILL ptrace() flag. return true; } if (ret == -1 && errno == EINTR) { VLOG(3) << "waitpid() interruped with EINTR"; continue; } if (ret == -1) { PLOG(ERROR) << "waitpid() failed"; continue; } VLOG(3) << "waitpid() returned with PID: " << ret << ", status: " << status; if (WIFEXITED(status)) { VLOG(1) << "PID: " << ret << " finished with code: " << WEXITSTATUS(status); // That's the main process, set the exit code, and exit. It will kill // all remaining processes (if there are any) because of the // PTRACE_O_EXITKILL ptrace() flag. if (ret == pid_) { if (IsActivelyMonitoring()) { result_.SetExitStatusCode(Result::OK, WEXITSTATUS(status)); } else { result_.SetExitStatusCode(Result::SETUP_ERROR, Result::FAILED_MONITOR); } return true; } } else if (WIFSIGNALED(status)) { VLOG(1) << "PID: " << ret << " terminated with signal: " << util::GetSignalName(WTERMSIG(status)); if (ret == pid_) { // That's the main process, depending on the result of the process take // the register content and/or the stack trace. The death of this // process will cause all remaining processes to be killed (if there are // any), see the PTRACE_O_EXITKILL ptrace() flag. // When the process is killed from a signal from within the result // status will be still unset, fix this. // The other cases should either be already handled, or (in the case of // Result::OK) should be impossible to reach. if (result_.final_status() == Result::UNSET) { result_.SetExitStatusCode(Result::SIGNALED, WTERMSIG(status)); } else if (result_.final_status() == Result::OK) { LOG(ERROR) << "Unexpected codepath taken"; } return true; } } else if (WIFSTOPPED(status)) { VLOG(2) << "PID: " << ret << " received signal: " << util::GetSignalName(WSTOPSIG(status)) << " with event: " << __WPTRACEEVENT(status); StateProcessStopped(ret, status); } else if (WIFCONTINUED(status)) { VLOG(2) << "PID: " << ret << " is being continued"; } } } void Monitor::MainLoop(sigset_t* sset) { for (;;) { // Use a time-out, so we can check for missed waitpid() events. It should // not happen during regular operations, so it's a defense-in-depth // mechanism against SIGCHLD signals being lost by the kernel (since these // are not-RT signals - i.e. not queued). static const timespec ts = {kWakeUpPeriodSec, kWakeUpPeriodNSec}; // Wait for any kind of events, e.g. signals sent from the parent process, // or SIGCHLD sent by kernel indicating that state of one of the traced // processes has changed. siginfo_t si; int ret = sigtimedwait(sset, &si, &ts); if (ret > 0) { // Process signals which arrived. MainSignals(ret, &si); } // If CheckWait reported no more traced processes, or that // the main pid had exited, we should break this loop (i.e. our job is // done here). // // MainWait() should use a not-blocking (e.g. WNOHANG with waitpid()) // syntax, so it returns quickly if there are not status changes in // traced processes. if (MainWait()) { return; } } } bool Monitor::InitSetupTimer() { walltime_timer_ = absl::make_unique<timer_t>(); // Set the wall-time timer. sigevent sevp; sevp.sigev_value.sival_ptr = walltime_timer_.get(); sevp.sigev_signo = kTimerWallTimeSignal; sevp.sigev_notify = SIGEV_THREAD_ID | SIGEV_SIGNAL; sevp._sigev_un._tid = static_cast<pid_t>(util::Syscall(__NR_gettid)); // GLibc's implementation seem to mis-behave during timer_delete, as it's // trying to find out whether POSIX TIMERs are available. So, we stick to // syscalls for this class of calls. if (util::Syscall(__NR_timer_create, CLOCK_REALTIME, reinterpret_cast<uintptr_t>(&sevp), reinterpret_cast<uintptr_t>(walltime_timer_.get())) == -1) { walltime_timer_ = nullptr; PLOG(ERROR) << "timer_create(CLOCK_REALTIME, walltime_timer_)"; return false; } return TimerArm(executor_->limits()->wall_time_limit()); } // Can be used from a signal handler. Avoid non-reentrant functions. bool Monitor::TimerArm(absl::Duration duration) { VLOG(2) << (duration == absl::ZeroDuration() ? "Disarming" : "Arming") << " the walltime timer with " << absl::FormatDuration(duration); itimerspec ts; absl::Duration rem; ts.it_value.tv_sec = absl::IDivDuration(duration, absl::Seconds(1), &rem); ts.it_value.tv_nsec = absl::ToInt64Nanoseconds(rem); ts.it_interval.tv_sec = duration != absl::ZeroDuration() ? 1L : 0L; // Re-fire every 1 sec. ts.it_interval.tv_nsec = 0UL; itimerspec* null_ts = nullptr; if (util::Syscall(__NR_timer_settime, reinterpret_cast<uintptr_t>(*walltime_timer_), 0, reinterpret_cast<uintptr_t>(&ts), reinterpret_cast<uintptr_t>(null_ts)) == -1) { PLOG(ERROR) << "timer_settime(): time: " << absl::FormatDuration(duration); return false; } return true; } void Monitor::CleanUpTimer() { if (walltime_timer_) { if (util::Syscall(__NR_timer_delete, reinterpret_cast<uintptr_t>(*walltime_timer_)) == -1) { PLOG(ERROR) << "timer_delete()"; } } } bool Monitor::InitSetupSig(int signo, sigset_t* sset) { // sigtimedwait will react (wake-up) to arrival of this signal. sigaddset(sset, signo); // Block this specific signal, so only sigtimedwait reacts to it. sigset_t block_set; if (sigemptyset(&block_set) == -1) { PLOG(ERROR) << "sigemptyset()"; return false; } if (sigaddset(&block_set, signo) == -1) { PLOG(ERROR) << "sigaddset(" << signo << ")"; return false; } if (pthread_sigmask(SIG_BLOCK, &block_set, nullptr) == -1) { PLOG(ERROR) << "pthread_sigmask(SIG_BLOCK, " << signo << ")"; return false; } return true; } bool Monitor::InitSetupSignals(sigset_t* sset) { sigemptyset(sset); return Monitor::InitSetupSig(kExternalKillSignal, sset) && Monitor::InitSetupSig(kTimerWallTimeSignal, sset) && Monitor::InitSetupSig(kTimerSetSignal, sset) && Monitor::InitSetupSig(kDumpStackSignal, sset) && // SIGCHLD means that a new children process status change event // has been delivered (e.g. due ptrace notification). Monitor::InitSetupSig(SIGCHLD, sset); } bool Monitor::InitSendPolicy() { if (!policy_->SendPolicy(comms_)) { LOG(ERROR) << "Couldn't send policy"; return false; } return true; } bool Monitor::InitSendCwd() { if (!comms_->SendString(executor_->cwd_)) { PLOG(ERROR) << "Couldn't send cwd"; return false; } return true; } bool Monitor::InitApplyLimit(pid_t pid, __rlimit_resource resource, const rlimit64& rlim) const { std::string rlim_name = absl::StrCat("UNKNOWN: ", resource); switch (resource) { case RLIMIT_AS: rlim_name = "RLIMIT_AS"; break; case RLIMIT_FSIZE: rlim_name = "RLIMIT_FSIZE"; break; case RLIMIT_NOFILE: rlim_name = "RLIMIT_NOFILE"; break; case RLIMIT_CPU: rlim_name = "RLIMIT_CPU"; break; case RLIMIT_CORE: rlim_name = "RLIMIT_CORE"; break; default: break; } rlimit64 curr_limit; if (prlimit64(pid, resource, nullptr, &curr_limit) == -1) { PLOG(ERROR) << "prlimit64(" << pid << ", " << rlim_name << ")"; } else { // In such case, don't update the limits, as it will fail. Just stick to the // current ones (which are already lower than intended). if (rlim.rlim_cur > curr_limit.rlim_max) { LOG(ERROR) << rlim_name << ": new.current > current.max (" << rlim.rlim_cur << " > " << curr_limit.rlim_max << "), skipping"; return true; } } if (prlimit64(pid, resource, &rlim, nullptr) == -1) { PLOG(ERROR) << "prlimit64(RLIMIT_AS, " << rlim.rlim_cur << ")"; return false; } return true; } bool Monitor::InitApplyLimits() { Limits* limits = executor_->limits(); return InitApplyLimit(pid_, RLIMIT_AS, limits->rlimit_as()) && InitApplyLimit(pid_, RLIMIT_CPU, limits->rlimit_cpu()) && InitApplyLimit(pid_, RLIMIT_FSIZE, limits->rlimit_fsize()) && InitApplyLimit(pid_, RLIMIT_NOFILE, limits->rlimit_nofile()) && InitApplyLimit(pid_, RLIMIT_CORE, limits->rlimit_core()); } bool Monitor::InitSendIPC() { return ipc_->SendFdsOverComms(); } bool Monitor::WaitForSandboxReady() { uint32_t tmp; if (!comms_->RecvUint32(&tmp)) { LOG(ERROR) << "Couldn't receive 'Client::kClient2SandboxReady' message"; return false; } if (tmp != Client::kClient2SandboxReady) { LOG(ERROR) << "Received " << tmp << " != Client::kClient2SandboxReady (" << Client::kClient2SandboxReady << ")"; return false; } return true; } bool Monitor::InitPtraceAttach() { sanitizer::WaitForTsan(); // Get a list of tasks. std::set<int> tasks; if (!sanitizer::GetListOfTasks(pid_, &tasks)) { LOG(ERROR) << "Could not get list of tasks"; return false; } // With TSYNC, we can allow threads: seccomp applies to all threads. if (tasks.size() > 1) { LOG(WARNING) << "PID " << pid_ << " has " << tasks.size() << " threads," << " at the time of call to SandboxMeHere. If you are seeing" << " more sandbox violations than expected, this might be" << " the reason why" << "."; } intptr_t ptrace_opts = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEVFORKDONE | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXEC | PTRACE_O_TRACEEXIT | PTRACE_O_TRACESECCOMP | PTRACE_O_EXITKILL; bool main_pid_found = false; for (auto task : tasks) { if (task == pid_) { main_pid_found = true; } // In some situations we allow ptrace to try again when it fails. bool ptrace_succeeded = false; int retries = 0; auto deadline = absl::Now() + absl::Seconds(2); while (absl::Now() < deadline) { int ret = ptrace(PTRACE_SEIZE, task, 0, ptrace_opts); if (ret == 0) { ptrace_succeeded = true; break; } if (ret != 0 && errno == ESRCH) { // A task may have exited since we captured the task list, we will allow // things to continue after we log a warning. PLOG(WARNING) << "ptrace(PTRACE_SEIZE, " << task << ", " << absl::StrCat("0x", absl::Hex(ptrace_opts)) << ") skipping exited task. Continuing with other tasks."; ptrace_succeeded = true; break; } if (ret != 0 && errno == EPERM) { // Sometimes when a task is exiting we can get an EPERM from ptrace. // Let's try again up until the timeout in this situation. PLOG(WARNING) << "ptrace(PTRACE_SEIZE, " << task << ", " << absl::StrCat("0x", absl::Hex(ptrace_opts)) << "), trying again..."; // Exponential Backoff. constexpr auto kInitialRetry = absl::Milliseconds(1); constexpr auto kMaxRetry = absl::Milliseconds(20); const auto retry_interval = kInitialRetry * (1 << std::min(10, retries++)); absl::SleepFor(std::min(retry_interval, kMaxRetry)); continue; } // Any other errno will be considered a failure. PLOG(ERROR) << "ptrace(PTRACE_SEIZE, " << task << ", " << absl::StrCat("0x", absl::Hex(ptrace_opts)) << ") failed."; return false; } if (!ptrace_succeeded) { LOG(ERROR) << "ptrace(PTRACE_SEIZE, " << task << ", " << absl::StrCat("0x", absl::Hex(ptrace_opts)) << ") failed after retrying until the timeout."; return false; } } if (!main_pid_found) { LOG(ERROR) << "The pid " << pid_ << " was not found in its own tasklist."; return false; } // Get a list of tasks after attaching. std::set<int> tasks_after; if (!sanitizer::GetListOfTasks(pid_, &tasks_after)) { LOG(ERROR) << "Could not get list of tasks"; return false; } // Check that no new threads have shown up. Note: tasks_after can have fewer // tasks than before but no new tasks can be added as they would be missing // from the initial task list. if (!std::includes(tasks.begin(), tasks.end(), tasks_after.begin(), tasks_after.end())) { LOG(ERROR) << "The pid " << pid_ << " spawned new threads while we were trying to attach to it."; return false; } // No glibc wrapper for gettid - see 'man gettid'. VLOG(1) << "Monitor (PID: " << getpid() << ", TID: " << util::Syscall(__NR_gettid) << ") attached to PID: " << pid_; // Technically, the sandboxee can be in a ptrace-stopped state right now, // because some signal could have arrived in the meantime. Yet, this // Comms::SendUint32 call shouldn't lock our process, because the underlying // socketpair() channel is buffered, hence it will accept the uint32_t message // no matter what is the current state of the sandboxee, and it will allow for // our process to continue and unlock the sandboxee with the proper ptrace // event handling. if (!comms_->SendUint32(Client::kSandbox2ClientDone)) { LOG(ERROR) << "Couldn't send Client::kSandbox2ClientDone message"; return false; } return true; } bool Monitor::InitAcceptConnection() { // It's a pre-connected Comms channel, no need to accept new connection or // verify the peer (sandboxee). if (comms_->IsConnected()) { return true; } if (!comms_->Accept()) { return false; } // Check whether the PID which has connected to us, is the PID we're // expecting. pid_t cred_pid; uid_t cred_uid; gid_t cred_gid; if (!comms_->RecvCreds(&cred_pid, &cred_uid, &cred_gid)) { LOG(ERROR) << "Couldn't receive credentials"; return false; } if (pid_ != cred_pid) { LOG(ERROR) << "Initial PID (" << pid_ << ") differs from the PID received " << "from the peer (" << cred_pid << ")"; return false; } return true; } void Monitor::ActionProcessContinue(pid_t pid, int signo) { if (ptrace(PTRACE_CONT, pid, 0, signo) == -1) { PLOG(ERROR) << "ptrace(PTRACE_CONT, pid=" << pid << ", sig=" << signo << ")"; } } void Monitor::ActionProcessStop(pid_t pid, int signo) { if (ptrace(PTRACE_LISTEN, pid, 0, signo) == -1) { PLOG(ERROR) << "ptrace(PTRACE_LISTEN, pid=" << pid << ", sig=" << signo << ")"; } } void Monitor::ActionProcessSyscall(Regs* regs, const Syscall& syscall) { // If the sandboxing is not enabled yet, allow the first __NR_execveat. if (syscall.nr() == __NR_execveat && !IsActivelyMonitoring()) { VLOG(1) << "[PERMITTED/BEFORE_EXECVEAT]: " << "SYSCALL ::: PID: " << regs->pid() << ", PROG: '" << util::GetProgName(regs->pid()) << "' : " << syscall.GetDescription(); ActionProcessContinue(regs->pid(), 0); return; } // Notify can decide whether we want to allow this syscall. It could be useful // for sandbox setups in which some syscalls might still need some logging, // but nonetheless be allowed ('permissible syscalls' in sandbox v1). if (notify_->EventSyscallTrap(syscall)) { LOG(WARNING) << "[PERMITTED]: SYSCALL ::: PID: " << regs->pid() << ", PROG: '" << util::GetProgName(regs->pid()) << "' : " << syscall.GetDescription(); ActionProcessContinue(regs->pid(), 0); return; } // TODO(wiktorg): Further clean that up, probably while doing monitor cleanup // log_file_ not null iff FLAGS_sandbox2_danger_danger_permit_all_and_log is // set. if (log_file_) { std::string syscall_description = syscall.GetDescription(); PCHECK(absl::FPrintF(log_file_, "PID: %d %s\n", regs->pid(), syscall_description) >= 0); ActionProcessContinue(regs->pid(), 0); return; } if (absl::GetFlag(FLAGS_sandbox2_danger_danger_permit_all)) { ActionProcessContinue(regs->pid(), 0); return; } ActionProcessSyscallViolation(regs, syscall, kSyscallViolation); } void Monitor::ActionProcessSyscallViolation(Regs* regs, const Syscall& syscall, ViolationType violation_type) { pid_t pid = regs->pid(); LogAccessViolation(syscall); notify_->EventSyscallViolation(syscall, violation_type); result_.SetExitStatusCode(Result::VIOLATION, syscall.nr()); result_.SetSyscall(absl::make_unique<Syscall>(syscall)); // Only get the stacktrace if we are not in the libunwind sandbox (avoid // recursion). if (executor_->libunwind_sbox_for_pid_ == 0 && policy_->GetNamespace()) { if (policy_->collect_stacktrace_on_violation_) { result_.SetStackTrace( GetStackTrace(regs, policy_->GetNamespace()->mounts())); LOG(ERROR) << "Stack trace: " << result_.GetStackTrace(); } else { LOG(ERROR) << "Stack traces have been disabled"; } } // We make the result object create its own Reg instance. our regs is a // pointer to a stack variable which might not live long enough. result_.LoadRegs(pid); result_.SetProgName(util::GetProgName(pid)); result_.SetProcMaps(ReadProcMaps(pid_)); // Rewrite the syscall argument to something invalid (-1). The process will // be killed by ActionProcessKill(), so this is just a precaution. auto status = regs->SkipSyscallReturnValue(-ENOSYS); if (!status.ok()) { LOG(ERROR) << status; } ActionProcessKill(pid, Result::VIOLATION, syscall.nr()); } void Monitor::LogAccessViolation(const Syscall& syscall) { // Do not unwind libunwind. if (executor_->libunwind_sbox_for_pid_ != 0) { LOG(ERROR) << "Sandbox violation during execution of libunwind: " << syscall.GetDescription(); return; } uintptr_t syscall_nr = syscall.nr(); uintptr_t arg0 = syscall.args()[0]; // So, this is an invalid syscall. Will be killed by seccomp-bpf policies as // well, but we should be on a safe side here as well. LOG(ERROR) << "SANDBOX VIOLATION : PID: " << syscall.pid() << ", PROG: '" << util::GetProgName(syscall.pid()) << "' : " << syscall.GetDescription(); // This follows policy in Policy::GetDefaultPolicy - keep it in sync. if (syscall.arch() != Syscall::GetHostArch()) { LOG(ERROR) << "This is a violation because the syscall was issued because the" << " sandboxee and executor architectures are different."; return; } if (syscall_nr == __NR_ptrace) { LOG(ERROR) << "This is a violation because the ptrace syscall would be unsafe in" << " sandbox2, so it has been blocked."; return; } if (syscall_nr == __NR_bpf) { LOG(ERROR) << "This is a violation because the bpf syscall would be risky in" << " a sandbox, so it has been blocked."; return; } if (syscall_nr == __NR_clone && ((arg0 & CLONE_UNTRACED) != 0)) { LOG(ERROR) << "This is a violation because calling clone with CLONE_UNTRACE" << " would be unsafe in sandbox2, so it has been blocked."; return; } } void Monitor::ActionProcessKill(pid_t pid, Result::StatusEnum status, uintptr_t code) { // Avoid overwriting result if we set it for instance after a violation. if (result_.final_status() == Result::UNSET) { result_.SetExitStatusCode(status, code); } VLOG(1) << "Sending SIGKILL to the PID: " << pid_; if (kill(pid_, SIGKILL) != 0) { LOG(FATAL) << "Could not send SIGKILL to PID " << pid_; } } void Monitor::EventPtraceSeccomp(pid_t pid, int event_msg) { VLOG(1) << "PID: " << pid << " violation uncovered via the SECCOMP_EVENT"; // If the seccomp-policy is using RET_TRACE, we request that it returns the // syscall architecture identifier in the SECCOMP_RET_DATA. const auto syscall_arch = static_cast<Syscall::CpuArch>(event_msg); Regs regs(pid); auto status = regs.Fetch(); if (!status.ok()) { LOG(ERROR) << status; ActionProcessKill(pid, Result::INTERNAL_ERROR, Result::FAILED_FETCH); return; } Syscall syscall = regs.ToSyscall(syscall_arch); // If the architecture of the syscall used is different that the current host // architecture, report a violation. if (syscall_arch != Syscall::GetHostArch()) { ActionProcessSyscallViolation(&regs, syscall, kArchitectureSwitchViolation); return; } ActionProcessSyscall(&regs, syscall); } void Monitor::EventPtraceExec(pid_t pid, int event_msg) { if (!IsActivelyMonitoring()) { VLOG(1) << "PTRACE_EVENT_EXEC seen from PID: " << event_msg << ". SANDBOX ENABLED!"; SetActivelyMonitoring(); } ActionProcessContinue(pid, 0); } void Monitor::EventPtraceExit(pid_t pid, int event_msg) { // A regular exit, let it continue. if (WIFEXITED(event_msg)) { ActionProcessContinue(pid, 0); return; } // Everything except the SECCOMP violation can continue. if (!WIFSIGNALED(event_msg) || WTERMSIG(event_msg) != SIGSYS) { // Process is dying because it received a signal. // This can occur in three cases: // 1) Process was killed from the sandbox, in this case the result status // was already set to Result::EXTERNAL_KILL. We do not get the stack // trace in this case. // 2) Process was killed because it hit a timeout. The result status is // also already set, however we are interested in the stack trace. // 3) Regular signal. We need to obtain everything. The status will be set // upon the process exit handler. if (pid == pid_) { result_.LoadRegs(pid_); result_.SetProgName(util::GetProgName(pid_)); result_.SetProcMaps(ReadProcMaps(pid_)); bool stacktrace_collection_possible = policy_->GetNamespace() && executor_->libunwind_sbox_for_pid_ == 0; auto collect_stacktrace = [this]() { result_.SetStackTrace(GetStackTrace(result_.GetRegs(), policy_->GetNamespace()->mounts())); }; switch (result_.final_status()) { case Result::EXTERNAL_KILL: if (stacktrace_collection_possible && policy_->collect_stacktrace_on_kill_) { collect_stacktrace(); } break; case Result::TIMEOUT: if (stacktrace_collection_possible && policy_->collect_stacktrace_on_timeout_) { collect_stacktrace(); } break; case Result::VIOLATION: break; case Result::UNSET: // Regular signal. if (stacktrace_collection_possible && policy_->collect_stacktrace_on_signal_) { collect_stacktrace(); } break; default: LOG(ERROR) << "Unexpected codepath taken"; break; } } ActionProcessContinue(pid, 0); return; } VLOG(1) << "PID: " << pid << " violation uncovered via the EXIT_EVENT"; // We do not generate the stack trace in the SECCOMP case as it will be // generated during ActionProcessSyscallViolation anyway. Regs regs(pid); auto status = regs.Fetch(); if (!status.ok()) { LOG(ERROR) << status; ActionProcessKill(pid, Result::INTERNAL_ERROR, Result::FAILED_FETCH); return; } auto syscall = regs.ToSyscall(Syscall::GetHostArch()); ActionProcessSyscallViolation(&regs, syscall, kSyscallViolation); } void Monitor::EventPtraceStop(pid_t pid, int stopsig) { // It's not a real stop signal. For example PTRACE_O_TRACECLONE and similar // flags to ptrace(PTRACE_SEIZE) might generate this event with SIGTRAP. if (stopsig != SIGSTOP && stopsig != SIGTSTP && stopsig != SIGTTIN && stopsig != SIGTTOU) { ActionProcessContinue(pid, 0); return; } // It's our PID stop signal. Stop it. VLOG(2) << "PID: " << pid << " stopped due to " << util::GetSignalName(stopsig); ActionProcessStop(pid, 0); } void Monitor::StateProcessStopped(pid_t pid, int status) { int stopsig = WSTOPSIG(status); if (__WPTRACEEVENT(status) == 0) { // Must be a regular signal delivery. VLOG(2) << "PID: " << pid << " received signal: " << util::GetSignalName(stopsig); notify_->EventSignal(pid, stopsig); ActionProcessContinue(pid, stopsig); return; } unsigned long event_msg; // NOLINT if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &event_msg) == -1) { if (errno == ESRCH) { // This happens from time to time, the kernel does not guarantee us that // we get the event in time. PLOG(INFO) << "ptrace(PTRACE_GETEVENTMSG, " << pid << ")"; return; } PLOG(ERROR) << "ptrace(PTRACE_GETEVENTMSG, " << pid << ")"; ActionProcessKill(pid, Result::INTERNAL_ERROR, Result::FAILED_GETEVENT); return; } if (pid == pid_ && should_dump_stack_ && executor_->libunwind_sbox_for_pid_ == 0 && policy_->GetNamespace()) { Regs regs(pid); auto status = regs.Fetch(); if (status.ok()) { VLOG(0) << "SANDBOX STACK : PID: " << pid << ", [" << GetStackTrace(&regs, policy_->GetNamespace()->mounts()) << "]"; } else { LOG(WARNING) << "FAILED TO GET SANDBOX STACK : " << status; } should_dump_stack_ = false; } #if !defined(PTRACE_EVENT_STOP) #define PTRACE_EVENT_STOP 128 #endif switch (__WPTRACEEVENT(status)) { case PTRACE_EVENT_FORK: /* fall through */ case PTRACE_EVENT_VFORK: /* fall through */ case PTRACE_EVENT_CLONE: /* fall through */ case PTRACE_EVENT_VFORK_DONE: ActionProcessContinue(pid, 0); break; case PTRACE_EVENT_EXEC: VLOG(2) << "PID: " << pid << " PTRACE_EVENT_EXEC, PID: " << event_msg; EventPtraceExec(pid, event_msg); break; case PTRACE_EVENT_EXIT: VLOG(2) << "PID: " << pid << " PTRACE_EVENT_EXIT: " << event_msg; EventPtraceExit(pid, event_msg); break; case PTRACE_EVENT_STOP: VLOG(2) << "PID: " << pid << " PTRACE_EVENT_STOP: " << event_msg; EventPtraceStop(pid, stopsig); break; case PTRACE_EVENT_SECCOMP: VLOG(2) << "PID: " << pid << " PTRACE_EVENT_SECCOMP: " << event_msg; EventPtraceSeccomp(pid, event_msg); break; default: LOG(ERROR) << "Unknown ptrace event: " << __WPTRACEEVENT(status) << " with data: " << event_msg; break; } } void Monitor::PidInterrupt(pid_t pid) { if (ptrace(PTRACE_INTERRUPT, pid, 0, 0) == -1) { PLOG(WARNING) << "ptrace(PTRACE_INTERRUPT, pid=" << pid << ")"; } } } // namespace sandbox2
34.76204
84
0.641594
[ "object" ]
abd8bc03b35e0abb6e2571b49365c67b570960bf
269,832
cc
C++
SmartDiet_Backend/matlab/SensorFusion/BSR/grouping/source/gpb_src/src/math/libraries/lib_image.cc
mdepak/mobile_computing
0ac1250b86c35cbe4eef7186f4efcdbfeabfb244
[ "MIT" ]
7
2018-05-05T03:51:01.000Z
2020-12-30T01:05:33.000Z
SmartDiet_Backend/matlab/SensorFusion/BSR/grouping/source/gpb_src/src/math/libraries/lib_image.cc
mdepak/mobile_computing
0ac1250b86c35cbe4eef7186f4efcdbfeabfb244
[ "MIT" ]
1
2020-08-13T08:49:05.000Z
2020-08-13T08:49:05.000Z
SmartDiet_Backend/matlab/SensorFusion/BSR/grouping/source/gpb_src/src/math/libraries/lib_image.cc
mdepak/mobile_computing
0ac1250b86c35cbe4eef7186f4efcdbfeabfb244
[ "MIT" ]
null
null
null
/* * Image processing library. */ #include "collections/abstract/collection.hh" #include "collections/array_list.hh" #include "collections/list.hh" #include "collections/queue_set.hh" #include "collections/pointers/auto_collection.hh" #include "concurrent/threads/child_thread.hh" #include "concurrent/threads/runnable.hh" #include "concurrent/threads/thread.hh" #include "functors/comparable_functors.hh" #include "functors/distanceable_functors.hh" #include "lang/array.hh" #include "lang/exceptions/ex_index_out_of_bounds.hh" #include "lang/exceptions/ex_invalid_argument.hh" #include "lang/exceptions/ex_not_found.hh" #include "lang/iterators/iterator.hh" #include "lang/pointers/auto_ptr.hh" #include "math/geometry/point_2D.hh" #include "math/geometry/seg_intersect.hh" #include "math/geometry/triangulation.hh" #include "math/libraries/lib_image.hh" #include "math/libraries/lib_signal.hh" #include "math/math.hh" #include "math/matrices/matrix.hh" #include "math/matrices/cmatrix.hh" #include "mlearning/clustering/clusterers/abstract/centroid_clusterer.hh" #include "mlearning/clustering/clusterers/general/sample_clusterer.hh" #include "mlearning/clustering/clusterers/kmeans/matrix_clusterer.hh" #include "mlearning/clustering/metrics/matrix_metrics.hh" namespace math { namespace libraries { /* * Imports. */ using collections::abstract::collection; using collections::array_list; using collections::list; using collections::queue_set; using collections::pointers::auto_collection; using concurrent::threads::child_thread; using concurrent::threads::runnable; using concurrent::threads::thread; using functors::comparable_functor; using functors::compare_functor; using functors::compare_functors; using functors::distanceable_functor; using lang::array; using lang::exceptions::ex_index_out_of_bounds; using lang::exceptions::ex_invalid_argument; using lang::exceptions::ex_not_found; using lang::iterators::iterator; using lang::pointers::auto_ptr; using math::geometry::point_2D; using math::geometry::seg_intersect; using math::geometry::triangulation; using math::matrices::matrix; using math::matrices::cmatrix; using mlearning::clustering::clusterers::abstract::centroid_clusterer; using mlearning::clustering::clusterers::general::sample_clusterer; using mlearning::clustering::metrics::matrix_metrics; using namespace mlearning::clustering::clusterers; /*************************************************************************** * Image color space transforms. ***************************************************************************/ /* * Compute a grayscale image from an RGB image. */ matrix<> lib_image::grayscale( const matrix<>& r, const matrix<>& g, const matrix<>& b) { /* check arguments */ matrix<>::assert_dims_equal(r._dims, g._dims); matrix<>::assert_dims_equal(r._dims, b._dims); /* convert to grayscale */ matrix<> m(r._dims); for (unsigned long n = 0; n < m._size; n++) { m._data[n] = (0.29894 * r._data[n]) + (0.58704 * g._data[n]) + (0.11402 * b._data[n]); } return m; } /* * Normalize a grayscale image so that intensity values lie in [0,1]. */ void lib_image::grayscale_normalize(matrix<>& m) { if (m._size > 0) { double max_val = max(m); if (max_val > 0) { for (unsigned long n = 0; n < m._size; n++) m._data[n] /= max_val; } } } /* * Normalize and stretch a grayscale image so that intensity values span * the full [0,1] range. */ void lib_image::grayscale_normalize_stretch(matrix<>& m) { /* subtract off minimum value */ if (m._size > 0) { double min_val = min(m); for (unsigned long n = 0; n < m._size; n++) m._data[n] -= min_val; } /* normalize image */ lib_image::grayscale_normalize(m); } /* * Gamma correct the RGB image using the given correction value. */ void lib_image::rgb_gamma_correct( matrix<>& r, matrix<>& g, matrix<>& b, double gamma) { /* check arguments */ matrix<>::assert_dims_equal(r._dims, g._dims); matrix<>::assert_dims_equal(r._dims, b._dims); /* gamma correct image */ for (unsigned long n = 0; n < r._size; n++) { r._data[n] = math::pow(r._data[n], gamma); g._data[n] = math::pow(g._data[n], gamma); b._data[n] = math::pow(b._data[n], gamma); } } /* * Normalize an Lab image so that values for each channel lie in [0,1]. */ void lib_image::lab_normalize( matrix<>& l, matrix<>& a, matrix<>& b) { /* check arguments */ matrix<>::assert_dims_equal(l._dims, a._dims); matrix<>::assert_dims_equal(l._dims, b._dims); /* range for a, b channels */ const double ab_min = -73; const double ab_max = 95; const double ab_range = ab_max - ab_min; /* normalize Lab image */ for (unsigned long n = 0; n < l._size; n++) { double l_val = l._data[n] / 100.0; double a_val = (a._data[n] - ab_min) / ab_range; double b_val = (b._data[n] - ab_min) / ab_range; if (l_val < 0) { l_val = 0; } else if (l_val > 1) { l_val = 1; } if (a_val < 0) { a_val = 0; } else if (a_val > 1) { a_val = 1; } if (b_val < 0) { b_val = 0; } else if (b_val > 1) { b_val = 1; } l._data[n] = l_val; a._data[n] = a_val; b._data[n] = b_val; } } /* * Convert from RGB color space to XYZ color space. */ void lib_image::rgb_to_xyz(matrix<>& r_x, matrix<>& g_y, matrix<>& b_z) { /* check arguments */ matrix<>::assert_dims_equal(r_x._dims, g_y._dims); matrix<>::assert_dims_equal(r_x._dims, b_z._dims); /* convert RGB to XYZ */ for (unsigned long n = 0; n < r_x._size; n++) { double r = r_x._data[n]; double g = g_y._data[n]; double b = b_z._data[n]; r_x._data[n] = (0.412453 * r) + (0.357580 * g) + (0.180423 * b); g_y._data[n] = (0.212671 * r) + (0.715160 * g) + (0.072169 * b); b_z._data[n] = (0.019334 * r) + (0.119193 * g) + (0.950227 * b); } } /* * Convert from RGB color space to Lab color space. */ void lib_image::rgb_to_lab(matrix<>& r_l, matrix<>& g_a, matrix<>& b_b) { lib_image::rgb_to_xyz(r_l, g_a, b_b); lib_image::xyz_to_lab(r_l, g_a, b_b); } /* * Convert from XYZ color space to RGB color space. */ void lib_image::xyz_to_rgb(matrix<>& x_r, matrix<>& y_g, matrix<>& z_b) { /* check arguments */ matrix<>::assert_dims_equal(x_r._dims, y_g._dims); matrix<>::assert_dims_equal(x_r._dims, z_b._dims); /* convert XYZ to RGB */ for (unsigned long n = 0; n < x_r._size; n++) { double x = x_r._data[n]; double y = y_g._data[n]; double z = z_b._data[n]; x_r._data[n] = ( 3.240479 * x) + (-1.537150 * y) + (-0.498535 * z); y_g._data[n] = (-0.969256 * x) + ( 1.875992 * y) + ( 0.041556 * z); z_b._data[n] = ( 0.055648 * x) + (-0.204043 * y) + ( 1.057311 * z); } } /* * Convert from XYZ color space to Lab color space. */ void lib_image::xyz_to_lab(matrix<>& x_l, matrix<>& y_a, matrix<>& z_b) { /* check arguments */ matrix<>::assert_dims_equal(x_l._dims, y_a._dims); matrix<>::assert_dims_equal(x_l._dims, z_b._dims); /* D65 white point reference */ const double x_ref = 0.950456; const double y_ref = 1.000000; const double z_ref = 1.088754; /* threshold value */ const double threshold = 0.008856; /* convert XYZ to Lab */ for (unsigned long n = 0; n < x_l._size; n++) { /* extract xyz color value and normalize by reference point */ double x = (x_l._data[n] / x_ref); double y = (y_a._data[n] / y_ref); double z = (z_b._data[n] / z_ref); /* compute fx, fy, fz */ double fx = (x > threshold) ? math::pow(x,(1.0/3.0)) : (7.787*x + (16.0/116.0)); double fy = (y > threshold) ? math::pow(y,(1.0/3.0)) : (7.787*y + (16.0/116.0)); double fz = (z > threshold) ? math::pow(z,(1.0/3.0)) : (7.787*z + (16.0/116.0)); /* compute Lab color value */ x_l._data[n] = (y > threshold) ? (116*math::pow(y,(1.0/3.0)) - 16) : (903.3*y); y_a._data[n] = 500 * (fx - fy); z_b._data[n] = 200 * (fy - fz); } } /* * Convert from Lab color space to RGB color space. */ void lib_image::lab_to_rgb(matrix<>& l_r, matrix<>& a_g, matrix<>& b_b) { lib_image::lab_to_xyz(l_r, a_g, b_b); lib_image::xyz_to_rgb(l_r, a_g, b_b); } /* * Convert from Lab color space to XYZ color space. */ void lib_image::lab_to_xyz(matrix<>& l_x, matrix<>& a_y, matrix<>& b_z) { /* check arguments */ matrix<>::assert_dims_equal(l_x._dims, a_y._dims); matrix<>::assert_dims_equal(l_x._dims, b_z._dims); /* D65 white point reference */ const double x_ref = 0.950456; const double y_ref = 1.000000; const double z_ref = 1.088754; /* threshold value */ const double threshold = 0.008856; /* convert Lab to XYZ */ for (unsigned long n = 0; n < l_x._size; n++) { /* extract Lab color value */ double l = l_x._data[n]; double a = a_y._data[n]; double b = b_z._data[n]; /* compute y (normalized by reference point) */ double y = (l + 16.0)/116.0; y = y*y*y; if (y <= threshold) y = l / 903.3; /* compute fy, fx, fz */ double fy = (y > threshold) ? math::pow(y,(1.0/3.0)) : (7.787*y + (16.0/116.0)); double fx = (a/500) + fy; double fz = fy - (b/200); /* compute x (normalized by reference point) */ double x = fx*fx*fx; if (x <= threshold) x = (fx - (16.0/116.0))/7.787; /* compute z (normalized by reference point) */ double z = fz*fz*fz; if (z <= threshold) z = (fz - (16.0/116.0))/7.787; /* compute xyz color value */ l_x._data[n] = x * x_ref; a_y._data[n] = y * y_ref; b_z._data[n] = z * z_ref; } } /*************************************************************************** * Matrix border operations (2D). ***************************************************************************/ namespace { /* * Compute border mirrored matrix. */ template <typename T> void compute_border_mirror_2D( const T* m_src, /* source matrix */ T* m_dst, /* destination matrix */ unsigned long border_x, /* size of border */ unsigned long border_y, unsigned long size_x_src, /* size of source */ unsigned long size_y_src) { /* compute destination size */ unsigned long size_x_dst = size_x_src + 2*border_x; unsigned long size_y_dst = size_y_src + 2*border_y; /* compute step sizes in destination matrix (for copying interior) */ unsigned long ind_init = border_x * size_y_dst + border_y; unsigned long ind_step = 2*border_y; /* copy interior */ for (unsigned long n = 0, ind = ind_init, x = 0; x < size_x_src; x++) { for (unsigned long y = 0; y < size_y_src; y++, n++, ind++) m_dst[ind] = m_src[n]; ind += ind_step; } /* mirror top */ { unsigned long ind_intr = border_x * size_y_dst; unsigned long ind_bdr = ind_intr + size_y_dst; for (unsigned long x = 0; x < border_x; x++) { ind_bdr -= 2*size_y_dst; for (unsigned long y = 0; y < size_y_dst; y++) m_dst[ind_bdr++] = m_dst[ind_intr++]; } } /* mirror bottom */ { unsigned long ind_bdr = (size_x_src + border_x) * size_y_dst; unsigned long ind_intr = ind_bdr + size_y_dst; for (unsigned long x = 0; x < border_x; x++) { ind_intr -= 2*size_y_dst; for (unsigned long y = 0; y < size_y_dst; y++) m_dst[ind_bdr++] = m_dst[ind_intr++]; } } /* mirror left */ { unsigned long ind_bdr = 0; unsigned long ind_intr = 2*border_y; for (unsigned long x = 0; x < size_x_dst; x++) { for (unsigned long y = 0; y < border_y; y++) m_dst[ind_bdr++] = m_dst[--ind_intr]; ind_bdr += (size_y_dst - border_y); ind_intr += (size_y_dst + border_y); } } /* mirror right */ { unsigned long ind_bdr = size_y_dst - border_y; unsigned long ind_intr = ind_bdr; for (unsigned long x = 0; x < size_x_dst; x++) { for (unsigned long y = 0; y < border_y; y++) m_dst[ind_bdr++] = m_dst[--ind_intr]; ind_bdr += (size_y_dst - border_y); ind_intr += (size_y_dst + border_y); } } } /* * Compute border trimmed matrix. */ template <typename T> void compute_border_trim_2D( const T* m_src, /* source matrix */ T* m_dst, /* destination matrix */ unsigned long border_x, /* size of border */ unsigned long border_y, unsigned long size_x_dst, /* size of destination */ unsigned long size_y_dst, unsigned long size_y_src) /* size of source in y-dimension */ { /* compute step sizes in source matrix */ unsigned long ind_init = border_x * size_y_src + border_y; unsigned long ind_step = 2*border_y; /* trim border */ for (unsigned long n = 0, ind = ind_init, x = 0; x < size_x_dst; x++) { for (unsigned long y = 0; y < size_y_dst; y++, n++, ind++) m_dst[n] = m_src[ind]; ind += ind_step; } } } /* namespace */ /* * Expand the border of the 2D matrix by the specified size on all sides. * The expanded border is filled with the mirror image of interior data. */ matrix<> lib_image::border_mirror_2D(const matrix<>& m, unsigned long size) { return lib_image::border_mirror_2D(m, size, size); } cmatrix<> lib_image::border_mirror_2D(const cmatrix<>& m, unsigned long size) { return lib_image::border_mirror_2D(m, size, size); } /* * Expand the border of the 2D matrix by the specified sizes in the x- and * y-dimensions. The expanded border is filled with the mirror image of * interior data. */ matrix<> lib_image::border_mirror_2D( const matrix<>& m, unsigned long border_x, unsigned long border_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* get matrix size */ unsigned long size_x_src = m._dims[0]; unsigned long size_y_src = m._dims[1]; /* check that interior can be mirrored */ if ((border_x > size_x_src) || (border_y > size_y_src)) throw ex_invalid_argument( "cannot create mirrored border larger than matrix interior dimensions" ); /* mirror border */ matrix<> m_dst(size_x_src + 2*border_x, size_y_src + 2*border_y); compute_border_mirror_2D( m._data, m_dst._data, border_x, border_y, size_x_src, size_y_src ); return m_dst; } cmatrix<> lib_image::border_mirror_2D( const cmatrix<>& m, unsigned long border_x, unsigned long border_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* get matrix size */ unsigned long size_x_src = m._dims[0]; unsigned long size_y_src = m._dims[1]; /* check that interior can be mirrored */ if ((border_x > size_x_src) || (border_y > size_y_src)) throw ex_invalid_argument( "cannot create mirrored border larger than matrix interior dimensions" ); /* mirror border */ cmatrix<> m_dst(size_x_src + 2*border_x, size_y_src + 2*border_y); compute_border_mirror_2D( m._data, m_dst._data, border_x, border_y, size_x_src, size_y_src ); return m_dst; } /* * Trim the specified border size off all sides of the 2D matrix. */ matrix<> lib_image::border_trim_2D(const matrix<>& m, unsigned long size) { return lib_image::border_trim_2D(m, size, size); } cmatrix<> lib_image::border_trim_2D(const cmatrix<>& m, unsigned long size) { return lib_image::border_trim_2D(m, size, size); } /* * Trim the specified border dimensions off of the 2D matrix. */ matrix<> lib_image::border_trim_2D( const matrix<>& m, unsigned long border_x, unsigned long border_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* get matrix size */ unsigned long size_x_src = m._dims[0]; unsigned long size_y_src = m._dims[1]; /* compute size of result matrix */ unsigned long size_x_dst = (size_x_src > (2*border_x)) ? (size_x_src - 2*border_x) : 0; unsigned long size_y_dst = (size_y_src > (2*border_y)) ? (size_y_src - 2*border_y) : 0; /* trim border */ matrix<> m_dst(size_x_dst, size_y_dst); compute_border_trim_2D( m._data, m_dst._data, border_x, border_y, size_x_dst, size_y_dst, size_y_src ); return m_dst; } cmatrix<> lib_image::border_trim_2D( const cmatrix<>& m, unsigned long border_x, unsigned long border_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* get matrix size */ unsigned long size_x_src = m._dims[0]; unsigned long size_y_src = m._dims[1]; /* compute size of result matrix */ unsigned long size_x_dst = (size_x_src > (2*border_x)) ? (size_x_src - 2*border_x) : 0; unsigned long size_y_dst = (size_y_src > (2*border_y)) ? (size_y_src - 2*border_y) : 0; /* trim border */ cmatrix<> m_dst(size_x_dst, size_y_dst); compute_border_trim_2D( m._data, m_dst._data, border_x, border_y, size_x_dst, size_y_dst, size_y_src ); return m_dst; } /*************************************************************************** * Matrix subdivision (2D). ***************************************************************************/ /* * Compute the optimal number of subdivisions along each dimension. * * The optimal subdivision parameters split the 2D matrix into no more than * the desired number of cells, while at the same time preferring nearly * square cells over elongated rectangles. * * Adjacent cells overlap by the specified number of elements in each * dimension. */ void lib_image::subdivision_params_2D( unsigned long size_x, unsigned long size_y, unsigned long n_subdiv, unsigned long& n_subdiv_x, unsigned long& n_subdiv_y, unsigned long overlap_x, unsigned long overlap_y) { /* check number of subdivisions is valid */ if (n_subdiv == 0) throw ex_invalid_argument("number of subdivisions must be nonzero"); /* check matrix is not smaller than overlap */ if (size_x < (2*overlap_x)) throw ex_invalid_argument("x-overlap is too large"); if (size_y < (2*overlap_y)) throw ex_invalid_argument("y-overlap is too large"); /* handle the case of an empty matrix */ if ((size_x == 0) || (size_y == 0)) { n_subdiv_x = 1; n_subdiv_y = 1; return; } /* compute maximum number of subdivisions allowed */ unsigned long max_subdiv_x = (overlap_x == 0) ? size_x : (size_x - overlap_x) / overlap_x; unsigned long max_subdiv_y = (overlap_y == 0) ? size_y : (size_y - overlap_y) / overlap_y; /* compute desired number of subdivisions */ double length_x = static_cast<double>(size_x - overlap_x); double length_y = static_cast<double>(size_y - overlap_y); double num_x = math::sqrt(static_cast<double>(n_subdiv)*length_x/length_y); double num_y = math::sqrt(static_cast<double>(n_subdiv)*length_y/length_x); unsigned long nx = static_cast<unsigned long>(math::round(num_x)); unsigned long ny = static_cast<unsigned long>(math::round(num_y)); /* adjust to allowed subdivision limits */ if (nx == 0) { nx = 1; } else if (nx > max_subdiv_x) { nx = max_subdiv_x; } if (ny == 0) { ny = 1; } else if (ny > max_subdiv_y) { ny = max_subdiv_y; } /* adjust to subdivision geometry */ if ((nx > ny) || ((nx == ny) && (max_subdiv_x > max_subdiv_y))) { /* adjust nx, then ny */ nx = ((n_subdiv / ny) < max_subdiv_x) ? (n_subdiv / ny) : max_subdiv_x; ny = ((n_subdiv / nx) < max_subdiv_y) ? (n_subdiv / nx) : max_subdiv_y; } else { /* adjust ny, then nx */ ny = ((n_subdiv / nx) < max_subdiv_y) ? (n_subdiv / nx) : max_subdiv_y; nx = ((n_subdiv / ny) < max_subdiv_x) ? (n_subdiv / ny) : max_subdiv_x; } /* return subdivision parameters */ n_subdiv_x = nx; n_subdiv_y = ny; } void lib_image::subdivision_params_2D( const matrix<>& m, unsigned long n_subdiv, unsigned long& n_subdiv_x, unsigned long& n_subdiv_y, unsigned long overlap_x, unsigned long overlap_y) { if (m.dimensionality() != 2) throw ex_invalid_argument("matrix must be 2D"); return lib_image::subdivision_params_2D( m.size(0), m.size(1), n_subdiv, n_subdiv_x, n_subdiv_y, overlap_x, overlap_y ); } void lib_image::subdivision_params_2D( const cmatrix<>& m, unsigned long n_subdiv, unsigned long& n_subdiv_x, unsigned long& n_subdiv_y, unsigned long overlap_x, unsigned long overlap_y) { if (m.dimensionality() != 2) throw ex_invalid_argument("matrix must be 2D"); return lib_image::subdivision_params_2D( m.size(0), m.size(1), n_subdiv, n_subdiv_x, n_subdiv_y, overlap_x, overlap_y ); } namespace { /* * Compute matrix subdivision. */ template <typename T> void compute_subdivide_2D( const matrix<T>& m, /* matrix */ unsigned long n_subdiv_x, /* # of subdivisions in x-dimension */ unsigned long n_subdiv_y, /* # of subdivisions in y-dimension */ unsigned long overlap_x, /* overlap in x-dimension */ unsigned long overlap_y, /* overlap in y-dimension */ array_list< matrix<T> >& submatrices) /* returned subdivision */ { /* check that matrix is 2D */ if (m.dimensionality() != 2) throw ex_invalid_argument("matrix must be 2D"); /* check number of subdivisions is valid */ if ((n_subdiv_x == 0) || (n_subdiv_y == 0)) throw ex_invalid_argument("number of subdivisions must be nonzero"); /* get matrix dimensions */ unsigned long size_x = m.size(0); unsigned long size_y = m.size(1); /* compute total overlap size */ unsigned long overlap_x_total = (n_subdiv_x + 1) * overlap_x; unsigned long overlap_y_total = (n_subdiv_y + 1) * overlap_y; /* check that all subdivisions can be filled */ if ((overlap_x_total > size_x) || (n_subdiv_x > size_x)) throw ex_invalid_argument("cannot fill requested # of x-subdivisions"); if ((overlap_y_total > size_y) || (n_subdiv_y > size_y)) throw ex_invalid_argument("cannot fill requested # of y-subdivisions"); /* compute subdivision size (excluding overlap) */ unsigned long interior_x_total = size_x - overlap_x_total; unsigned long interior_y_total = size_y - overlap_y_total; unsigned long interior_x = interior_x_total / n_subdiv_x; unsigned long interior_y = interior_y_total / n_subdiv_y; unsigned long extra_x = interior_x_total - (interior_x * n_subdiv_x); unsigned long extra_y = interior_y_total - (interior_y * n_subdiv_y); /* subdivide matrix */ const T* m_data = m.data(); for (unsigned long nx = 0, n = 0, start_x = 0; nx < n_subdiv_x; nx++) { /* compute submatrix x-size */ unsigned long sx_interior = interior_x + ((nx < extra_x) ? 1 : 0); unsigned long sx = sx_interior + (2*overlap_x); for (unsigned long ny = 0, start_y = 0; ny < n_subdiv_y; ny++, n++) { /* compute submatrix y-size */ unsigned long sy_interior = interior_y + ((ny < extra_y) ? 1 : 0); unsigned long sy = sy_interior + (2*overlap_y); /* copy submatrix */ matrix<T>& m_sub = submatrices[n]; m_sub.resize(sx, sy); T* m_sub_data = m_sub.data(); unsigned long pos = start_x * size_y + start_y; for (unsigned long x = 0, ind = 0; x < sx; x++) { for (unsigned long y = 0; y < sy; y++) m_sub_data[ind++] = m_data[pos++]; pos += (size_y - sy); } /* update y offset */ start_y += (sy_interior + overlap_y); } /* update x offset */ start_x += (sx_interior + overlap_x); } } /* * Compute combined matrix from subdivision. */ template <typename T> void compute_combine_2D( const array_list< matrix<T> >& submatrices, /* subdivision */ unsigned long n_subdiv_x, /* # of x-subdivisions */ unsigned long n_subdiv_y, /* # of y-subdivisions */ unsigned long overlap_x, /* overlap in x-dimension */ unsigned long overlap_y, /* overlap in y-dimension */ matrix<T>& m) /* returned matrix */ { /* check for correct number of subdivisions */ unsigned long n_subdiv = n_subdiv_x * n_subdiv_y; if (submatrices.size() != n_subdiv) throw ex_invalid_argument("incorrect number of subdivisions specified"); /* check that all submatrices are 2D */ for (unsigned long n = 0; n < n_subdiv; n++) { if (submatrices[n].dimensionality() != 2) throw ex_invalid_argument("all submatrices must be 2D"); } /* determine x-subdivision sizes */ array<unsigned long> subdiv_sizes_x(n_subdiv_x); unsigned long size_x = overlap_x; for (unsigned long nx = 0, n = 0; nx < n_subdiv_x; nx++, n += n_subdiv_y) { unsigned long sx = submatrices[n].size(0); if (sx < (2*overlap_x)) throw ex_invalid_argument("incorrect submatrix size"); sx -= (2*overlap_x); size_x += (sx + overlap_x); subdiv_sizes_x[nx] = sx; } /* determine y-subdivision sizes */ array<unsigned long> subdiv_sizes_y(n_subdiv_y); unsigned long size_y = overlap_y; for (unsigned long ny = 0; ny < n_subdiv_y; ny++) { unsigned long sy = submatrices[ny].size(1); if (sy < (2*overlap_y)) throw ex_invalid_argument("incorrect submatrix size"); sy -= (2*overlap_y); size_y += (sy + overlap_y); subdiv_sizes_y[ny] = sy; } /* combine submatrices */ m.resize(size_x, size_y); T* m_data = m.data(); for (unsigned long nx = 0, n = 0, start_x = 0; nx < n_subdiv_x; nx++) { /* get submatrix x-size */ unsigned long sx_interior = subdiv_sizes_x[nx]; unsigned long sx = sx_interior + (2*overlap_x); for (unsigned long ny = 0, start_y = 0; ny < n_subdiv_y; ny++, n++) { /* get submatrix y-size */ unsigned long sy_interior = subdiv_sizes_y[ny]; unsigned long sy = sy_interior + (2*overlap_y); /* check submatrix size */ const matrix<T>& m_sub = submatrices[n]; if ((m_sub.size(0) != sx) || (m_sub.size(1) != sy)) throw ex_invalid_argument("submatrix size disagreement"); /* copy submatrix */ const T* m_sub_data = m_sub.data(); unsigned long pos = start_x * size_y + start_y; for (unsigned long x = 0, ind = 0; x < sx; x++) { for (unsigned long y = 0; y < sy; y++) m_data[pos++] = m_sub_data[ind++]; pos += (size_y - sy); } /* update y offset */ start_y += (sy_interior + overlap_y); } /* update x offset */ start_x += (sx_interior + overlap_x); } } } /* namespace */ /* * Subdivide the 2D matrix into a grid of overlapping submatrices. * Return the collection of submatrices. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::subdivide_2D( const matrix<>& m, unsigned long n_subdiv_x, unsigned long n_subdiv_y, unsigned long overlap_x, unsigned long overlap_y) { /* allocate subdivision */ unsigned long n_subdiv = n_subdiv_x * n_subdiv_y; auto_collection< matrix<>, array_list< matrix<> > > submatrices( new array_list< matrix<> >() ); for (unsigned long n = 0; n < n_subdiv; n++) { auto_ptr< matrix<> > m_sub(new matrix<>()); submatrices->add(*m_sub); m_sub.release(); } /* compute subdivision */ compute_subdivide_2D( m, n_subdiv_x, n_subdiv_y, overlap_x, overlap_y, *submatrices ); return submatrices; } auto_collection< cmatrix<>, array_list< cmatrix<> > > lib_image::subdivide_2D( const cmatrix<>& m, unsigned long n_subdiv_x, unsigned long n_subdiv_y, unsigned long overlap_x, unsigned long overlap_y) { /* allocate subdivision */ unsigned long n_subdiv = n_subdiv_x * n_subdiv_y; auto_collection< cmatrix<>, array_list< cmatrix<> > > submatrices( new array_list< cmatrix<> >() ); for (unsigned long n = 0; n < n_subdiv; n++) { auto_ptr< cmatrix<> > m_sub(new cmatrix<>()); submatrices->add(*m_sub); m_sub.release(); } /* create submatrix array of matrix< complex<> > type */ array_list< matrix< complex<> > > submatrix_arr; for (unsigned long n = 0; n < n_subdiv; n++) submatrix_arr.add((*submatrices)[n]); /* compute subdivision */ compute_subdivide_2D( m, n_subdiv_x, n_subdiv_y, overlap_x, overlap_y, submatrix_arr ); return submatrices; } /* * Combine submatrices resulting from matrix subdivision. */ matrix<> lib_image::combine_2D( const array_list< matrix<> >& submatrices, unsigned long n_subdiv_x, unsigned long n_subdiv_y, unsigned long overlap_x, unsigned long overlap_y) { matrix<> m; compute_combine_2D( submatrices, n_subdiv_x, n_subdiv_y, overlap_x, overlap_y, m ); return m; } cmatrix<> lib_image::combine_2D( const array_list< cmatrix<> >& submatrices, unsigned long n_subdiv_x, unsigned long n_subdiv_y, unsigned long overlap_x, unsigned long overlap_y) { /* create submatrix array of matrix< complex<> > type */ array_list< matrix< complex<> > > submatrix_arr; for (unsigned long n = 0, n_subdiv = submatrices.size(); n < n_subdiv; n++) submatrix_arr.add(submatrices[n]); /* combine submatrices */ cmatrix<> m; compute_combine_2D( submatrix_arr, n_subdiv_x, n_subdiv_y, overlap_x, overlap_y, m ); return m; } /*************************************************************************** * Matrix resampling (2D). ***************************************************************************/ namespace { /* * Compute resampled 2D matrix using bilinear interpolation. */ template <typename T> void compute_resample_2D( const T* m_src, /* source matrix */ T* m_dst, /* destination matrix */ unsigned long size_x_src, /* size of source */ unsigned long size_y_src, unsigned long size_x_dst, /* size of destination */ unsigned long size_y_dst) { /* check that matrices are nonempty */ if ((size_x_src > 0) && (size_y_src > 0) && (size_x_dst > 0) && (size_y_dst > 0)) { /* compute whether to anchor x, y extrema to existing extrema */ const bool anchor_x = ((size_x_dst >= 3) || ((size_x_dst == 2) && (size_x_src <= 2))); const bool anchor_y = ((size_y_dst >= 3) || ((size_y_dst == 2) && (size_y_src <= 2))); /* compute step sizes */ const double step_x = (anchor_x) ? (static_cast<double>(size_x_src-1)/static_cast<double>(size_x_dst-1)) : (static_cast<double>(size_x_src-1)/static_cast<double>(size_x_dst+1)); const double step_y = (anchor_y) ? (static_cast<double>(size_y_src-1)/static_cast<double>(size_y_dst-1)) : (static_cast<double>(size_y_src-1)/static_cast<double>(size_y_dst+1)); /* resample */ double x = (anchor_x) ? 0 : step_x; unsigned long n = 0; for (unsigned long dst_x = 0; dst_x < size_x_dst; dst_x++) { /* compute integer coordinates bounding x-coordinate */ unsigned long x0 = static_cast<unsigned long>(math::floor(x)); unsigned long x1 = static_cast<unsigned long>(math::ceil(x)); if (x1 == size_x_src) { x1--; } /* compute distances to x-bounds */ const double dist_x0 = x - x0; const double dist_x1 = x1 - x; /* loop over y */ double y = (anchor_y) ? 0 : step_y; for (unsigned long dst_y = 0; dst_y < size_y_dst; dst_y++) { /* compute integer coordinates bounding y-coordinate */ unsigned long y0 = static_cast<unsigned long>(math::floor(y)); unsigned long y1 = static_cast<unsigned long>(math::ceil(y)); /* compute distances to y-bounds */ if (y1 == size_y_src) { y1--; } const double dist_y0 = y - y0; const double dist_y1 = y1 - y; /* grab matrix elements */ const T& m00 = m_src[x0*size_y_src + y0]; const T& m01 = m_src[x0*size_y_src + y1]; const T& m10 = m_src[x1*size_y_src + y0]; const T& m11 = m_src[x1*size_y_src + y1]; /* interpolate in x-direction */ const T t0 = (x0 != x1) ? (dist_x1 * m00 + dist_x0 * m10) : m00; const T t1 = (x0 != x1) ? (dist_x1 * m01 + dist_x0 * m11) : m01; /* interpolate in y-direction */ m_dst[n] = (y0 != y1) ? (dist_y1 * t0 + dist_y0 * t1) : t0; /* increment coordinate */ n++; y += step_y; } x += step_x; } } } } /* namespace */ /* * Resample the 2D matrix by the given scale factor in both the x- and y- * directions. A factor less than 1 produces a result smaller than the * original matrix, while a factor greater than 1 produces a result larger. */ matrix<> lib_image::resample_2D(const matrix<>& m, double scale) { return lib_image::resample_2D(m, scale, scale); } cmatrix<> lib_image::resample_2D(const cmatrix<>& m, double scale) { return lib_image::resample_2D(m, scale, scale); } /* * Resample the 2D matrix by the given scale factors in the x- and y- * directions, respectively. */ matrix<> lib_image::resample_2D( const matrix<>& m, double scale_x, double scale_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* compute desired size from scale factor */ unsigned long size_x = static_cast<unsigned long>( math::ceil(scale_x * static_cast<double>(m._dims[0])) ); unsigned long size_y = static_cast<unsigned long>( math::ceil(scale_y * static_cast<double>(m._dims[1])) ); /* resample */ return lib_image::resample_2D(m, size_x, size_y); } cmatrix<> lib_image::resample_2D( const cmatrix<>& m, double scale_x, double scale_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* compute desired size from scale factor */ unsigned long size_x = static_cast<unsigned long>( math::ceil(scale_x * static_cast<double>(m._dims[0])) ); unsigned long size_y = static_cast<unsigned long>( math::ceil(scale_y * static_cast<double>(m._dims[1])) ); /* resample */ return lib_image::resample_2D(m, size_x, size_y); } /* * Resample the 2D matrix on a grid of the specified size. */ matrix<> lib_image::resample_2D( const matrix<>& m, unsigned long size_x, unsigned long size_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* resample */ matrix<> m_dst(size_x, size_y); compute_resample_2D( m._data, m_dst._data, m._dims[0], m._dims[1], size_x, size_y ); return m_dst; } cmatrix<> lib_image::resample_2D( const cmatrix<>& m, unsigned long size_x, unsigned long size_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* resample */ cmatrix<> m_dst(size_x, size_y); compute_resample_2D( m._data, m_dst._data, m._dims[0], m._dims[1], size_x, size_y ); return m_dst; } /*************************************************************************** * Matrix rotation (2D). ***************************************************************************/ namespace { /* * Compute x/y-support for rotated 2D matrix. */ double support_x_rotated(double support_x, double support_y, double ori) { const double sx_cos_ori = support_x * math::cos(ori); const double sy_sin_ori = support_y * math::sin(ori); double x0_mag = math::abs(sx_cos_ori - sy_sin_ori); double x1_mag = math::abs(sx_cos_ori + sy_sin_ori); return (x0_mag > x1_mag) ? x0_mag : x1_mag; } double support_y_rotated(double support_x, double support_y, double ori) { const double sx_sin_ori = support_x * math::sin(ori); const double sy_cos_ori = support_y * math::cos(ori); double y0_mag = math::abs(sx_sin_ori - sy_cos_ori); double y1_mag = math::abs(sx_sin_ori + sy_cos_ori); return (y0_mag > y1_mag) ? y0_mag : y1_mag; } /* * Compute integer-valued supports for rotated 2D matrix. */ unsigned long support_x_rotated( unsigned long support_x, unsigned long support_y, double ori) { return static_cast<unsigned long>( math::ceil(support_x_rotated( static_cast<double>(support_x), static_cast<double>(support_y), ori )) ); } unsigned long support_y_rotated( unsigned long support_x, unsigned long support_y, double ori) { return static_cast<unsigned long>( math::ceil(support_y_rotated( static_cast<double>(support_x), static_cast<double>(support_y), ori )) ); } /* * Compute x/y-size for rotated 2D matrix. */ unsigned long size_x_rotated( unsigned long size_x, unsigned long size_y, double ori) { double support_x = static_cast<double>(size_x) / 2; double support_y = static_cast<double>(size_y) / 2; return static_cast<unsigned long>( math::ceil(support_x_rotated(support_x, support_y, ori) * 2) ); } unsigned long size_y_rotated( unsigned long size_x, unsigned long size_y, double ori) { double support_x = static_cast<double>(size_x) / 2; double support_y = static_cast<double>(size_y) / 2; return static_cast<unsigned long>( math::ceil(support_y_rotated(support_x, support_y, ori) * 2) ); } /* * Compute rotated 2D matrix using bilinear interpolation. */ template <typename T> void compute_rotate_2D( const T* m_src, /* source matrix */ T* m_dst, /* destination matrix */ unsigned long size_x_src, /* size of source */ unsigned long size_y_src, unsigned long size_x_dst, /* size of destination */ unsigned long size_y_dst, double ori) /* orientation */ { /* check that matrices are nonempty */ if ((size_x_src > 0) && (size_y_src > 0) && (size_x_dst > 0) && (size_y_dst > 0)) { /* compute sin and cos of rotation angle */ const double cos_ori = math::cos(ori); const double sin_ori = math::sin(ori); /* compute location of origin in src */ const double origin_x_src = static_cast<double>((size_x_src - 1)) / 2; const double origin_y_src = static_cast<double>((size_y_src - 1)) / 2; /* rotate */ double u = -(static_cast<double>((size_x_dst - 1)) / 2); unsigned long n = 0; for (unsigned long dst_x = 0; dst_x < size_x_dst; dst_x++) { double v = -(static_cast<double>((size_y_dst - 1)) / 2); for (unsigned long dst_y = 0; dst_y < size_y_dst; dst_y++) { /* reverse rotate by orientation and shift by origin offset */ double x = u * cos_ori + v * sin_ori + origin_x_src; double y = v * cos_ori - u * sin_ori + origin_y_src; /* check that location is in first quadrant */ if ((x >= 0) && (y >= 0)) { /* compute integer bounds on location */ unsigned long x0 = static_cast<unsigned long>(math::floor(x)); unsigned long x1 = static_cast<unsigned long>(math::ceil(x)); unsigned long y0 = static_cast<unsigned long>(math::floor(y)); unsigned long y1 = static_cast<unsigned long>(math::ceil(y)); /* check that location is within src matrix */ if ((0 <= x0) && (x1 < size_x_src) && (0 <= y0) && (y1 < size_y_src)) { /* compute distances to bounds */ double dist_x0 = x - x0; double dist_x1 = x1 - x; double dist_y0 = y - y0; double dist_y1 = y1 - y; /* grab matrix elements */ const T& m00 = m_src[x0*size_y_src + y0]; const T& m01 = m_src[x0*size_y_src + y1]; const T& m10 = m_src[x1*size_y_src + y0]; const T& m11 = m_src[x1*size_y_src + y1]; /* interpolate in x-direction */ const T t0 = (x0 != x1) ? (dist_x1 * m00 + dist_x0 * m10) : m00; const T t1 = (x0 != x1) ? (dist_x1 * m01 + dist_x0 * m11) : m01; /* interpolate in y-direction */ m_dst[n] = (y0 != y1) ? (dist_y1 * t0 + dist_y0 * t1) : t0; } } /* increment coordinate */ n++; v++; } u++; } } } } /* namespace */ /* * Rotate and pad with zeros. */ matrix<> lib_image::rotate_2D(const matrix<>& m, double ori) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* compute size of rotated matrix */ unsigned long size_x = size_x_rotated(m._dims[0], m._dims[1], ori); unsigned long size_y = size_y_rotated(m._dims[0], m._dims[1], ori); /* compute rotation */ return lib_image::rotate_2D_crop(m, ori, size_x, size_y); } cmatrix<> lib_image::rotate_2D(const cmatrix<>& m, double ori) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* compute size of rotated matrix */ unsigned long size_x = size_x_rotated(m._dims[0], m._dims[1], ori); unsigned long size_y = size_y_rotated(m._dims[0], m._dims[1], ori); /* compute rotation */ return lib_image::rotate_2D_crop(m, ori, size_x, size_y); } /* * Rotate and pad with zeros, but crop the result to be the same size as * the input matrix. */ matrix<> lib_image::rotate_2D_crop(const matrix<>& m, double ori) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* compute rotation */ return lib_image::rotate_2D_crop(m, ori, m._dims[0], m._dims[1]); } cmatrix<> lib_image::rotate_2D_crop(const cmatrix<>& m, double ori) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* compute rotation */ return lib_image::rotate_2D_crop(m, ori, m._dims[0], m._dims[1]); } /* * Rotate and pad with zeros, but crop the result to the specified size. */ matrix<> lib_image::rotate_2D_crop( const matrix<>& m, double ori, unsigned long size_x, unsigned long size_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* compute rotation */ matrix<> m_rot(size_x, size_y); compute_rotate_2D( m._data, m_rot._data, m._dims[0], m._dims[1], size_x, size_y, ori ); return m_rot; } cmatrix<> lib_image::rotate_2D_crop( const cmatrix<>& m, double ori, unsigned long size_x, unsigned long size_y) { /* check that matrix is 2D */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* compute rotation */ cmatrix<> m_rot(size_x, size_y); compute_rotate_2D( m._data, m_rot._data, m._dims[0], m._dims[1], size_x, size_y, ori ); return m_rot; } /*************************************************************************** * Image pyramids. ***************************************************************************/ /* * Gaussian pyramid. * * Construct the Gaussian pyramid for the given image. The pyramid is * defined by: * * I[n] = D(G(sigma) * I[n-1]) * * where * denotes convolution, D denotes downsampling by a factor of * 1/sigma in the x- and y-dimensions, I[0] is then input image, and * G is a 2D Gaussian kernel. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::gaussian_pyramid( const matrix<>& m, double sigma) { /* check arguments */ if (m._dims.size() != 2) throw ex_invalid_argument("image must be 2D"); if (sigma <= 1) throw ex_invalid_argument("sigma must be > 1"); /* compute gaussian filters */ matrix<> gx = lib_image::gaussian(sigma); matrix<> gy = transpose(gx); unsigned long min_size = gx.size(0); /* allocate pyramid */ auto_collection< matrix<>, array_list< matrix<> > > g_pyramid( new array_list< matrix<> >() ); /* initialize base level of pyramid */ auto_ptr< matrix<> > g_base(new matrix<>(m)); g_pyramid->add(*g_base); g_base.release(); /* compute gaussian pyramid */ while (true) { /* get previous level */ const matrix<>& g_prev = g_pyramid->tail(); /* compute dimensions of current level */ unsigned long size_x = static_cast<unsigned long>( math::floor(static_cast<double>(g_prev._dims[0]) / sigma) ); unsigned long size_y = static_cast<unsigned long>( math::floor(static_cast<double>(g_prev._dims[1]) / sigma) ); /* check if at top of pyramid */ if ((size_x < min_size) || (size_y < min_size)) break; /* compute current level */ auto_ptr< matrix<> > g_curr(new matrix<>( lib_image::resample_2D( conv_crop(conv_crop(g_prev, gx), gy), size_x, size_y ) )); /* store current level */ g_pyramid->add(*g_curr); g_curr.release(); } return g_pyramid; } /* * Laplacian pyramid. * * Construct an approximation to the scale-normalized Laplacian of Gaussian * pyramid by computing difference of Gaussians. This pyramid is defined by: * * L[n] = I[n] - U(I[n+1]) for 0 <= n < N * L[N] = I[N] for the coarsest level N * * where U denotes upsampling by a factor of sigma, and I[n] is a level in * the Gaussian pyramid defined above. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::laplacian_pyramid( const matrix<>& m, double sigma) { auto_collection< matrix<>, array_list< matrix<> > > g_pyramid = lib_image::gaussian_pyramid(m, sigma); return lib_image::laplacian_pyramid(*g_pyramid); } auto_collection< matrix<>, array_list< matrix<> > > lib_image::laplacian_pyramid( const array_list< matrix<> >& g_pyramid) { /* allocate pyramid */ auto_collection< matrix<>, array_list< matrix<> > > l_pyramid( new array_list< matrix<> >() ); /* compute pyramid */ unsigned long n_levels = g_pyramid.size(); for (unsigned long n = 0; (n+1) < n_levels; n++) { const matrix<>& g_curr = g_pyramid[n]; const matrix<>& g_next = g_pyramid[n+1]; auto_ptr< matrix<> > l_curr(new matrix<>( g_curr - lib_image::resample_2D(g_next, g_curr._dims[0], g_curr._dims[1]) )); l_pyramid->add(*l_curr); l_curr.release(); } /* add coarsest level of gaussian pyramid to top of laplacian pyramid */ if (n_levels > 0) { auto_ptr< matrix<> > l_top(new matrix<>(g_pyramid[n_levels-1])); l_pyramid->add(*l_top); l_top.release(); } return l_pyramid; } /* * Resize all images in the pyramid to be the same size. * The base (largest) image is scaled by the given factor in both the * x- and y-dimensions and all other images are resampled to that size. */ void lib_image::pyramid_resize(array_list< matrix<> >& pyramid, double scale) { /* check that pyramid is nonempty */ unsigned long n_levels = pyramid.size(); if (n_levels == 0) return; /* resize base level */ pyramid[0] = lib_image::resample_2D(pyramid[0], scale); /* get size of base level */ unsigned long size_x = pyramid[0]._dims[0]; unsigned long size_y = pyramid[0]._dims[1]; /* resize other levels */ for (unsigned long n = 1; n < n_levels; n++) pyramid[n] = lib_image::resample_2D(pyramid[n], size_x, size_y); } /* * Reconstruct the original image given its laplacian pyramid. */ matrix<> lib_image::image_from_laplacian_pyramid( const array_list< matrix<> >& l_pyramid) { /* check that pyramid is nonempty */ unsigned long n_levels = l_pyramid.size(); if (n_levels == 0) return matrix<>(); /* reconstruct original image */ matrix<> m(l_pyramid[n_levels-1]); for (unsigned long n = (n_levels-1); n > 0; n--) { const matrix<>& l_curr = l_pyramid[n-1]; m = lib_image::resample_2D(m, l_curr._dims[0], l_curr._dims[1]); m += l_curr; } return m; } /*************************************************************************** * Gaussian kernels. ***************************************************************************/ /* * Gaussian kernel (1D). * * Specify the standard deviation and (optionally) the support. * The length of the returned vector is 2*support + 1. * The support defaults to 3*sigma. * The kernel is normalized to have unit L1 norm. * If returning a 1st or 2nd derivative, the kernel has zero mean. */ matrix<> lib_image::gaussian( double sigma, unsigned int deriv, bool hlbrt) { unsigned long support = static_cast<unsigned long>(math::ceil(3*sigma)); return lib_image::gaussian(sigma, deriv, hlbrt, support); } matrix<> lib_image::gaussian( double sigma, unsigned int deriv, bool hlbrt, unsigned long support) { /* enlarge support so that hilbert transform can be done efficiently */ unsigned long support_big = support; if (hlbrt) { support_big = 1; unsigned long temp = support; while (temp > 0) { support_big *= 2; temp /= 2; } } /* compute constants */ const double sigma2_inv = double(1)/(sigma*sigma); const double neg_two_sigma2_inv = double(-0.5)*sigma2_inv; /* compute gaussian (or gaussian derivative) */ unsigned long size = 2*support_big + 1; matrix<> m(size, 1); double x = -(static_cast<double>(support_big)); if (deriv == 0) { /* compute guassian */ for (unsigned long n = 0; n < size; n++, x++) m._data[n] = math::exp(x*x*neg_two_sigma2_inv); } else if (deriv == 1) { /* compute gaussian first derivative */ for (unsigned long n = 0; n < size; n++, x++) m._data[n] = math::exp(x*x*neg_two_sigma2_inv) * (-x); } else if (deriv == 2) { /* compute gaussian second derivative */ for (unsigned long n = 0; n < size; n++, x++) { double x2 = x * x; m._data[n] = math::exp(x2*neg_two_sigma2_inv) * (x2*sigma2_inv - 1); } } else { throw ex_invalid_argument("only derivatives 0, 1, 2 supported"); } /* take hilbert transform (if requested) */ if (hlbrt) { /* grab power of two sized submatrix (ignore last element) */ m._size--; m._dims[0]--; /* grab desired submatrix after hilbert transform */ array<unsigned long> start(2); array<unsigned long> end(2); start[0] = support_big - support; end[0] = start[0] + support + support; m = (lib_signal::hilbert(m)).submatrix(start, end); } /* make zero mean (if returning derivative) */ if (deriv > 0) m -= mean(m); /* make unit L1 norm */ m /= sum(abs(m)); return m; } /* * Gaussian kernel (2D). * * Specify the standard deviation along each axis, and (optionally) the * orientation (in radians). In addition, optionally specify the support. * The support defaults to 3*sigma (automatically adjusted for rotation). * * The 1st or 2nd derivative and/or the hilbert transform can optionally * be taken along the y-axis prior to rotation. * * The kernel is normalized to have unit L1 norm. * If returning a 1st or 2nd derivative, the kernel has zero mean. */ matrix<> lib_image::gaussian_2D( double sigma_x, double sigma_y, double ori, unsigned int deriv, bool hlbrt) { /* compute support from rotated corners of original support box */ unsigned long support_x = static_cast<unsigned long>(math::ceil(3*sigma_x)); unsigned long support_y = static_cast<unsigned long>(math::ceil(3*sigma_y)); unsigned long support_x_rot = support_x_rotated(support_x, support_y, ori); unsigned long support_y_rot = support_y_rotated(support_x, support_y, ori); /* compute gaussian */ return lib_image::gaussian_2D( sigma_x, sigma_y, ori, deriv, hlbrt, support_x_rot, support_y_rot ); } matrix<> lib_image::gaussian_2D( double sigma_x, double sigma_y, double ori, unsigned int deriv, bool hlbrt, unsigned long support_x, unsigned long support_y) { /* compute size of larger grid for axis-aligned gaussian */ /* (reverse rotate corners of bounding box by orientation) */ unsigned long support_x_rot = support_x_rotated(support_x, support_y, -ori); unsigned long support_y_rot = support_y_rotated(support_x, support_y, -ori); /* compute 1D kernels */ matrix<> mx = lib_image::gaussian(sigma_x, 0, false, support_x_rot); matrix<> my = lib_image::gaussian(sigma_y, deriv, hlbrt, support_y_rot); /* compute 2D kernel from product of 1D kernels */ matrix<> m(mx._size, my._size); unsigned long n = 0; for (unsigned long n_x = 0; n_x < mx._size; n_x++) { for (unsigned long n_y = 0; n_y < my._size; n_y++) { m._data[n] = mx._data[n_x] * my._data[n_y]; n++; } } /* rotate 2D kernel by orientation */ m = lib_image::rotate_2D_crop(m, ori, 2*support_x + 1, 2*support_y + 1); /* make zero mean (if returning derivative) */ if (deriv > 0) m -= mean(m); /* make unit L1 norm */ m /= sum(abs(m)); return m; } /* * Gaussian center-surround kernel (2D). * * Specify the standard deviation along each axis, and (optionally) the * orientation (in radians). In addition, optionally specify the support. * The support defaults to 3*sigma (automatically adjusted for rotation). * * The center-surround kernel is the difference of a Gaussian with the * specified standard deviation and one with a standard deviation scaled * by the specified factor. * * The kernel is normalized to have unit L1 norm and zero mean. */ matrix<> lib_image::gaussian_cs_2D( double sigma_x, double sigma_y, double ori, double scale_factor) { /* compute support from rotated corners of original support box */ unsigned long support_x = static_cast<unsigned long>(math::ceil(3*sigma_x)); unsigned long support_y = static_cast<unsigned long>(math::ceil(3*sigma_y)); unsigned long support_x_rot = support_x_rotated(support_x, support_y, ori); unsigned long support_y_rot = support_y_rotated(support_x, support_y, ori); /* compute gaussian */ return lib_image::gaussian_cs_2D( sigma_x, sigma_y, ori, scale_factor, support_x_rot, support_y_rot ); } matrix<> lib_image::gaussian_cs_2D( double sigma_x, double sigma_y, double ori, double scale_factor, unsigned long support_x, unsigned long support_y) { /* compute standard deviation for center kernel */ double sigma_x_c = sigma_x / scale_factor; double sigma_y_c = sigma_y / scale_factor; /* compute center and surround kernels */ matrix<> m_center = lib_image::gaussian_2D( sigma_x_c, sigma_y_c, ori, 0, false, support_x, support_y ); matrix<> m_surround = lib_image::gaussian_2D( sigma_x, sigma_y, ori, 0, false, support_x, support_y ); /* compute center-surround kernel */ matrix<> m = m_surround - m_center; /* make zero mean and unit L1 norm */ m -= mean(m); m /= sum(abs(m)); return m; } /*************************************************************************** * Filter banks. ***************************************************************************/ /* * Get the standard set of filter orientations. * * The standard orientations are k*pi/n for k in [0,n) where n is the * number of orientation requested. */ array<double> lib_image::standard_filter_orientations(unsigned long n_ori) { array<double> oris(n_ori); double ori = 0; double ori_step = (n_ori > 0) ? (M_PIl / static_cast<double>(n_ori)) : 0; for (unsigned long n = 0; n < n_ori; n++, ori += ori_step) oris[n] = ori; return oris; } namespace { /* * Runnable object for creating a filter. */ class filter_creator : public runnable { public: /* * Constructor. */ explicit filter_creator( double sigma_x, /* sigma x */ double sigma_y, /* sigma y */ double ori, /* orientation */ unsigned int deriv, /* derivative in y-direction (0, 1, or 2) */ bool hlbrt, /* take hilbert transform in y-direction? */ unsigned long support_x, /* x support */ unsigned long support_y, /* y support */ matrix<>& f) /* output filter matrix */ : _sigma_x(sigma_x), _sigma_y(sigma_y), _ori(ori), _deriv(deriv), _hlbrt(hlbrt), _support_x(support_x), _support_y(support_y), _f(f) { } /* * Destructor. */ virtual ~filter_creator() { /* do nothing */ } /* * Create the filter. */ virtual void run() { _f = lib_image::gaussian_2D( _sigma_x, _sigma_y, _ori, _deriv, _hlbrt, _support_x, _support_y ); } protected: double _sigma_x; /* sigma x */ double _sigma_y; /* sigma y */ double _ori; /* orientation */ unsigned int _deriv; /* derivative in y-direction (0, 1, or 2) */ bool _hlbrt; /* take hilbert transform in y-direction? */ unsigned long _support_x; /* x support */ unsigned long _support_y; /* y support */ matrix<>& _f; /* output filter matrix */ }; } /* namespace */ /* * Oriented Gaussian derivative filters. * * Create a filter set consisting of rotated versions of the Gaussian * derivative filter with the specified parameters. * * The filters are created at the standard orientations unless custom * orientations are specified. * * Specify the standard deviation (sigma) along the longer principle axis. * The standard deviation along the other principle axis is sigma/r where * r is the elongation ratio. * * Each returned filter is an (s+1) x (s+1) matrix where s = 3*sigma. * * Filters are created in parallel when possible. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::gaussian_filters( unsigned long n_ori, double sigma, unsigned int deriv, bool hlbrt, double elongation) { array<double> oris = lib_image::standard_filter_orientations(n_ori); return lib_image::gaussian_filters(oris, sigma, deriv, hlbrt, elongation); } auto_collection< matrix<>, array_list< matrix<> > > lib_image::gaussian_filters( const array<double>& oris, double sigma, unsigned int deriv, bool hlbrt, double elongation) { /* compute support from sigma */ unsigned long support = static_cast<unsigned long>(math::ceil(3*sigma)); double sigma_x = sigma; double sigma_y = sigma_x/elongation; /* allocate collection to hold filters */ auto_collection< matrix<>, array_list< matrix<> > > filters( new array_list< matrix<> >() ); /* allocate collection of filter creators */ auto_collection< runnable, list<runnable> > filter_creators( new list<runnable>() ); /* setup filter creators */ unsigned long n_ori = oris.size(); for (unsigned long n = 0; n < n_ori; n++) { auto_ptr< matrix<> > f(new matrix<>()); auto_ptr<filter_creator> f_creator( new filter_creator( sigma_x, sigma_y, oris[n], deriv, hlbrt, support, support, *f ) ); filters->add(*f); f.release(); filter_creators->add(*f_creator); f_creator.release(); } /* create filters */ child_thread::run(*filter_creators); return filters; } /* * Even and odd-symmetric filters for computing oriented edge energy. * * The even-symmetric filter is a Gaussian second-derivative and the odd- * symmetric filter is its Hilbert transform. The filters are elongated * by a ratio of 3:1 along their principle axis. Each filter set consists * of rotated versions of the same filter. * * Each returned filter is an (s+1) x (s+1) matrix where s = 3*sigma and * sigma is the specified standard deviation. * * Filters are created in parallel when possible. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::oe_filters_even( unsigned long n_ori, double sigma) { return lib_image::gaussian_filters(n_ori, sigma, 2, false, 3.0); } auto_collection< matrix<>, array_list< matrix<> > > lib_image::oe_filters_odd( unsigned long n_ori, double sigma) { return lib_image::gaussian_filters(n_ori, sigma, 2, true, 3.0); } void lib_image::oe_filters( unsigned long n_ori, double sigma, auto_collection< matrix<>, array_list< matrix<> > >& filters_even, auto_collection< matrix<>, array_list< matrix<> > >& filters_odd) { /* runnable class for creating oe filters */ class oe_filters_creator : public runnable { public: /* * Constructor. */ explicit oe_filters_creator( unsigned long n_ori, double sigma, bool even_or_odd, auto_collection< matrix<>, array_list< matrix<> > >& filters) : _n_ori(n_ori), _sigma(sigma), _even_or_odd(even_or_odd), _filters(filters) { } /* * Destructor. */ virtual ~oe_filters_creator() { /* do nothing */ } /* * Create the filter set. */ virtual void run() { _filters = _even_or_odd ? lib_image::oe_filters_odd(_n_ori, _sigma) : lib_image::oe_filters_even(_n_ori, _sigma); } protected: unsigned long _n_ori; double _sigma; bool _even_or_odd; auto_collection< matrix<>, array_list< matrix<> > >& _filters; }; /* create oe filters */ oe_filters_creator f_even_creator(n_ori, sigma, false, filters_even); oe_filters_creator f_odd_creator(n_ori, sigma, true, filters_odd); child_thread::run(f_even_creator, f_odd_creator); } /* * Filters for computing textons. * * The set of texton filters is the union of the even and odd-symmetric * filter sets above in addition to a center-surround difference of * Gaussians filter. * * Each returned filter is an (s+1) x (s+1) matrix where s = 3*sigma and * sigma is the specified standard deviation. * * Filters are created in parallel when possible. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::texton_filters( unsigned long n_ori, double sigma) { /* allocate collection to hold filters */ auto_collection< matrix<>, array_list< matrix<> > > filters( new array_list< matrix<> >() ); /* get even and odd-symmetric filter sets */ auto_collection< matrix<>, array_list< matrix<> > > filters_even; auto_collection< matrix<>, array_list< matrix<> > > filters_odd; lib_image::oe_filters(n_ori, sigma, filters_even, filters_odd); /* add even and odd-symmetric filters to collection */ filters->add(*filters_even); filters_even.release(); filters->add(*filters_odd); filters_odd.release(); /* compute center surround filter */ unsigned long support = static_cast<unsigned long>(math::ceil(3*sigma)); matrix<> f_cs = lib_image::gaussian_cs_2D( sigma, sigma, 0, M_SQRT2l, support, support ); /* add center surround filter to collection */ auto_ptr< matrix<> > f_ptr(new matrix<>()); matrix<>::swap(f_cs, *f_ptr); filters->add(*f_ptr); f_ptr.release(); return filters; } /*************************************************************************** * Image filtering. ***************************************************************************/ namespace { /* * Abstract base class for runnable filterers. */ class filterer_base : public runnable { public: /* * Constructor. */ explicit filterer_base( const matrix<>& m, /* image */ const matrix<>& f, /* filter */ matrix<>& m_result) /* filter output */ : _m(m), _f(f), _m_result(m_result) { } /* * Destructor. */ virtual ~filterer_base() { /* do nothing */ } /* * Run the filter. */ virtual void run() = 0; protected: const matrix<>& _m; /* image */ const matrix<>& _f; /* filter */ matrix<>& _m_result; /* filter output */ }; /* * Runnable object for convolving an image with a filter. */ class filterer : public filterer_base { public: /* * Constructor. */ explicit filterer( const matrix<>& m, /* image */ const matrix<>& f, /* filter */ matrix<>& m_result) /* filter output */ : filterer_base(m, f, m_result) { } /* * Destructor. */ virtual ~filterer() { /* do nothing */ } /* * Convolve image with filter. */ virtual void run() { _m_result = conv_crop(_m, _f); } }; /* * Runnable object for convolving an image with a filter and squaring * the result. */ class filterer_sq : public filterer_base { public: /* * Constructor. */ explicit filterer_sq( const matrix<>& m, /* image */ const matrix<>& f, /* filter */ matrix<>& m_result) /* filter output */ : filterer_base(m, f, m_result) { } /* * Destructor. */ virtual ~filterer_sq() { /* do nothing */ } /* * Convolve image with filter and square result. */ virtual void run() { matrix<> m_conv = conv_crop(_m, _f); _m_result = prod(m_conv, m_conv); } }; /* * Abstract base class for runnable rectifying filterers. */ class filterer_rectified_base : public runnable { public: /* * Constructor. */ explicit filterer_rectified_base( const matrix<>& m, /* image */ const matrix<>& f, /* filter */ matrix<>& m_result_neg, /* negative rectified response */ matrix<>& m_result_pos) /* positive rectified response */ : _m(m), _f(f), _m_result_neg(m_result_neg), _m_result_pos(m_result_pos) { } /* * Destructor. */ virtual ~filterer_rectified_base() { /* do nothing */ } /* * Run the filter. */ virtual void run() = 0; protected: const matrix<>& _m; /* image */ const matrix<>& _f; /* filter */ matrix<>& _m_result_neg; /* negative filter output */ matrix<>& _m_result_pos; /* positive filter output */ }; /* * Runnable object for rectified filtering. */ class filterer_rectified : public filterer_rectified_base { public: /* * Constructor. */ explicit filterer_rectified( const matrix<>& m, /* image */ const matrix<>& f, /* filter */ matrix<>& m_result_neg, /* negative rectified response */ matrix<>& m_result_pos) /* positive rectified response */ : filterer_rectified_base(m, f, m_result_neg, m_result_pos) { } /* * Destructor. */ virtual ~filterer_rectified() { /* do nothing */ } /* * Convolve image with filter and rectify. */ virtual void run() { /* convolve with filter */ matrix<> m_conv = conv_crop(_m, _f); /* resize result matrices */ _m_result_neg.resize(0); _m_result_pos.resize(0); array<unsigned long> dims = m_conv.dimensions(); _m_result_neg.resize(dims); _m_result_pos.resize(dims); /* compute rectified signals */ unsigned long n_inds = m_conv.size(); for (unsigned long n = 0; n < n_inds; n++) { double v = m_conv[n]; if (v < 0) _m_result_neg[n] = -v; else _m_result_pos[n] = v; } } }; /* * Runnable object for squared rectified filtering. */ class filterer_rectified_sq : public filterer_rectified_base { public: /* * Constructor. */ explicit filterer_rectified_sq( const matrix<>& m, /* image */ const matrix<>& f, /* filter */ matrix<>& m_result_neg, /* negative rectified response */ matrix<>& m_result_pos) /* positive rectified response */ : filterer_rectified_base(m, f, m_result_neg, m_result_pos) { } /* * Destructor. */ virtual ~filterer_rectified_sq() { /* do nothing */ } /* * Convolve image with filter, rectify, and square. */ virtual void run() { /* convolve with filter */ matrix<> m_conv = conv_crop(_m, _f); /* resize result matrices */ _m_result_neg.resize(0); _m_result_pos.resize(0); array<unsigned long> dims = m_conv.dimensions(); _m_result_neg.resize(dims); _m_result_pos.resize(dims); /* compute rectified signals */ unsigned long n_inds = m_conv.size(); for (unsigned long n = 0; n < n_inds; n++) { double v = m_conv[n]; double v2 = v*v; if (v < 0) _m_result_neg[n] = v2; else _m_result_pos[n] = v2; } } }; } /* namespace */ /* * Image filtering. * * Return the convolution of the image with each filter (cropped so that * the result is the same size as the original image). * * Filter responses are computed in parallel when possible. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::filter( const matrix<>& m, const collection< matrix<> >& filters) { /* allocate collection to hold filter responses */ auto_collection< matrix<>, array_list< matrix<> > > responses( new array_list< matrix<> >() ); /* allocate collection of filterers */ auto_collection< runnable, list<runnable> > filterers(new list<runnable>()); /* setup filterers */ for (auto_ptr< iterator< matrix<> > > i = filters.iter_create(); i->has_next(); ) { matrix<>& f = i->next(); auto_ptr< matrix<> > m_result(new matrix<>()); auto_ptr<filterer> filt(new filterer(m, f, *m_result)); responses->add(*m_result); m_result.release(); filterers->add(*filt); filt.release(); } /* run filterers */ child_thread::run(*filterers); return responses; } /* * Image filtering. * * Return the square of the convolution of the image with each filter * (cropped so that the result is the same size as the original image). * * Filter responses are computed in parallel when possible. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::filter_sq( const matrix<>& m, const collection< matrix<> >& filters) { /* allocate collection to hold filter responses */ auto_collection< matrix<>, array_list< matrix<> > > responses( new array_list< matrix<> >() ); /* allocate collection of filterers */ auto_collection< runnable, list<runnable> > filterers(new list<runnable>()); /* setup filterers */ for (auto_ptr< iterator< matrix<> > > i = filters.iter_create(); i->has_next(); ) { matrix<>& f = i->next(); auto_ptr< matrix<> > m_result(new matrix<>()); auto_ptr<filterer_sq> filt(new filterer_sq(m, f, *m_result)); responses->add(*m_result); m_result.release(); filterers->add(*filt); filt.release(); } /* run filterers */ child_thread::run(*filterers); return responses; } /* * Image filtering and rectification. * * Return the rectified components of the convolution of the image with * each filter (cropped so that the result is the same size as the original * image). * * Filter responses are computed in parallel when possible. */ void lib_image::filter_rectified( const matrix<>& m, const collection< matrix<> >& filters, auto_collection< matrix<>, array_list< matrix<> > >& responses_neg, auto_collection< matrix<>, array_list< matrix<> > >& responses_pos) { /* allocate collections to hold filter responses */ responses_neg.reset(new array_list< matrix<> >()); responses_pos.reset(new array_list< matrix<> >()); /* allocate collection of filterers */ auto_collection< runnable, list<runnable> > filterers(new list<runnable>()); /* setup filterers */ for (auto_ptr< iterator< matrix<> > > i = filters.iter_create(); i->has_next(); ) { matrix<>& f = i->next(); auto_ptr< matrix<> > m_result_neg(new matrix<>()); auto_ptr< matrix<> > m_result_pos(new matrix<>()); auto_ptr<filterer_rectified> filt( new filterer_rectified(m, f, *m_result_neg, *m_result_pos) ); responses_neg->add(*m_result_neg); m_result_neg.release(); responses_pos->add(*m_result_pos); m_result_pos.release(); filterers->add(*filt); filt.release(); } /* run filterers */ child_thread::run(*filterers); } /* * Image filtering and rectification. * * Return the square of the rectified components of the convolution of the * image with each filter (cropped so that the result is the same size as * the original image). * * Filter responses are computed in parallel when possible. */ void lib_image::filter_rectified_sq( const matrix<>& m, const collection< matrix<> >& filters, auto_collection< matrix<>, array_list< matrix<> > >& responses_neg, auto_collection< matrix<>, array_list< matrix<> > >& responses_pos) { /* allocate collections to hold filter responses */ responses_neg.reset(new array_list< matrix<> >()); responses_pos.reset(new array_list< matrix<> >()); /* allocate collection of filterers */ auto_collection< runnable, list<runnable> > filterers(new list<runnable>()); /* setup filterers */ for (auto_ptr< iterator< matrix<> > > i = filters.iter_create(); i->has_next(); ) { matrix<>& f = i->next(); auto_ptr< matrix<> > m_result_neg(new matrix<>()); auto_ptr< matrix<> > m_result_pos(new matrix<>()); auto_ptr<filterer_rectified_sq> filt( new filterer_rectified_sq(m, f, *m_result_neg, *m_result_pos) ); responses_neg->add(*m_result_neg); m_result_neg.release(); responses_pos->add(*m_result_pos); m_result_pos.release(); filterers->add(*filt); filt.release(); } /* run filterers */ child_thread::run(*filterers); } namespace { /* * Runnable object for stacking multiple matrices into a matrix of vectors. * Automatically split the stacking task into parallel subtasks. */ class vectorizer : public runnable { public: /* * Constructor. * The result matrix must have been initialized to an appropriately sized * matrix of length zero vectors. */ explicit vectorizer( const array_list< matrix<> >& m_arr, /* matrices to stack */ unsigned long start, /* first index to process */ unsigned long end, /* last index to process */ matrix< matrix<> >& m) /* resulting matrix of vectors */ : _m_arr(m_arr), _start(start), _end(end), _m(m) { } /* * Destructor. */ virtual ~vectorizer() { /* do nothing */ } /* * Stack matrices. */ virtual void run() { if ((thread::processors() > 1) && (_start < _end)) { /* split stacking task */ unsigned long mid = (_start + _end)/2; vectorizer v_left(_m_arr, _start, mid, _m); vectorizer v_right(_m_arr, mid+1, _end, _m); child_thread::run(v_left, v_right); } else { /* stack matrices */ unsigned long length = _m_arr.size(); for (unsigned long n = _start; n <= _end; n++) { matrix<>& v = _m[n]; v.resize(length); for (unsigned long ind = 0; ind < length; ind++) v[ind] = (_m_arr[ind])[n]; } } } protected: const array_list< matrix<> >& _m_arr; /* matrices to stack */ unsigned long _start; /* first index to process */ unsigned long _end; /* last index to process */ matrix< matrix<> >& _m; /* resulting matrix of vectors */ }; } /* namespace */ /* * Stack the output of multiple filters into column vectors. */ matrix< matrix<> > lib_image::vectorize_filter_responses( const collection< matrix<> >& filter_responses) { /* create array_list of responses */ array_list< matrix<> > responses(filter_responses); /* check number of filters */ unsigned long n_filt = responses.size(); if (n_filt == 0) return matrix< matrix<> >(); /* check that all response matrices are the same size */ for (unsigned long n = 1; n < n_filt; n++) matrix<>::assert_dims_equal(responses[0]._dims, responses[n]._dims); /* stack matrices */ matrix< matrix<> > m(responses[0]._dims); if (m._size > 0) { vectorizer v(responses, 0, (m._size-1), m); v.run(); } return m; } /*************************************************************************** * Image quantization. ***************************************************************************/ /* * Vector quantize filter responses. * Return both the cluster assignments and cluster centroids. */ matrix<unsigned long> lib_image::cluster_filter_responses( const collection< matrix<> >& responses, const centroid_clusterer< matrix<> >& clusterer, auto_collection< matrix<>, array_list< matrix<> > >& centroids) { /* stack filter responses into vectors */ matrix< matrix<> > vecs = lib_image::vectorize_filter_responses(responses); /* cluster vectors */ return lib_image::cluster_filter_responses(vecs, clusterer, centroids); } matrix<unsigned long> lib_image::cluster_filter_responses( const matrix< matrix<> >& responses, const centroid_clusterer< matrix<> >& clusterer, auto_collection< matrix<>, array_list< matrix<> > >& centroids) { /* create collection of vectors */ list< matrix<> > vec_list; for (unsigned long n = 0; n < responses._size; n++) vec_list.add(responses._data[n]); /* cluster */ array<unsigned long> assign = clusterer.cluster(vec_list, centroids); /* convert assignment array to assignment matrix */ matrix<unsigned long> m_assign = matrix<unsigned long>::to_matrix(assign); m_assign.reshape(responses._dims); return m_assign; } /* * Cluster image values. * Return both the cluster assignments and cluster centroids. */ matrix<unsigned long> lib_image::cluster_values( const matrix<>& m, const centroid_clusterer<double>& clusterer, auto_collection< double, array_list<double> >& centroids) { /* create collection of values */ list<double> value_list; for (unsigned long n = 0; n < m._size; n++) value_list.add(m._data[n]); /* cluster */ array<unsigned long> assign = clusterer.cluster(value_list, centroids); /* convert assignment array to assignment matrix */ matrix<unsigned long> m_assign = matrix<unsigned long>::to_matrix(assign); m_assign.reshape(m._dims); return m_assign; } /* * Quantize image values into uniformly spaced bins in [0,1]. * Return the assignments and bin centroids. */ matrix<unsigned long> lib_image::quantize_values( const matrix<>& m, unsigned long n_bins) { auto_collection< double, array_list<double> > centroids; return lib_image::quantize_values(m, n_bins, centroids); } matrix<unsigned long> lib_image::quantize_values( const matrix<>& m, unsigned long n_bins, auto_collection< double, array_list<double> >& centroids) { /* check arguments */ if (n_bins == 0) throw ex_invalid_argument("n_bins must be > 0"); /* create centroids */ centroids.reset(new array_list<double>()); for (unsigned long n = 0; n < n_bins; n++) { auto_ptr<double> val( new double( (static_cast<double>(n) + 0.5)/static_cast<double>(n_bins) ) ); centroids->add(*val); val.release(); } /* compute assignments */ matrix<unsigned long> assign(m._dims); for (unsigned long n = 0; n < m._size; n++) { unsigned long bin = static_cast<unsigned long>( math::floor(m._data[n]*static_cast<double>(n_bins)) ); if (bin == n_bins) { bin = n_bins-1; } assign._data[n] = bin; } return assign; } /* * Construct a quantized image by looking up the value of the centroid to * which each element is assigned. */ matrix<> lib_image::quantized_image( const matrix<unsigned long>& assignments, const array_list<double>& centroids) { matrix<> m_quantized(assignments._dims); for (unsigned long n = 0; n < assignments._size; n++) m_quantized._data[n] = centroids[assignments._data[n]]; return m_quantized; } /*************************************************************************** * Edge detection. ***************************************************************************/ /* * Compute oriented edge energy. * * Given that fe and fo are the even and odd-symmetric filters at a specific * orientation, the even and odd components of oriented energy (oe_e, oe_o) * at that orientation for an image I are defined as: * * oe_e = (I ** fe) * oe_o = (I ** fo) * * where ** denotes convolution. */ void lib_image::edge_oe( const matrix<>& m, const matrix<>& fe, const matrix<>& fo, auto_ptr< matrix<> >& oe_even, auto_ptr< matrix<> >& oe_odd) { /* allocate result */ oe_even.reset(new matrix<>()); oe_odd.reset(new matrix<>()); /* setup filterers */ filterer filt_even(m, fe, *oe_even); filterer filt_odd(m, fo, *oe_odd); /* compute oe */ child_thread::run(filt_even, filt_odd); } /* * Compute oriented edge energy (at multiple orientations/scales). * * Different orientations/scales are processed in parallel when possible. */ void lib_image::edge_oe( const matrix<>& m, const collection< matrix<> >& fe_set, const collection< matrix<> >& fo_set, auto_collection< matrix<>, array_list< matrix<> > >& oes_even, auto_collection< matrix<>, array_list< matrix<> > >& oes_odd) { /* check arguments */ unsigned long n_filt = fe_set.size(); if (n_filt != fo_set.size()) throw ex_invalid_argument( "even and odd-symmetric filter sets do not match" ); /* place all filters in one collection */ array_list< matrix<> > filters; filters.add(fe_set); filters.add(fo_set); /* compute filter responses */ auto_collection< matrix<>, array_list< matrix<> > > responses = lib_image::filter(m, filters); /* allocate collections to hold rectified oe */ oes_even.reset(new array_list< matrix<> >()); oes_odd.reset(new array_list< matrix<> >()); /* read off even components */ for (unsigned long n = 0; n < n_filt; n++) { auto_ptr< matrix<> > oe_even(&(responses->remove_head())); oes_even->add(*oe_even); oe_even.release(); } /* read off odd components */ for (unsigned long n = 0; n < n_filt; n++) { auto_ptr< matrix<> > oe_odd(&(responses->remove_head())); oes_odd->add(*oe_odd); oe_odd.release(); } } /* * Compute rectified oriented edge energy. * * Given that fo is the odd-symmetric filter at a specified orientation, the * rectified oriented energy (oe-, oe+) at that orientation for an image I * is defined as: * * oe- = [I ** fo]- * oe+ = [I ** fo]+ * * where ** denotes convolution, and -/+ denote negative/positive * rectification. */ void lib_image::edge_oe_rectified( const matrix<>& m, const matrix<>& fo, auto_ptr< matrix<> >& oe_neg, auto_ptr< matrix<> >& oe_pos) { /* allocate result */ oe_neg.reset(new matrix<>()); oe_pos.reset(new matrix<>()); /* compute rectified oe */ filterer_rectified filt_rect(m, fo, *oe_neg, *oe_pos); filt_rect.run(); } /* * Compute rectified oriented edge energy (at multiple orientations/scales). * * Different orientations/scales are processed in parallel when possible. */ void lib_image::edge_oe_rectified( const matrix<>& m, const collection< matrix<> >& fo_set, auto_collection< matrix<>, array_list< matrix<> > >& oes_neg, auto_collection< matrix<>, array_list< matrix<> > >& oes_pos) { lib_image::filter_rectified(m, fo_set, oes_neg, oes_pos); } namespace { /* * Runnable class for combining oe components. */ class oe_combiner : public runnable { public: /* * Constructor. */ explicit oe_combiner( const matrix<>& oe_even, /* oe_e */ const matrix<>& oe_odd, /* oe_o */ matrix<>& oe_strength, /* returned oe */ matrix<>& oe_phase) /* returned oe phase */ : _oe_even(oe_even), _oe_odd(oe_odd), _oe_strength(oe_strength), _oe_phase(oe_phase) { } /* * Destructor. */ virtual ~oe_combiner() { /* do nothing */ } /* * Compute oe strength and phase. */ virtual void run() { _oe_strength = sqrt(prod(_oe_even, _oe_even) + prod(_oe_odd, _oe_odd)).real(); _oe_phase = atan2(_oe_odd, _oe_even); } protected: const matrix<>& _oe_even; /* oe_e */ const matrix<>& _oe_odd; /* oe_o */ matrix<>& _oe_strength; /* returned oe */ matrix<>& _oe_phase; /* returned oe phase */ }; } /* namespace */ /* * Combine components of oriented edge energy into edge maps. * * For each pair of components, the oriented energy is computed as: * * oe_strength = sqrt((oe_e)^2 + (oe_o)^2) * oe_phase = atan2(oe_o, oe_e) * * where oe_o and oe_e are the even and odd components of oe, respectively. */ void lib_image::combine_edge_oe( const collection< matrix<> >& oes_even, const collection< matrix<> >& oes_odd, auto_collection< matrix<>, array_list< matrix<> > >& oes_strength, auto_collection< matrix<>, array_list< matrix<> > >& oes_phase) { /* check arguments - number of components */ if (oes_even.size() != oes_odd.size()) { throw ex_invalid_argument( "number of oe_even matrices different from number of oe_odd matrices" ); } /* initialize result */ oes_strength.reset(new array_list< matrix<> >()); oes_phase.reset(new array_list< matrix<> >()); /* allocate collection to hold combiners */ auto_collection< runnable, list<runnable> > oe_combiners( new list<runnable>() ); /* setup oe combiners */ auto_ptr< iterator< matrix<> > > i_even = oes_even.iter_create(); auto_ptr< iterator< matrix<> > > i_odd = oes_odd.iter_create(); while (i_even->has_next()) { auto_ptr< matrix<> > oe_strength(new matrix<>()); auto_ptr< matrix<> > oe_phase(new matrix<>()); auto_ptr<oe_combiner> oe_comb( new oe_combiner( i_even->next(), i_odd->next(), *oe_strength, *oe_phase ) ); oes_strength->add(*oe_strength); oe_strength.release(); oes_phase->add(*oe_phase); oe_phase.release(); oe_combiners->add(*oe_comb); oe_comb.release(); } /* run oe combiners */ child_thread::run(*oe_combiners); } namespace { /* * Runnable class for combining rectified oe components. */ class oe_rectified_combiner : public runnable { public: /* * Constructor. */ explicit oe_rectified_combiner( const matrix<>& oe_neg, /* oe- */ const matrix<>& oe_pos, /* oe+ */ matrix<>& oe_strength, /* returned oe */ matrix<>& oe_polarity) /* returned oe polarity */ : _oe_neg(oe_neg), _oe_pos(oe_pos), _oe_strength(oe_strength), _oe_polarity(oe_polarity) { } /* * Destructor. */ virtual ~oe_rectified_combiner() { /* do nothing */ } /* * Compute oe strength and phase. */ virtual void run() { _oe_strength = _oe_neg + _oe_pos; _oe_polarity.resize(0); _oe_polarity.resize(_oe_strength.dimensions()); unsigned long size = _oe_polarity.size(); for (unsigned long n = 0; n < size; n++) { if (_oe_neg[n] > 0) _oe_polarity[n] = -1; else if (_oe_pos[n] > 0) _oe_polarity[n] = 1; } } protected: const matrix<>& _oe_neg; /* oe- */ const matrix<>& _oe_pos; /* oe+ */ matrix<>& _oe_strength; /* returned oe */ matrix<>& _oe_polarity; /* returned oe polarity */ }; } /* namespace */ /* * Combine components of rectified oriented edge energy into edge maps. * * For each pair of components, the oriented energy is computed as: * * oe_strength = sqrt((oe-)^2 + (oe+)^2) * = (oe-) + (oe+) * * oe_polarity = sign(-(oe-) + (oe+)) * * where oe- and oe+ are the negative and positive rectified components * of oe, respectively. * * The polarity is -1 at locations for which oe- was the dominant edge, +1 * at locations for which oe+ was the dominant edge, and 0 at locations * with no edge strength. */ void lib_image::combine_edge_oe_rectified( const collection< matrix<> >& oes_neg, const collection< matrix<> >& oes_pos, auto_collection< matrix<>, array_list< matrix<> > >& oes_strength, auto_collection< matrix<>, array_list< matrix<> > >& oes_polarity) { /* check arguments - number of components */ if (oes_neg.size() != oes_pos.size()) { throw ex_invalid_argument( "number of oe- matrices different from number of oe+ matrices" ); } /* initialize result */ oes_strength.reset(new array_list< matrix<> >()); oes_polarity.reset(new array_list< matrix<> >()); /* allocate collection to hold combiners */ auto_collection< runnable, list<runnable> > oe_combiners( new list<runnable>() ); /* setup oe combiners */ auto_ptr< iterator< matrix<> > > i_neg = oes_neg.iter_create(); auto_ptr< iterator< matrix<> > > i_pos = oes_pos.iter_create(); while (i_neg->has_next()) { auto_ptr< matrix<> > oe_strength(new matrix<>()); auto_ptr< matrix<> > oe_polarity(new matrix<>()); auto_ptr<oe_rectified_combiner> oe_comb( new oe_rectified_combiner( i_neg->next(), i_pos->next(), *oe_strength, *oe_polarity ) ); oes_strength->add(*oe_strength); oe_strength.release(); oes_polarity->add(*oe_polarity); oe_polarity.release(); oe_combiners->add(*oe_comb); oe_comb.release(); } /* run oe combiners */ child_thread::run(*oe_combiners); } namespace { /* * Runnable object for computing the index of the maximum value in a stack of * matrices. Computation is performed in parallel across the result matrix. */ class matrix_max_selector : public runnable { public: /* * Constructor. */ explicit matrix_max_selector( const array_list< matrix<> >& matrices, /* stack of matrices */ unsigned long start, /* first index to process */ unsigned long end, /* last index to process */ matrix<unsigned long>& index) /* returned index matrix */ : _matrices(matrices), _start(start), _end(end), _index(index) { } /* * Destructor. */ virtual ~matrix_max_selector() { /* do nothing */ } /* * Find indices of maximum values. */ virtual void run() { if ((thread::processors() > 1) && (_start < _end)) { /* split task */ unsigned long mid = (_start + _end)/2; matrix_max_selector m_left(_matrices, _start, mid, _index); matrix_max_selector m_right(_matrices, mid+1, _end, _index); child_thread::run(m_left, m_right); } else { /* compute indices of maximum values */ unsigned long n_matrices = _matrices.size(); if (n_matrices > 0) { for (unsigned long n = _start; n <= _end; n++) { double max_val = (_matrices[0])[n]; unsigned long max_ind = 0; for (unsigned long ind = 1; ind < n_matrices; ind++) { double val = (_matrices[ind])[n]; if (val > max_val) { max_val = val; max_ind = ind; } } _index[n] = max_ind; } } } } /* * Select values from a matrix stack given the indices. */ static matrix<> select_values( const array_list< matrix<> >& matrices, /* stack of matrices */ const matrix<unsigned long>& index) /* index */ { matrix<> m(index.dimensions()); unsigned long size = m.size(); for (unsigned long n = 0; n < size; n++) m[n] = (matrices[index[n]])[n]; return m; } /* * Select values from an array given the indices. */ static matrix<> select_values( const array<double>& arr, /* array */ const matrix<unsigned long>& index) /* index */ { matrix<> m(index.dimensions()); unsigned long size = m.size(); for (unsigned long n = 0; n < size; n++) m[n] = arr[index[n]]; return m; } protected: const array_list< matrix<> >& _matrices; /* stack of matrices */ unsigned long _start; /* first index to process */ unsigned long _end; /* last index to process */ matrix<unsigned long>& _index; /* returned index matrix */ }; } /* namespace */ /* * Combine oriented edge energy into a single edge map. * * Each location is assigned edge strength equal to the maximum oe value * over all orientations. The phase, atan2(oe_o, oe_e), for the maximum * oe value at each location is also returned. In addition, the dominant * orientation at each location is returned. * * Unless otherwise specified, the orientations corresponding to the input * collection of n oriented edge maps are assumed to be k*pi/n for integer * k in [0,n). */ void lib_image::combine_edge_oe( const collection< matrix<> >& oes_even, const collection< matrix<> >& oes_odd, auto_ptr< matrix<> >& edge, auto_ptr< matrix<> >& edge_phase, auto_ptr< matrix<> >& edge_ori) { unsigned long n_ori = oes_even.size(); array<double> oris = lib_image::standard_filter_orientations(n_ori); lib_image::combine_edge_oe( oes_even, oes_odd, oris, edge, edge_phase, edge_ori ); } void lib_image::combine_edge_oe( const collection< matrix<> >& oes_even, const collection< matrix<> >& oes_odd, const array<double>& oris, auto_ptr< matrix<> >& edge, auto_ptr< matrix<> >& edge_phase, auto_ptr< matrix<> >& edge_ori) { /* check arguments - number of orientations */ unsigned long n_ori = oris.size(); if (oes_even.size() != n_ori) throw ex_invalid_argument( "number of oe_even matrices different from number of orientations" ); if (oes_odd.size() != n_ori) throw ex_invalid_argument( "number of oe_odd matrices different from number of orientations" ); /* initialize edge map */ edge.reset(new matrix<>()); edge_phase.reset(new matrix<>()); edge_ori.reset(new matrix<>()); /* check if nontrivial result */ if (n_ori > 0) { /* combine oe components */ auto_collection< matrix<>, array_list< matrix<> > > oes_strength; auto_collection< matrix<>, array_list< matrix<> > > oes_phase; lib_image::combine_edge_oe( oes_even, oes_odd, oes_strength, oes_phase ); /* check that all combined components have the same size */ array<unsigned long> dims = (*oes_strength)[0]._dims; for (unsigned long n = 0; n < n_ori; n++) { matrix<>::assert_dims_equal(dims, (*oes_strength)[n]._dims); matrix<>::assert_dims_equal(dims, (*oes_phase)[n]._dims); } /* compute indices of maximum oe values */ matrix<unsigned long> index(dims); if (index._size > 0) { matrix_max_selector m_select(*oes_strength, 0, index._size-1, index); m_select.run(); } /* select responses from channel with max oe value */ *edge = matrix_max_selector::select_values(*oes_strength, index); *edge_phase = matrix_max_selector::select_values(*oes_phase, index); *edge_ori = matrix_max_selector::select_values(oris, index); } } /* * Combine rectified oriented edge energy into a single edge map. * * Each location is assigned edge strength equal to the maximum oe value * over all orientations. The polarity, sign(-(oe-) + (oe+)), for the * maximum oe value at each location is also returned. In addition, the * dominant orientation at each location is returned. * * Unless otherwise specified, the orientations corresponding to the input * collection of n oriented edge maps are assumed to be k*pi/n for integer * k in [0,n). */ void lib_image::combine_edge_oe_rectified( const collection< matrix<> >& oes_neg, const collection< matrix<> >& oes_pos, auto_ptr< matrix<> >& edge, auto_ptr< matrix<> >& edge_polarity, auto_ptr< matrix<> >& edge_ori) { unsigned long n_ori = oes_neg.size(); array<double> oris = lib_image::standard_filter_orientations(n_ori); lib_image::combine_edge_oe_rectified( oes_neg, oes_pos, oris, edge, edge_polarity, edge_ori ); } void lib_image::combine_edge_oe_rectified( const collection< matrix<> >& oes_neg, const collection< matrix<> >& oes_pos, const array<double>& oris, auto_ptr< matrix<> >& edge, auto_ptr< matrix<> >& edge_polarity, auto_ptr< matrix<> >& edge_ori) { /* check arguments - number of orientations */ unsigned long n_ori = oris.size(); if (oes_neg.size() != n_ori) throw ex_invalid_argument( "number of oe- matrices different from number of orientations" ); if (oes_pos.size() != n_ori) throw ex_invalid_argument( "number of oe+ matrices different from number of orientations" ); /* initialize edge map */ edge.reset(new matrix<>()); edge_polarity.reset(new matrix<>()); edge_ori.reset(new matrix<>()); /* check if nontrivial result */ if (n_ori > 0) { /* combine oe components */ auto_collection< matrix<>, array_list< matrix<> > > oes_strength; auto_collection< matrix<>, array_list< matrix<> > > oes_polarity; lib_image::combine_edge_oe_rectified( oes_neg, oes_pos, oes_strength, oes_polarity ); /* check that all combined components have the same size */ array<unsigned long> dims = (*oes_strength)[0]._dims; for (unsigned long n = 0; n < n_ori; n++) { matrix<>::assert_dims_equal(dims, (*oes_strength)[n]._dims); matrix<>::assert_dims_equal(dims, (*oes_polarity)[n]._dims); } /* compute indices of maximum oe values */ matrix<unsigned long> index(dims); if (index._size > 0) { matrix_max_selector m_select(*oes_strength, 0, index._size-1, index); m_select.run(); } /* select responses from channel with max oe value */ *edge = matrix_max_selector::select_values(*oes_strength, index); *edge_polarity = matrix_max_selector::select_values(*oes_polarity, index); *edge_ori = matrix_max_selector::select_values(oris, index); } } /*************************************************************************** * Textons. ***************************************************************************/ /* * Compute textons using the given filter set. * * Convolve the image with each filter (in parallel) and cluster the * response vectors into textons. Return the texton assignment for each * pixel as well as the textons themselves. * * Cluster textons using the parallel K-means clusterer with the L2 distance * metric. The number of textons (K) and maximum number of iterations may * be specified below. Note that setting the number of iterations to zero * indicates unlimited iterations (in this case, K-means continues until * convergence). * * In order to speed up cluserting, users may specify that textons should be * produced by clustering only a randomly selected subsample of the filter * responses. */ matrix<unsigned long> lib_image::textons( const matrix<>& m, const collection< matrix<> >& filters, auto_collection< matrix<>, array_list< matrix<> > >& textons, unsigned long K, unsigned long max_iter, double subsampling) { return lib_image::textons( m, filters, sample_clusterer< matrix<> >( kmeans::matrix_clusterer<>(K, max_iter, matrix_metrics<>::L2_metric()), subsampling, K ), textons ); } /* * Compute textons as above, however specify a custom clustering routine. */ matrix<unsigned long> lib_image::textons( const matrix<>& m, const collection< matrix<> >& filters, const centroid_clusterer< matrix<> >& clusterer, auto_collection< matrix<>, array_list< matrix<> > >& textons) { /* convolve image with filters */ auto_collection< matrix<>, array_list< matrix<> > > responses = lib_image::filter(m, filters); /* cluster filter responses */ return lib_image::cluster_filter_responses(*responses, clusterer, textons); } /*************************************************************************** * Histogram gradient helper functions (2D). ***************************************************************************/ namespace { /* * Construct region mask for circular disc of the given radius. */ matrix<bool> region_mask_disc(unsigned long r) { /* initialize matrix */ unsigned long size = 2*r + 1; matrix<bool> mask(size, size); /* set values in disc to true */ long radius = static_cast<long>(r); long r_sq = radius * radius; unsigned long ind = 0; for (long x = -radius; x <= radius; x++) { long x_sq = x * x; for (long y = -radius; y <= radius; y++) { /* check if index is within disc */ long y_sq = y * y; if ((x_sq + y_sq) <= r_sq) mask[ind] = true; /* increment linear index */ ind++; } } return mask; } /* * Construct region mask for annulus with the given inner and outer radii. */ matrix<bool> region_mask_annulus(unsigned long r_inner, unsigned long r_outer) { /* initialize matrix */ unsigned long size = 2*r_outer + 1; matrix<bool> mask(size, size); /* set values in annulus to true */ long radius = static_cast<long>(r_outer); long r_outer_sq = radius * radius; long r_inner_sq = static_cast<long>(r_inner) * static_cast<long>(r_inner); unsigned long ind = 0; for (long x = -radius; x <= radius; x++) { long x_sq = x * x; for (long y = -radius; y <= radius; y++) { /* check if index is within circular disc */ long y_sq = y * y; long dist_sq = x_sq + y_sq; if ((r_inner_sq < dist_sq) && (dist_sq <= r_outer_sq)) mask[ind] = true; /* increment linear index */ ind++; } } return mask; } /* * Construct weight matrix for circular disc of the given radius. */ matrix<> weight_matrix_disc(unsigned long r) { /* initialize matrix */ unsigned long size = 2*r + 1; matrix<> weights(size, size); /* set values in disc to 1 */ long radius = static_cast<long>(r); long r_sq = radius * radius; unsigned long ind = 0; for (long x = -radius; x <= radius; x++) { long x_sq = x * x; for (long y = -radius; y <= radius; y++) { /* check if index is within disc */ long y_sq = y * y; if ((x_sq + y_sq) <= r_sq) weights[ind] = 1; /* increment linear index */ ind++; } } return weights; } /* * Construct orientation slice lookup map. */ matrix<unsigned long> orientation_slice_map( unsigned long size_x, unsigned long size_y, unsigned long n_ori) { /* initialize map */ matrix<unsigned long> slice_map(size_x, size_y); /* compute orientation of each element from center */ unsigned long ind = 0; double x = -static_cast<double>(size_x)/2; for (unsigned long n_x = 0; n_x < size_x; n_x++) { double y = -static_cast<double>(size_y)/2; for (unsigned long n_y = 0; n_y < size_y; n_y++) { /* compute orientation index */ double ori = math::atan2(y, x) + M_PIl; unsigned long idx = static_cast<unsigned long>( math::floor(ori / M_PIl * static_cast<double>(n_ori)) ); if (idx >= (2*n_ori)) idx = 2*n_ori - 1; slice_map[ind] = idx; /* increment position */ ind++; y++; } /* increment x-coordinate */ x++; } return slice_map; } /* * Compute convolution in place (for 1D matrices). */ void conv_in_place_1D( const matrix<>& m0, const matrix<>& m1, matrix<>& m) { /* get size of each matrix */ unsigned long size0 = m0.size(); unsigned long size1 = m1.size(); /* set dimensions for result matrix no larger than left input */ unsigned long size = ((size0 > 0) && (size1 > 0)) ? (size0) : 0; /* set start position for result matrix no larger than left input */ unsigned long pos_start = size1/2; /* initialize position in result */ unsigned long pos = pos_start; for (unsigned long n = 0; n < size; n++) { /* compute range of offset */ unsigned long offset_min = ((pos + 1) > size0) ? (pos + 1 - size0) : 0; unsigned long offset_max = (pos < size1) ? pos : (size1 - 1); /* multiply and add corresponing elements */ unsigned long ind0 = pos - offset_min; unsigned long ind1 = offset_min; while (ind1 <= offset_max) { /* update result value */ m[n] += m0[ind0] * m1[ind1]; /* update linear positions */ ind0--; ind1++; } /* update position */ pos++; } } /* * Compute histograms and histogram differences at each location. */ void compute_hist_gradient_2D( const matrix<unsigned long>& labels, const matrix<>& weights, const matrix<unsigned long>& slice_map, const matrix<>& smoothing_kernel, array_list< matrix<> >& slice_hist, /* hist per slice */ array_list< matrix<> >& gradients, /* matrix per ori */ const distanceable_functor<matrix<>,double>& f_dist) { /* get number of orientations */ unsigned long n_ori = gradients.size(); /* get label matrix size */ unsigned long size0_x = labels.size(0); unsigned long size0_y = labels.size(1); /* get window size */ unsigned long size1_x = weights.size(0); unsigned long size1_y = weights.size(1); /* set start position for gradient matrices */ unsigned long pos_start_x = size1_x/2; unsigned long pos_start_y = size1_y/2; unsigned long pos_bound_y = pos_start_y + size0_y; /* initialize position in result */ unsigned long pos_x = pos_start_x; unsigned long pos_y = pos_start_y; /* compute initial range of offset_x */ unsigned long offset_min_x = ((pos_x + 1) > size0_x) ? (pos_x + 1 - size0_x) : 0; unsigned long offset_max_x = (pos_x < size1_x) ? pos_x : (size1_x - 1); unsigned long ind0_start_x = (pos_x - offset_min_x) * size0_y; unsigned long ind1_start_x = (offset_min_x) * size1_y; unsigned long size = labels.size(); /* determine whether to use smoothing kernel */ bool use_smoothing = !(smoothing_kernel.is_empty()); matrix<> temp_conv(slice_hist[0].dimensions()); unsigned long size_hist = slice_hist[0].size(); /* allocate half disc histograms */ matrix<> hist_left(slice_hist[0].dimensions()); matrix<> hist_right(slice_hist[0].dimensions()); for (unsigned long n = 0; n < size; n++) { /* compute range of offset_y */ unsigned long offset_min_y = ((pos_y + 1) > size0_y) ? (pos_y + 1 - size0_y) : 0; unsigned long offset_max_y = (pos_y < size1_y) ? pos_y : (size1_y - 1); unsigned long offset_range_y = offset_max_y - offset_min_y; /* initialize indices */ unsigned long ind0 = ind0_start_x + (pos_y - offset_min_y); unsigned long ind1 = ind1_start_x + offset_min_y; /* clear histograms */ for (unsigned long n_hist = 0; n_hist < 2*n_ori; n_hist++) slice_hist[n_hist].fill(0); /* update histograms */ for (unsigned long o_x = offset_min_x; o_x <= offset_max_x; o_x++) { for (unsigned long o_y = offset_min_y; o_y < offset_max_y; o_y++) { /* update histogram value */ (slice_hist[slice_map[ind1]])[labels[ind0]] += weights[ind1]; /* update linear positions */ ind0--; ind1++; } /* update last histogram value */ (slice_hist[slice_map[ind1]])[labels[ind0]] += weights[ind1]; /* update linear positions */ ind0 = ind0 + offset_range_y - size0_y; ind1 = ind1 - offset_range_y + size1_y; } /* smooth bins */ if (use_smoothing) { for (unsigned long o = 0; o < 2*n_ori; o++) { matrix<>& sh = slice_hist[o]; temp_conv.fill(0); conv_in_place_1D(sh, smoothing_kernel, temp_conv); for (unsigned long nh = 0; nh < size_hist; nh++) sh[nh] = temp_conv[nh]; } } /* L1 normalize bins */ for (unsigned long o = 0; o < 2*n_ori; o++) { double sum_slice_hist = sum(slice_hist[o]); if (sum_slice_hist != 0) slice_hist[o] /= sum_slice_hist; } /* compute circular gradients - initialize histograms */ hist_left.fill(0); hist_right.fill(0); for (unsigned long o = 0; o < n_ori; o++) { hist_left += slice_hist[o]; hist_right += slice_hist[o+n_ori]; } /* compute circular gradients - spin the disc */ for (unsigned long o = 0; o < n_ori; o++) { (gradients[o])[n] = f_dist(hist_left, hist_right); hist_left -= slice_hist[o]; hist_left += slice_hist[o+n_ori]; hist_right += slice_hist[o]; hist_right -= slice_hist[o+n_ori]; } /* update position */ pos_y++; if (pos_y == pos_bound_y) { /* reset y position, increment x position */ pos_y = pos_start_y; pos_x++; /* update range of offset_x */ offset_min_x = ((pos_x + 1) > size0_x) ? (pos_x + 1 - size0_x) : 0; offset_max_x = (pos_x < size1_x) ? pos_x : (size1_x - 1); ind0_start_x = (pos_x - offset_min_x) * size0_y; ind1_start_x = (offset_min_x) * size1_y; } } } /* * Compute histograms and histogram differences at each location. */ void compute_hist_gradient_2D( const matrix< matrix<> >& histograms, const matrix<>& weights, const matrix<unsigned long>& slice_map, const matrix<>& smoothing_kernel, array_list< matrix<> >& slice_hist, /* hist per slice */ array_list< matrix<> >& gradients, /* matrix per ori */ const distanceable_functor<matrix<>,double>& f_dist) { /* get number of orientations */ unsigned long n_ori = gradients.size(); /* get label matrix size */ unsigned long size0_x = histograms.size(0); unsigned long size0_y = histograms.size(1); /* get window size */ unsigned long size1_x = weights.size(0); unsigned long size1_y = weights.size(1); /* set start position for gradient matrices */ unsigned long pos_start_x = size1_x/2; unsigned long pos_start_y = size1_y/2; unsigned long pos_bound_y = pos_start_y + size0_y; /* initialize position in result */ unsigned long pos_x = pos_start_x; unsigned long pos_y = pos_start_y; /* compute initial range of offset_x */ unsigned long offset_min_x = ((pos_x + 1) > size0_x) ? (pos_x + 1 - size0_x) : 0; unsigned long offset_max_x = (pos_x < size1_x) ? pos_x : (size1_x - 1); unsigned long ind0_start_x = (pos_x - offset_min_x) * size0_y; unsigned long ind1_start_x = (offset_min_x) * size1_y; unsigned long size = histograms.size(); /* determine whether to use smoothing kernel */ bool use_smoothing = !(smoothing_kernel.is_empty()); /* allocate half disc histograms */ matrix<> hist_left(slice_hist[0].dimensions()); matrix<> hist_right(slice_hist[0].dimensions()); for (unsigned long n = 0; n < size; n++) { /* compute range of offset_y */ unsigned long offset_min_y = ((pos_y + 1) > size0_y) ? (pos_y + 1 - size0_y) : 0; unsigned long offset_max_y = (pos_y < size1_y) ? pos_y : (size1_y - 1); unsigned long offset_range_y = offset_max_y - offset_min_y; /* initialize indices */ unsigned long ind0 = ind0_start_x + (pos_y - offset_min_y); unsigned long ind1 = ind1_start_x + offset_min_y; /* clear histograms */ for (unsigned long n_hist = 0; n_hist < 2*n_ori; n_hist++) slice_hist[n_hist].fill(0); /* update histograms */ for (unsigned long o_x = offset_min_x; o_x <= offset_max_x; o_x++) { for (unsigned long o_y = offset_min_y; o_y < offset_max_y; o_y++) { /* update histogram value */ (slice_hist[slice_map[ind1]]) += weights[ind1] * histograms[ind0]; /* update linear positions */ ind0--; ind1++; } /* update last histogram value */ (slice_hist[slice_map[ind1]]) += weights[ind1] * histograms[ind0]; /* update linear positions */ ind0 = ind0 + offset_range_y - size0_y; ind1 = ind1 - offset_range_y + size1_y; } /* smooth bins */ if (use_smoothing) { for (unsigned long o = 0; o < 2*n_ori; o++) slice_hist[o] = conv_crop(slice_hist[o], smoothing_kernel); } /* L1 normalize bins */ for (unsigned long o = 0; o < 2*n_ori; o++) { double sum_slice_hist = sum(slice_hist[o]); if (sum_slice_hist != 0) slice_hist[o] /= sum_slice_hist; } /* compute circular gradients - initialize histograms */ hist_left.fill(0); hist_right.fill(0); for (unsigned long o = 0; o < n_ori; o++) { hist_left += slice_hist[o]; hist_right += slice_hist[o+n_ori]; } /* compute circular gradients - spin the disc */ for (unsigned long o = 0; o < n_ori; o++) { (gradients[o])[n] = f_dist(hist_left, hist_right); hist_left -= slice_hist[o]; hist_left += slice_hist[o+n_ori]; hist_right += slice_hist[o]; hist_right -= slice_hist[o+n_ori]; } /* update position */ pos_y++; if (pos_y == pos_bound_y) { /* reset y position, increment x position */ pos_y = pos_start_y; pos_x++; /* update range of offset_x */ offset_min_x = ((pos_x + 1) > size0_x) ? (pos_x + 1 - size0_x) : 0; offset_max_x = (pos_x < size1_x) ? pos_x : (size1_x - 1); ind0_start_x = (pos_x - offset_min_x) * size0_y; ind1_start_x = (offset_min_x) * size1_y; } } } } /* namespace */ /*************************************************************************** * Difference of histograms (2D). ***************************************************************************/ /* * Compute the distance between histograms of label values in the disc * and annulus of the specified radii centered at each location in the * 2D matrix. The disc is bounded by the inner radius while the annulus * lies between the inner and outer radius. * * Alternatively, instead of specifying label values at each point, the user * may specify a histogram at each point, in which case the histogram for * a region is the sum of the histograms at points in that region. * * The user may optionally specify a nonempty 1D smoothing kernel to * convolve with histograms prior to computing the distance between them. * * The user may also optionally specify a custom functor for computing the * distance between histograms. */ matrix<> lib_image::hist_diff_2D( const matrix<unsigned long>& labels, unsigned long r_inner, unsigned long r_outer, const matrix<>& smoothing_kernel, const distanceable_functor<matrix<>,double>& f_dist) { /* construct region mask and weight matrix */ matrix<bool> region_mask = region_mask_annulus(r_inner, r_outer); matrix<> weights = weight_matrix_disc(r_outer); /* compute histrogram difference */ return lib_image::hist_diff_2D( labels, region_mask, weights, smoothing_kernel, f_dist ); } matrix<> lib_image::hist_diff_2D( const matrix< matrix<> >& histograms, unsigned long r_inner, unsigned long r_outer, const matrix<>& smoothing_kernel, const distanceable_functor<matrix<>,double>& f_dist) { /* construct region mask and weight matrix */ matrix<bool> region_mask = region_mask_annulus(r_inner, r_outer); matrix<> weights = weight_matrix_disc(r_outer); /* compute histrogram difference */ return lib_image::hist_diff_2D( histograms, region_mask, weights, smoothing_kernel, f_dist ); } /* * Compute the distance between histograms of label values in regions * centered at each location in the 2D matrix. * * The given 2D binary region mask (which must have odd dimensions) defines * the regions. Each label adds the weight at the corresponding position * in the weight matrix to its histogram bin in the respective region. * * If the user specifies a histogram at each point instead of a label, then * the histogram for a region is a weighted sum of histograms. */ matrix<> lib_image::hist_diff_2D( const matrix<unsigned long>& labels, const matrix<bool>& region_mask, const matrix<>& weights, const matrix<>& smoothing_kernel, const distanceable_functor<matrix<>,double>& f_dist) { /* check arguments - labels */ if (labels._dims.size() != 2) throw ex_invalid_argument("label matrix must be 2D"); /* check arguments - region mask */ if (region_mask._dims.size() != 2) throw ex_invalid_argument("region mask must be 2D"); unsigned long r_size_x = region_mask._dims[0]; unsigned long r_size_y = region_mask._dims[1]; if (((r_size_x/2) == ((r_size_x+1)/2)) || ((r_size_y/2) == ((r_size_y+1)/2))) throw ex_invalid_argument("dimensions of region mask must be odd"); /* check arguments - weights */ if (weights._dims.size() != 2) throw ex_invalid_argument("weight matrix must be 2D"); unsigned long w_size_x = weights._dims[0]; unsigned long w_size_y = weights._dims[1]; if ((w_size_x != r_size_x) || (w_size_y != r_size_y)) throw ex_invalid_argument( "dimensions of weight matrix must match dimensions of region mask" ); /* initialize result histogram difference matrix */ matrix<> h_diff(labels._dims); if (labels._size == 0) return h_diff; /* initialize collection containing result histogram difference matrix */ array_list< matrix<> > gradients; gradients.add(h_diff); /* initialize slice histogram matrices */ unsigned long hist_length = max(labels) + 1; matrix<> slice_hist0(1, hist_length); matrix<> slice_hist1(1, hist_length); array_list< matrix<> > slice_hist; slice_hist.add(slice_hist0); slice_hist.add(slice_hist1); /* convert region mask into a slice lookup map (with two slices) */ matrix<unsigned long> slice_map(region_mask); /* compute histograms and histogram differences at each location */ compute_hist_gradient_2D( labels, weights, slice_map, vector(smoothing_kernel), slice_hist, gradients, f_dist ); return h_diff; } matrix<> lib_image::hist_diff_2D( const matrix< matrix<> >& histograms, const matrix<bool>& region_mask, const matrix<>& weights, const matrix<>& smoothing_kernel, const distanceable_functor<matrix<>,double>& f_dist) { /* check arguments - labels */ if (histograms._dims.size() != 2) throw ex_invalid_argument("histogram matrix must be 2D"); /* check arguments - region mask */ if (region_mask._dims.size() != 2) throw ex_invalid_argument("region mask must be 2D"); unsigned long r_size_x = region_mask._dims[0]; unsigned long r_size_y = region_mask._dims[1]; if (((r_size_x/2) == ((r_size_x+1)/2)) || ((r_size_y/2) == ((r_size_y+1)/2))) throw ex_invalid_argument("dimensions of region mask must be odd"); /* check arguments - weights */ if (weights._dims.size() != 2) throw ex_invalid_argument("weight matrix must be 2D"); unsigned long w_size_x = weights._dims[0]; unsigned long w_size_y = weights._dims[1]; if ((w_size_x != r_size_x) || (w_size_y != r_size_y)) throw ex_invalid_argument( "dimensions of weight matrix must match dimensions of region mask" ); /* initialize result histogram difference matrix */ matrix<> h_diff(histograms._dims); if (histograms._size == 0) return h_diff; /* initialize collection containing result histogram difference matrix */ array_list< matrix<> > gradients; gradients.add(h_diff); /* initialize slice histogram matrices */ matrix<> slice_hist0(histograms[0]._dims); matrix<> slice_hist1(histograms[0]._dims); array_list< matrix<> > slice_hist; slice_hist.add(slice_hist0); slice_hist.add(slice_hist1); /* convert region mask into a slice lookup map (with two slices) */ matrix<unsigned long> slice_map(region_mask); /* compute histograms and histogram differences at each location */ compute_hist_gradient_2D( histograms, weights, slice_map, vector(smoothing_kernel), slice_hist, gradients, f_dist ); return h_diff; } /*************************************************************************** * Oriented gradient of histograms (2D). ***************************************************************************/ namespace { /* * Runnable class for resizing matrices in parallel. */ class matrix_resizer : public runnable { public: /* * Constructor. */ matrix_resizer( array_list< matrix<> >& m_arr, /* matrices to resize */ const array<unsigned long>& dims, /* desired dimensions */ unsigned long start, /* first index to process */ unsigned long end) /* last index to process */ : _m_arr(m_arr), _dims(dims), _start(start), _end(end) { } /* * Destructor. */ virtual ~matrix_resizer() { /* do nothing */ } /* * Resize matrices. */ virtual void run() { if ((thread::processors() > 1) && (_start < _end)) { /* split resizing task */ unsigned long mid = (_start + _end)/2; matrix_resizer r_left(_m_arr, _dims, _start, mid); matrix_resizer r_right(_m_arr, _dims, mid+1, _end); child_thread::run(r_left, r_right); } else { /* resize matrices */ for (unsigned long n = _start; n <= _end; n++) _m_arr[n].resize(_dims); } } protected: array_list< matrix<> >& _m_arr; /* matrices to resize */ const array<unsigned long>& _dims; /* desired dimensions */ unsigned long _start; /* first index to process */ unsigned long _end; /* last index to process */ }; } /* namespace */ /* * Compute the distance between histograms of label values in oriented * half-dics of the specified radius centered at each location in the 2D * matrix. Return one distance matrix per orientation. * * Alternatively, instead of specifying label values at each point, the user * may specify a histogram at each point, in which case the histogram for * a half-disc is the sum of the histograms at points in that half-disc. * * The half-disc orientations are k*pi/n for k in [0,n) where n is the * number of orientation requested. * * The user may optionally specify a nonempty 1D smoothing kernel to * convolve with histograms prior to computing the distance between them. * * The user may also optionally specify a custom functor for computing the * distance between histograms. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::hist_gradient_2D( const matrix<unsigned long>& labels, unsigned long r, unsigned long n_ori, const matrix<>& smoothing_kernel, const distanceable_functor<matrix<>,double>& f_dist) { /* construct weight matrix for circular disc */ matrix<> weights = weight_matrix_disc(r); /* compute oriented gradient histograms */ return lib_image::hist_gradient_2D( labels, weights, n_ori, smoothing_kernel, f_dist ); } auto_collection< matrix<>, array_list< matrix<> > > lib_image::hist_gradient_2D( const matrix< matrix<> >& histograms, unsigned long r, unsigned long n_ori, const matrix<>& smoothing_kernel, const distanceable_functor<matrix<>,double>& f_dist) { /* construct weight matrix for circular disc */ matrix<> weights = weight_matrix_disc(r); /* compute oriented gradient histograms */ return lib_image::hist_gradient_2D( histograms, weights, n_ori, smoothing_kernel, f_dist ); } /* * Compute the distance between histograms of label values in oriented * half-regions centered at each location in the 2D matrix. Return one * distance matrix per orientation. * * The given 2D weight matrix (which must have odd dimensions) defines the * half-regions. Each label adds the weight at the corresponding position * in this matrix to its histogram bin. * * If the user specifies a histogram at each point instead of a label, then * the histogram for a half-region is a weighted sum of histograms. * * The above version of hist_gradient_2D which specifies a radius r is * equivalent to calling this version with a (2*r+1) x (2*r+1) weight matrix * in which elements within a distance r from the center have weight one and * all other elements have weight zero. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::hist_gradient_2D( const matrix<unsigned long>& labels, const matrix<>& weights, unsigned long n_ori, const matrix<>& smoothing_kernel, const distanceable_functor<matrix<>,double>& f_dist) { /* check arguments - labels */ if (labels._dims.size() != 2) throw ex_invalid_argument("label matrix must be 2D"); /* check arguments - weights */ if (weights._dims.size() != 2) throw ex_invalid_argument("weight matrix must be 2D"); unsigned long w_size_x = weights._dims[0]; unsigned long w_size_y = weights._dims[1]; if (((w_size_x/2) == ((w_size_x+1)/2)) || ((w_size_y/2) == ((w_size_y+1)/2))) throw ex_invalid_argument("dimensions of weight matrix must be odd"); /* allocate result gradient matrices */ auto_collection< matrix<>, array_list< matrix<> > > gradients( new array_list< matrix<> >() ); /* check that result is nontrivial */ if (n_ori == 0) return gradients; /* initialize result gradient matrices */ for (unsigned long n = 0; n < n_ori; n++) { auto_ptr< matrix<> > m_ptr(new matrix<>()); gradients->add(*m_ptr); m_ptr.release(); } { matrix_resizer m_resizer(*gradients, labels._dims, 0, n_ori-1); m_resizer.run(); } /* check that result is nonempty */ if (labels._size == 0) return gradients; /* allocate matrices to hold histograms of each slice */ auto_collection< matrix<>, array_list< matrix<> > > slice_hist( new array_list< matrix<> >() ); /* initialize slice histogram matrices */ for (unsigned long n = 0; n < 2*n_ori; n++) { auto_ptr< matrix<> > m_ptr(new matrix<>()); slice_hist->add(*m_ptr); m_ptr.release(); } { unsigned long hist_length = max(labels) + 1; array<unsigned long> slice_hist_dims(1, hist_length); matrix_resizer m_resizer(*slice_hist, slice_hist_dims, 0, 2*n_ori-1); m_resizer.run(); } /* build orientation slice lookup map */ matrix<unsigned long> slice_map = orientation_slice_map( w_size_x, w_size_y, n_ori ); /* compute histograms and histogram differences at each location */ compute_hist_gradient_2D( labels, weights, slice_map, vector(smoothing_kernel), *slice_hist, *gradients, f_dist ); return gradients; } auto_collection< matrix<>, array_list< matrix<> > > lib_image::hist_gradient_2D( const matrix< matrix<> >& histograms, const matrix<>& weights, unsigned long n_ori, const matrix<>& smoothing_kernel, const distanceable_functor<matrix<>,double>& f_dist) { /* check arguments - histograms */ if (histograms._dims.size() != 2) throw ex_invalid_argument("histogram matrix must be 2D"); /* check arguments - weights */ if (weights._dims.size() != 2) throw ex_invalid_argument("weight matrix must be 2D"); unsigned long w_size_x = weights._dims[0]; unsigned long w_size_y = weights._dims[1]; if (((w_size_x/2) == ((w_size_x+1)/2)) || ((w_size_y/2) == ((w_size_y+1)/2))) throw ex_invalid_argument("dimensions of weight matrix must be odd"); /* allocate result gradient matrices */ auto_collection< matrix<>, array_list< matrix<> > > gradients( new array_list< matrix<> >() ); /* check that result is nontrivial */ if (n_ori == 0) return gradients; /* initialize result gradient matrices */ for (unsigned long n = 0; n < n_ori; n++) { auto_ptr< matrix<> > m_ptr(new matrix<>()); gradients->add(*m_ptr); m_ptr.release(); } { matrix_resizer m_resizer(*gradients, histograms._dims, 0, n_ori-1); m_resizer.run(); } /* check that result is nonempty */ if (histograms._size == 0) return gradients; /* allocate matrices to hold histograms of each slice */ auto_collection< matrix<>, array_list< matrix<> > > slice_hist( new array_list< matrix<> >() ); /* initialize slice histogram matrices */ for (unsigned long n = 0; n < 2*n_ori; n++) { auto_ptr< matrix<> > m_ptr(new matrix<>()); slice_hist->add(*m_ptr); m_ptr.release(); } { array<unsigned long> slice_hist_dims(histograms[0]._dims); matrix_resizer m_resizer(*slice_hist, slice_hist_dims, 0, 2*n_ori-1); m_resizer.run(); } /* build orientation slice lookup map */ matrix<unsigned long> slice_map = orientation_slice_map( w_size_x, w_size_y, n_ori ); /* compute histograms and histogram differences at each location */ compute_hist_gradient_2D( histograms, weights, slice_map, vector(smoothing_kernel), *slice_hist, *gradients, f_dist ); return gradients; } /* * Combine oriented gradients of histograms into a single gradient map. * * Each location is assigned gradient strength eqaul to the maximum gradient * value over all orientations. The dominant orientation at each location * is also returned. * * Unless otherwise specified, the orientations corresponding to the input * collection of n oriented gradient maps are assumed to be k*pi/n for * integer k in [0,n). */ void lib_image::combine_hist_gradients( const collection< matrix<> >& gradients, auto_ptr< matrix<> >& gradient, auto_ptr< matrix<> >& gradient_ori) { unsigned long n_ori = gradients.size(); array<double> oris = lib_image::standard_filter_orientations(n_ori); lib_image::combine_hist_gradients(gradients, oris, gradient, gradient_ori); } void lib_image::combine_hist_gradients( const collection< matrix<> >& gradients, const array<double>& oris, auto_ptr< matrix<> >& gradient, auto_ptr< matrix<> >& gradient_ori) { /* check arguments - number of orientations */ unsigned long n_ori = oris.size(); if (gradients.size() != n_ori) throw ex_invalid_argument( "number of gradient matrices different from number of orientations" ); /* initialize gradient map */ gradient.reset(new matrix<>()); gradient_ori.reset(new matrix<>()); /* check if nontrivial result */ if (n_ori > 0) { /* check that all gradient matrices have the same size */ array_list< matrix<> > gradients_arr(gradients); array<unsigned long> dims = gradients_arr[0]._dims; for (unsigned long n = 0; n < n_ori; n++) matrix<>::assert_dims_equal(dims, gradients_arr[n]._dims); /* compute indices of maximum gradient values */ matrix<unsigned long> index(dims); if (index._size > 0) { matrix_max_selector m_select(gradients_arr, 0, index._size-1, index); m_select.run(); } *gradient = matrix_max_selector::select_values(gradients_arr, index); *gradient_ori = matrix_max_selector::select_values(oris, index); } } /*************************************************************************** * Smoothing. ***************************************************************************/ /* * Compute "needleness" at each point from derivatives. * * The "needleness" for a signal f(x) is defined as * * f(x) * (-f''(x)) / (abs(f'(x)) + epsilon) * * This function is useful for smoothing and merging double peaks. */ matrix<> lib_image::needleness( const matrix<>& f0, const matrix<>& f1, const matrix<>& f2, double epsilon) { /* check arguments */ matrix<>::assert_dims_equal(f0._dims, f1._dims); matrix<>::assert_dims_equal(f0._dims, f2._dims); /* compute needleness */ matrix<> f(f0._dims); for (unsigned long n = 0; n < f._size; n++) { f._data[n] = f0._data[n] * (-(f2._data[n])) / (math::abs(f1._data[n]) + epsilon); } return f; } /* * Smooth and sharpen 2D oriented gradients using gaussian derivative * filters and the "needleness" function. * * Smoothing is done along the gradient directions, which are assumed to be * k*pi/n for k in [0,n) where n is the number of orientated gradients. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::smooth_grad_2D( const collection< matrix<> >& gradients, double sigma, double epsilon) { unsigned long n_ori = gradients.size(); array<double> oris = lib_image::standard_filter_orientations(n_ori); return lib_image::smooth_grad_2D(gradients, oris, sigma, epsilon); } /* * Smooth and sharpen 2D oriented gradients using gaussian derivative * filters and the "needleness" function. * * Specify the orientations along which to smooth. */ auto_collection< matrix<>, array_list< matrix<> > > lib_image::smooth_grad_2D( const collection< matrix<> >& gradients, const array<double>& oris, double sigma, double epsilon) { /* get number of orientations */ array_list< matrix<> > gradients_arr(gradients); unsigned long n_ori = gradients_arr.size(); /* smooth each orientation */ auto_collection< matrix<>, array_list< matrix<> > > f_smoothed( new array_list< matrix<> >() ); for (unsigned long n = 0; n < n_ori; n++) { /* create oriented gaussian smoothing kernels */ matrix<> g0 = lib_image::gaussian_2D(sigma, sigma, oris[n], 0); matrix<> g1 = lib_image::gaussian_2D(sigma, sigma, oris[n], 1); matrix<> g2 = lib_image::gaussian_2D(sigma, sigma, oris[n], 2); /* convolve with smoothing kernels */ matrix<>& f = gradients_arr[n]; matrix<> f0 = conv_crop(f, g0); matrix<> f1 = conv_crop(f, g1); matrix<> f2 = conv_crop(f, g2); /* take positive component of f0 */ for (unsigned long ind = 0; ind < f0._size; ind++) f0._data[ind] = (f0._data[ind] > 0) ? (f0._data[ind]) : 0; /* take negative component of f2 */ for (unsigned long ind = 0; ind < f2._size; ind++) f2._data[ind] = (f2._data[ind] < 0) ? (f2._data[ind]) : 0; /* compute needleness */ auto_ptr< matrix<> > f_result( new matrix<>(lib_image::needleness(f0, f1, f2, epsilon)) ); f_smoothed->add(*f_result); f_result.release(); } return f_smoothed; } /*************************************************************************** * Non-max suppression. ***************************************************************************/ /* * Non-max suppression. * * Perform non-max suppression in the local neighborhood of each matrix * element. Each local neighborhood is a block of 3^d elements where d is * the dimensionality of the matrix. * * Optionally, a matrix of size 3^d can be used as a mask to determine * to which elements of the local neighborhood the center element should * be compared during non-max suppression. * * Boundary elements are not considered as candidates for a local maximum. * * Non-max elements are assigned a value of zero. * * NOTE: The original matrix must be nonnegative. */ matrix<> lib_image::nonmax(const matrix<>& m) { /* create default mask for full 3^d neighborhood */ unsigned long n_dims = m._dims.size(); array<unsigned long> mask_dims(n_dims, 3); matrix<bool> mask(mask_dims, true); if (n_dims > 0) mask._data[mask._size/2] = false; /* don't compare center to itself */ /* perform non-max suppression */ return lib_image::nonmax(m, mask); } matrix<> lib_image::nonmax(const matrix<>& m, const matrix<bool>& mask) { /* check that mask is valid */ unsigned long n_dims = m._dims.size(); bool mask_valid = (n_dims == mask._dims.size()); for (unsigned long n = 0; ((n < n_dims) && (mask_valid)); n++) mask_valid = (mask._dims[n] == 3); if (!mask_valid) throw ex_invalid_argument( "mask for d-dimensional matrix must be size 3^d" ); /* initialize result matrix */ matrix<> nmax(m._dims); /* check that result is nontrivial */ if (nmax._size > 0) { /* compute offsets of neighbors */ array<long> neighbor_offsets = matrix<>::linear_neighbor_offsets(m._dims); /* grab offsets specified by mask */ array<unsigned long> used_offsets = mask.find(); array<long> offsets = neighbor_offsets.subarray(used_offsets); unsigned long n_offsets = offsets.size(); /* compute indices of interior elements */ array<unsigned long> start(n_dims, 1); array<unsigned long> end(n_dims); for (unsigned long n = 0; n < n_dims; n++) end[n] = m._dims[n] - 1; array<unsigned long> inds = matrix<>::linear_indices(m._dims, start, end); /* perform non-max suppression at each interior element */ unsigned long n_inds = inds.size(); for (unsigned long n = 0; n < n_inds; n++) { /* get index */ unsigned long ind_cntr = inds[n]; /* get element value */ double v = m._data[ind_cntr]; if (v < 0) throw ex_invalid_argument("matrix must be nonnegative"); /* compare to neighbors */ bool is_max = true; for (unsigned long n_off = 0; ((n_off < n_offsets) && (is_max)); n_off++) { long ind = static_cast<long>(ind_cntr) + offsets[n_off]; /* check if non-max */ if (v <= m._data[ind]) is_max = false; } /* suppress non-max */ if (is_max) nmax._data[ind_cntr] = v; } } return nmax; } /* * Non-max suppression (along specified dimension). * * Perform non-max suppression along the specified dimension of the matrix. * * Boundary elements along this dimension are only considered as candidates * for a local maximum if the flag to allow boundary candidates is set. * * Non-max elements are assigned a value of zero. * * NOTE: The original matrix must be nonnegative. */ matrix<> lib_image::nonmax( const matrix<>& m, unsigned long d, bool allow_boundary) { /* get # steps along dimension */ unsigned long n_dims = m._dims.size(); unsigned long n_steps = (d < n_dims) ? m._dims[d] : 1; /* initialize result matrix */ matrix<> nmax(m._dims); /* check that result is nontrivial */ if (nmax._size > 0) { /* compute indices along first slice of dimension */ array<unsigned long> inds = matrix<>::linear_indices_slice(m._dims, d); /* compute step size along dimension */ unsigned long step_size = matrix<>::dims_size(m._dims, d); /* compute result matrix */ unsigned long n_inds = inds.size(); for (unsigned long n = 0; n < n_inds; n++) { unsigned long ind = inds[n]; unsigned long ind_next = ind + step_size; /* check nonnegativitiy */ if (m._data[ind] < 0) throw ex_invalid_argument("matrix must be nonnegative"); /* check if neighbors exist */ if (n_steps > 1) { /* check first element */ if (allow_boundary) { if (m._data[ind] > m._data[ind_next]) nmax._data[ind] = m._data[ind]; } /* check interior elements */ for (unsigned long n_step = 1; n_step < (n_steps-1); n_step++) { unsigned long ind_prev = ind; ind = ind_next; ind_next += step_size; if ((m._data[ind] > m._data[ind_prev]) && (m._data[ind] > m._data[ind_next])) nmax._data[ind] = m._data[ind]; } /* check last element */ if (allow_boundary) { if (m._data[ind_next] > m._data[ind]) nmax._data[ind_next] = m._data[ind_next]; } } else if (allow_boundary) { nmax._data[ind] = m._data[ind]; } } } return nmax; } /* * Oriented non-max suppression (2D). * * Perform non-max suppression orthogonal to the specified orientation on * the given 2D matrix using linear interpolation in a 3x3 neighborhood. * * A local maximum must be greater than the interpolated values of its * adjacent elements along the direction orthogonal to this orientation. * * Elements which have a neighbor on only one side of this direction are * only considered as candidates for a local maximum if the flag to allow * boundary candidates is set. * * The same orientation angle may be specified for all elements, or the * orientation may be specified for each matrix element. * * If an orientation is specified per element, then the elements themselves * may optionally be treated as oriented vectors by specifying a value less * than pi/2 for the orientation tolerance. In this case, neighboring * vectors are projected along a line in the local orientation direction and * the lengths of the projections are used in determining local maxima. * When projecting, the orientation tolerance is subtracted from the true * angle between the vector and the line (with a result less than zero * causing the length of the projection to be the length of the vector). * * Non-max elements are assigned a value of zero. * * NOTE: The original matrix must be nonnegative. */ matrix<> lib_image::nonmax_oriented_2D( const matrix<>& m, double ori, bool allow_boundary) { /* create per element orientation matrix */ matrix<> m_ori(m._dims, ori); /* perform non-max suppression */ return lib_image::nonmax_oriented_2D(m, m_ori, M_PI_2l, allow_boundary); } matrix<> lib_image::nonmax_oriented_2D( const matrix<>& m, const matrix<>& m_ori, double o_tol, bool allow_boundary) { /* check arguments - matrix size */ if (m._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); matrix<>::assert_dims_equal(m._dims, m_ori._dims); /* check arguments - orientation tolerance */ if (o_tol < 0) throw ex_invalid_argument("orientation tolerance must be nonnegative"); /* get matrix size */ unsigned long size_x = m._dims[0]; unsigned long size_y = m._dims[1]; /* intialize result matrix */ matrix<> nmax(size_x, size_y); /* perform oriented non-max suppression at each element */ unsigned long n = 0; for (unsigned long x = 0; x < size_x; x++) { for (unsigned long y = 0; y < size_y; y++) { /* compute direction (in [0,pi)) along which to suppress */ double ori = m_ori._data[n]; double theta = ori + M_PI_2l; theta -= math::floor(theta/M_PIl) * M_PIl; /* check nonnegativity */ double v = m._data[n]; if (v < 0) throw ex_invalid_argument("matrix must be nonnegative"); /* initialize indices of values in local neighborhood */ unsigned long ind0a = 0, ind0b = 0, ind1a = 0, ind1b = 0; /* initialize distance weighting */ double d = 0; /* initialize boundary flags */ bool valid0 = false, valid1 = false; /* compute interpolation indicies */ if (theta == 0) { valid0 = (x > 0); valid1 = (x < (size_x-1)); if (valid0) { ind0a = n-size_y; ind0b = ind0a; } if (valid1) { ind1a = n+size_y; ind1b = ind1a; } } else if (theta < M_PI_4l) { d = math::tan(theta); valid0 = ((x > 0) && (y > 0)); valid1 = ((x < (size_x-1)) && (y < (size_y-1))); if (valid0) { ind0a = n-size_y; ind0b = ind0a-1; } if (valid1) { ind1a = n+size_y; ind1b = ind1a+1; } } else if (theta < M_PI_2l) { d = math::tan(M_PI_2l - theta); valid0 = ((x > 0) && (y > 0)); valid1 = ((x < (size_x-1)) && (y < (size_y-1))); if (valid0) { ind0a = n-1; ind0b = ind0a-size_y; } if (valid1) { ind1a = n+1; ind1b = ind1a+size_y; } } else if (theta == M_PI_2l) { valid0 = (y > 0); valid1 = (y < (size_y-1)); if (valid0) { ind0a = n-1; ind0b = ind0a; } if (valid1) { ind1a = n+1; ind1b = ind1a; } } else if (theta < (3.0*M_PI_4l)) { d = math::tan(theta - M_PI_2l); valid0 = ((x < (size_x-1)) && (y > 0)); valid1 = ((x > 0) && (y < (size_y-1))); if (valid0) { ind0a = n-1; ind0b = ind0a+size_y; } if (valid1) { ind1a = n+1; ind1b = ind1a-size_y; } } else /* (theta < M_PIl) */ { d = math::tan(M_PIl - theta); valid0 = ((x < (size_x-1)) && (y > 0)); valid1 = ((x > 0) && (y < (size_y-1))); if (valid0) { ind0a = n+size_y; ind0b = ind0a-1; } if (valid1) { ind1a = n-size_y; ind1b = ind1a+1; } } /* check boundary conditions */ if (allow_boundary || (valid0 && valid1)) { /* initialize values in local neighborhood */ double v0a = 0, v0b = 0, v1a = 0, v1b = 0; /* initialize orientations in local neighborhood */ double ori0a = 0, ori0b = 0, ori1a = 0, ori1b = 0; /* grab values and orientations */ if (valid0) { v0a = m._data[ind0a]; v0b = m._data[ind0b]; ori0a = m_ori._data[ind0a] - ori; ori0b = m_ori._data[ind0b] - ori; } if (valid1) { v1a = m._data[ind1a]; v1b = m._data[ind1b]; ori1a = m_ori._data[ind1a] - ori; ori1b = m_ori._data[ind1b] - ori; } /* place orientation difference in [0,pi/2) range */ ori0a -= math::floor(ori0a/(2*M_PIl)) * (2*M_PIl); ori0b -= math::floor(ori0b/(2*M_PIl)) * (2*M_PIl); ori1a -= math::floor(ori1a/(2*M_PIl)) * (2*M_PIl); ori1b -= math::floor(ori1b/(2*M_PIl)) * (2*M_PIl); if (ori0a >= M_PIl) { ori0a = 2*M_PIl - ori0a; } if (ori0b >= M_PIl) { ori0b = 2*M_PIl - ori0b; } if (ori1a >= M_PIl) { ori1a = 2*M_PIl - ori1a; } if (ori1b >= M_PIl) { ori1b = 2*M_PIl - ori1b; } if (ori0a >= M_PI_2l) { ori0a = M_PIl - ori0a; } if (ori0b >= M_PI_2l) { ori0b = M_PIl - ori0b; } if (ori1a >= M_PI_2l) { ori1a = M_PIl - ori1a; } if (ori1b >= M_PI_2l) { ori1b = M_PIl - ori1b; } /* correct orientation difference by tolerance */ ori0a = (ori0a <= o_tol) ? 0 : (ori0a - o_tol); ori0b = (ori0b <= o_tol) ? 0 : (ori0b - o_tol); ori1a = (ori1a <= o_tol) ? 0 : (ori1a - o_tol); ori1b = (ori1b <= o_tol) ? 0 : (ori1b - o_tol); /* interpolate */ double v0 = (1.0-d)*v0a*math::cos(ori0a) + d*v0b*math::cos(ori0b); double v1 = (1.0-d)*v1a*math::cos(ori1a) + d*v1b*math::cos(ori1b); /* suppress non-max */ if ((v > v0) && (v > v1)) nmax._data[n] = v; } /* increment linear coordinate */ n++; } } return nmax; } /*************************************************************************** * Neighbor lookup and comparison (2D). ***************************************************************************/ namespace { /* * Compute which neighbors are present in a 2D matrix. */ void neighbor_exists_2D( unsigned long size_x, unsigned long size_y, /* matrix size */ unsigned long x, unsigned long y, /* position */ bool& n, bool& s, bool& e, bool& w, bool& ne, bool& nw, bool& se, bool& sw) { n = ((y+1) < size_y); s = (y > 0); e = ((x+1) < size_x); w = (x > 0); ne = n && e; nw = n && w; se = s && e; sw = s && w; } /* * Compute indices of neighbors in a 2D matrix. */ void neighbor_indices_2D( unsigned long size_y, /* matrix size in y-direction */ unsigned long ind, /* linear position */ unsigned long& n, unsigned long& s, unsigned long& e, unsigned long& w, unsigned long& ne, unsigned long& nw, unsigned long& se, unsigned long& sw) { n = ind + 1; s = ind - 1; e = ind + size_y; w = ind - size_y; ne = e + 1; nw = w + 1; se = e - 1; sw = w - 1; } void neighbor_indices_2D( unsigned long size_y, /* matrix size in y-direction */ unsigned long x, unsigned long y, /* position */ unsigned long& n, unsigned long& s, unsigned long& e, unsigned long& w, unsigned long& ne, unsigned long& nw, unsigned long& se, unsigned long& sw) { neighbor_indices_2D( size_y, (x * size_y + y), n, s, e, w, ne, nw, se, sw ); } /* * Lookup values of neighbors in a 2D matrix. * Return zero for any neighbors which do not exist. */ template <typename T> void neighbor_values_2D( const T* m, unsigned long size_x, unsigned long size_y, /* matrix */ unsigned long x, unsigned long y, /* position */ unsigned long ind, /* linear position */ T& n, T& s, T& e, T& w, T& ne, T& nw, T& se, T& sw) { /* compute which neighbors are present */ bool has_n = false, has_s = false, has_e = false, has_w = false; bool has_ne = false, has_nw = false, has_se = false, has_sw = false; neighbor_exists_2D( size_x, size_y, x, y, has_n, has_s, has_e, has_w, has_ne, has_nw, has_se, has_sw ); /* compute indices of neighbors */ unsigned long ind_n = 0, ind_s = 0, ind_e = 0, ind_w = 0; unsigned long ind_ne = 0, ind_nw = 0, ind_se = 0, ind_sw = 0; neighbor_indices_2D( size_y, ind, ind_n, ind_s, ind_e, ind_w, ind_ne, ind_nw, ind_se, ind_sw ); /* get values of neighbors */ n = (has_n ? m[ind_n] : T()); s = (has_s ? m[ind_s] : T()); e = (has_e ? m[ind_e] : T()); w = (has_w ? m[ind_w] : T()); ne = (has_ne ? m[ind_ne] : T()); nw = (has_nw ? m[ind_nw] : T()); se = (has_se ? m[ind_se] : T()); sw = (has_sw ? m[ind_sw] : T()); } template <typename T> void neighbor_values_2D( const T* m, unsigned long size_x, unsigned long size_y, /* matrix */ unsigned long x, unsigned long y, /* position */ T& n, T& s, T& e, T& w, T& ne, T& nw, T& se, T& sw) { neighbor_values_2D( m, size_x, size_y, x, y, (x * size_y + y), n, s, e, w, ne, nw, se, sw ); } /* * Compare values of neighbors in a 2D matrix to the given value. * Neighbors which do not exist are assumed to have a value of zero. */ template <typename T> void neighbor_values_compare_2D( const T* m, unsigned long size_x, unsigned long size_y, /* matrix */ unsigned long x, unsigned long y, /* position */ unsigned long ind, /* linear position */ const T& v, /* value */ bool& n, bool& s, bool& e, bool& w, bool& ne, bool& nw, bool& se, bool& sw) { /* get values of neighbors */ T v_n = T(), v_s = T(), v_e = T(), v_w = T(); T v_ne = T(), v_nw = T(), v_se = T(), v_sw = T(); neighbor_values_2D( m, size_x, size_y, x, y, ind, v_n, v_s, v_e, v_w, v_ne, v_nw, v_se, v_sw ); /* compare */ n = (v_n == v); s = (v_s == v); e = (v_e == v); w = (v_w == v); ne = (v_ne == v); nw = (v_nw == v); se = (v_se == v); sw = (v_sw == v); } template <typename T> void neighbor_values_compare_2D( const T* m, unsigned long size_x, unsigned long size_y, /* matrix */ unsigned long x, unsigned long y, /* position */ const T& v, /* value */ bool& n, bool& s, bool& e, bool& w, bool& ne, bool& nw, bool& se, bool& sw) { neighbor_values_compare_2D( m, size_x, size_y, x, y, (x * size_y + y), v, n, s, e, w, ne, nw, se, sw ); } } /* namespace */ /*************************************************************************** * Local topology analysis (2D). ***************************************************************************/ namespace { /* * Determine whether the center element is part of a thick region (a 2x2 or * larger block) given flags indicating which elements are present in the * local 3x3 neighborhood. */ bool is_thick_region_2D( bool n, bool s, bool e, bool w, bool ne, bool nw, bool se, bool sw) { return ( (nw && n && w) || (n && ne && e) || (w && sw && s) || (e && s && se) ); } /* * Determine whether removal of the center element is a valid erosion * operation. Erosion is only possible if the center element is a local * extrema on the boundary of a thick region. */ bool is_erodable_2D( bool n, bool s, bool e, bool w, bool ne, bool nw, bool se, bool sw) { if (nw && n && w) { return ((!e) && (!s) && (!se)); } else if (n && ne && e) { return ((!w) && (!s) && (!sw)); } else if (w && sw && s) { return ((!e) && (!n) && (!ne)); } else if (e && s && se) { return ((!w) && (!n) && (!nw)); } else { return false; } } /* * Determine whether removal of the center element preserves structure (does * not introduce holes, delete components, disconnect components, or shrink * components) given flags indicating which elements are present in the local * 3x3 neighborhood. */ bool is_removable_2D( bool n, bool s, bool e, bool w, bool ne, bool nw, bool se, bool sw) { /* compute number of adjacent neighbors */ unsigned long n_adjacent = (n ? 1 : 0) + (s ? 1 : 0) + (e ? 1 : 0) + (w ? 1 : 0); /* compute number of diagonal neighbors */ unsigned long n_diagonal = (ne ? 1 : 0) + (nw ? 1 : 0) + (se ? 1 : 0) + (sw ? 1 : 0); /* compute total number of neighbors */ unsigned long nn = n_adjacent + n_diagonal; /* check removability */ if (nn <= 2) { /* removing center will shrink or disconnect component */ return false; } else if (nn == 3) { /* can only remove if neighbors are adjacently connected */ return ( (ne && n && nw) || (n && ne && e) || (se && s && sw) || (n && nw && w) || (ne && e && se) || (s && se && e) || (nw && w && sw) || (s && sw && w) ); } else if (n_adjacent == 4) { /* removing center will create a hole */ return false; } else if (is_thick_region_2D(n, s, e, w, ne, nw, se, sw)) { /* can merge center with neighbors if the neighbors are connected */ unsigned long n_connect = ((n && (ne || e)) ? 1 : 0) + ((n && (nw || w)) ? 1 : 0) + ((s && (se || e)) ? 1 : 0) + ((s && (sw || w)) ? 1 : 0) + ((e && ne) ? 1 : 0) + ((e && se) ? 1 : 0) + ((w && nw) ? 1 : 0) + ((w && sw) ? 1 : 0); return ((n_connect+1) >= nn); } else { return false; } } /* * Determine whether the center element must be a vertex when elements are * grouped into contours given flags indicating which elements are present * in the local 3x3 neighborhood. */ bool is_vertex_2D( bool n, bool s, bool e, bool w, bool ne, bool nw, bool se, bool sw) { /* compute number of adjacent neighbors */ unsigned long n_adjacent = (n ? 1 : 0) + (s ? 1 : 0) + (e ? 1 : 0) + (w ? 1 : 0); /* compute number of diagonal neighbors */ unsigned long n_diagonal = (ne ? 1 : 0) + (nw ? 1 : 0) + (se ? 1 : 0) + (sw ? 1 : 0); /* compute total number of neighbors */ unsigned long nn = n_adjacent + n_diagonal; /* check vertex conditions */ if (nn <= 1) { /* start/end vertex - only 0 or 1 neighbors */ return true; } else if (nn == 2) { /* start/end vertex if neighbors are adjacent */ return ( (n && (ne || nw)) || (s && (se || sw)) || (e && (ne || se)) || (w && (nw || sw)) ); } else if ((nn == 3) || (nn == 4)) { if ((nw && n && w) || (n && ne && e) || (w && sw && s) || (e && s && se)) { /* block of 4 (including center) */ return true; } else if ((nw && n && ne) || (sw && s && se) || (nw && w && sw) || (ne && e && se)) { /* check for vertex hanging from three collinear points */ return (nn == 3); } else if (n_adjacent >= 3) { /* junction with adjacent neighbors */ return true; } else if (n_diagonal >= 3) { /* junction with diagonal neighbors */ return true; } else if ((n && se && sw) || (s && ne && nw) || (w && se && ne) || (e && nw && sw)) { /* junction with 1 adjacent, 2 diagonal */ return true; } else if ((nw && s && e) || (ne && s && w) || (sw && n && e) || (se && n && w)) { /* junction with 2 adjacent, 1 diagonal */ return true; } else { return false; } } else { /* check not in middle of H or truncated H shape */ return (!((n_adjacent == 2) && ((n && s) || (e && w)))); } } } /* namespace */ /*************************************************************************** * Skeletonization (2D). ***************************************************************************/ namespace { /* * Skeleton element. */ class skeleton_element { public: /* * Constructor. */ explicit skeleton_element( unsigned long x, unsigned long y, double v, bool is_erode, bool is_rem) : x(x), y(y), value(v), is_erodable(is_erode), is_removable(is_rem) { } /* * Copy constructor. */ explicit skeleton_element(const skeleton_element& el) : x(el.x), y(el.y), value(el.value), is_erodable(el.is_erodable), is_removable(el.is_removable) { } /* * Destructor. */ ~skeleton_element() { /* do nothing */ } /* * Data. */ unsigned long x; /* x-coordinate */ unsigned long y; /* y-coordinate */ double value; /* element value */ bool is_erodable; /* is removal an erosion operation? */ bool is_removable; /* will removal preserve topology? */ }; /* * Priority comparison functor for skeleton elements. */ class skeleton_element_priority_functor : public comparable_functor<skeleton_element> { public: int operator()( const skeleton_element& el0, const skeleton_element& el1) const { static const compare_functor<bool>& f_cmp_bool = compare_functors<bool>::f_compare(); static const compare_functor<double>& f_cmp_double = compare_functors<double>::f_compare(); int cmp_quality = -(f_cmp_bool(el0.is_erodable, el1.is_erodable)); if (cmp_quality == 0) cmp_quality = -(f_cmp_bool(el0.is_removable, el1.is_removable)); return ( (cmp_quality == 0) ? f_cmp_double(el0.value, el1.value) : cmp_quality ); } }; /* * Search comparison functor for skeleton elements. */ class skeleton_element_compare_functor : public comparable_functor<skeleton_element> { public: int operator()( const skeleton_element& el0, const skeleton_element& el1) const { static const compare_functor<unsigned long>& f_cmp = compare_functors<unsigned long>::f_compare(); int cmp_x = f_cmp(el0.x, el1.x); return ((cmp_x == 0) ? f_cmp(el0.y, el1.y) : cmp_x); } }; /* * Update the status of an element on the skeleton. * * Return whether immediate removal of the element is a simple erosion * (is_erodable), whether removal preserves structure (is_removable), and * whether the element may be a candidate for removal after other neighboring * elements have been removed (is_candidate). */ void skeleton_status( const double* m, /* matrix */ unsigned long size_x, /* matrix size in x-direction */ unsigned long size_y, /* matrix size in y-direction */ unsigned long x, /* x-coordinate of element */ unsigned long y, /* y-coordinate of element */ unsigned long ind, /* linear index of element */ bool& is_candidate, /* is the element a candidate for removal? */ bool& is_erodable, /* is the element currently erodable? */ bool& is_removable) /* is the element currently removable? */ { /* check that element has not already been removed */ if (m[ind] == 0) { is_candidate = false; is_erodable = false; is_removable = false; return; } /* check which neighbors are nonzero */ bool n = false, s = false, e = false, w = false; bool ne = false, nw = false, se = false, sw = false; neighbor_values_compare_2D( m, size_x, size_y, x, y, ind, 0.0, n, s, e, w, ne, nw, se, sw ); n = !n; s = !s; e = !e; w = !w; ne = !ne; nw = !nw; se = !se; sw = !sw; /* check if element should be a candidate if it is not currently */ is_candidate = is_candidate || is_thick_region_2D(n, s, e, w, ne, nw, se, sw); /* candidates are erodable if removal is a simple erosion */ is_erodable = is_candidate && is_erodable_2D(n, s, e, w, ne, nw, se, sw); /* candidates are immediately removable if removal preserves structure */ is_removable = (is_erodable) || (is_candidate && is_removable_2D(n, s, e, w, ne, nw, se, sw)); } } /* namespace */ /* * Skeletonize the given 2D matrix, preserving its topology. * * Nonzero elements are treated as part of an area to be skeletonized and * zero elements are treated as background. * * Skeletonization proceeds by repeatedly removing (setting to zero) the * smallest nonzero element whos deletion best preserves the topology. */ matrix<> lib_image::skeletonize_2D(const matrix<>& m) { /* initialize comparison functors */ static const skeleton_element_priority_functor* f_prio = new skeleton_element_priority_functor(); static const skeleton_element_compare_functor* f_search = new skeleton_element_compare_functor(); /* initialize skeleton matrix */ matrix<> skel(m); /* check that matrix is 2D */ if (skel._dims.size() != 2) throw ex_invalid_argument("matrix must be 2D"); /* get matrix size */ unsigned long size_x = skel._dims[0]; unsigned long size_y = skel._dims[1]; /* initialize queue of skeleton elements */ auto_collection< skeleton_element, queue_set<skeleton_element> > q( new queue_set<skeleton_element>(*f_prio, *f_search) ); unsigned long ind = 0; for (unsigned long x = 0; x < size_x; x++) { for (unsigned long y = 0; y < size_y; y++) { /* compute removability of element */ bool is_candidate = false; bool is_erodable = false; bool is_removable = false; skeleton_status( skel._data, size_x, size_y, x, y, ind, is_candidate, is_erodable, is_removable ); /* enqueue candidate elements */ if (is_candidate) { auto_ptr<skeleton_element> el( new skeleton_element( x, y, skel._data[ind], is_erodable, is_removable ) ); q->enqueue(*el); el.release(); } /* increment linear index */ ind++; } } /* repeatedly remove elements and update skeleton */ while (!(q->is_empty())) { /* dequeue element */ auto_ptr<skeleton_element> el(&(q->dequeue())); /* check if skeletonization is complete */ if (!(el->is_removable)) break; /* update skeleton */ unsigned long el_x = el->x; unsigned long el_y = el->y; ind = el_x * size_y + el_y; skel._data[ind] = 0; /* compute size of local neighborhood */ unsigned long start_x = (el_x > 0) ? (el_x-1) : (el_x); unsigned long start_y = (el_y > 0) ? (el_y-1) : (el_y); unsigned long end_x = ((el_x+1) < size_x) ? (el_x+1) : (el_x); unsigned long end_y = ((el_y+1) < size_y) ? (el_y+1) : (el_y); unsigned long n_y = end_y - start_y + 1; if (el_x > 0) { ind -= size_y; } if (el_y > 0) { ind--; } /* update surrounding elements in queue */ for (unsigned long x = start_x; x <= end_x; x++) { for (unsigned long y = start_y; y <= end_y; y++) { /* check if on skeleton */ if (skel._data[ind] != 0) { /* check if element is in queue */ skeleton_element el_search(x, y, 0, false, false); if (q->contains(el_search)) { /* find element in queue */ skeleton_element& el_curr = q->find(el_search); /* update element status */ bool is_candidate = true; skeleton_status( skel._data, size_x, size_y, x, y, ind, is_candidate, el_curr.is_erodable, el_curr.is_removable ); /* update element in queue */ q->update(el_curr); } } /* increment linear index */ ind++; } /* reset linear index */ ind -= n_y; ind += size_y; } } return skel; } /*************************************************************************** * Connected components. ***************************************************************************/ /* * Label connected components in a matrix. * * For real-valued matrices, adjacent nonzero elements are considered * connected. For integer-valued matrices, adjacent elements must also * have the same value to be considered connected. In both cases, zero * elements denote empty space. * * Each element is assigned an integer label indicating the component to * which it belongs. The label zero is assigned to elements not part of * any component. Labels range from 0 to n, where n is the number of * components. * * Optionally, a mask matrix can be specified to determine to which elements * of the local neighborhood the center element may possibly be connected. * The default mask is the local neighborhood of size 3^d where d is the * dimensionality of the matrix. * * NOTE: The mask must be nonempty and should be symmetric about its center * (connectivity is ill-defined when using an asymmetric mask). */ matrix<unsigned long> lib_image::connected_components( const matrix<>& m) { /* create integer-valued matrix (map all nonzero values to 1) */ matrix<unsigned long> m_nonzero(m._dims); for (unsigned long n = 0; n < m._size; n++) { if (m._data[n] != 0) m_nonzero._data[n] = 1; } /* compute connected components */ return lib_image::connected_components(m_nonzero); } matrix<unsigned long> lib_image::connected_components( const matrix<unsigned long>& m) { /* create default mask for full 3^d neighborhood */ unsigned long n_dims = m._dims.size(); array<unsigned long> mask_dims(n_dims, 3); matrix<bool> mask(mask_dims, true); if (n_dims > 0) mask._data[mask._size/2] = false; /* don't compare center to itself */ /* label connected components */ return lib_image::connected_components(m, mask); } matrix<unsigned long> lib_image::connected_components( const matrix<>& m, const matrix<bool>& mask) { /* create integer-valued matrix (map all nonzero values to 1) */ matrix<unsigned long> m_nonzero(m._dims); for (unsigned long n = 0; n < m._size; n++) { if (m._data[n] != 0) m_nonzero._data[n] = 1; } /* compute connected components */ return lib_image::connected_components(m_nonzero, mask); } matrix<unsigned long> lib_image::connected_components( const matrix<unsigned long>& m, const matrix<bool>& mask) { /* check that mask is nonempty */ if (mask._size == 0) throw ex_invalid_argument("mask must be nonempty"); /* get number of dimensions */ unsigned long n_dims_m = m._dims.size(); unsigned long n_dims_mask = mask._dims.size(); unsigned long n_dims = (n_dims_m > n_dims_mask) ? n_dims_m : n_dims_mask; /* extend dimension arrays */ array<unsigned long> dims_m = matrix<>::extend_dims(m._dims, n_dims); array<unsigned long> dims_mask = matrix<>::extend_dims(mask._dims, n_dims); /* compute step sizes along each dimension */ array<unsigned long> sizes_m = matrix<>::dims_sizes(dims_m); array<unsigned long> sizes_mask = matrix<>::dims_sizes(dims_mask); /* compute mask size to left/right of center along each dimension */ array<unsigned long> mask_size_left(n_dims); array<unsigned long> mask_size_right(n_dims); for (unsigned long d = 0; d < n_dims; d++) { unsigned long s = dims_mask[d] - 1; mask_size_left[d] = s / 2; mask_size_right[d] = s - mask_size_left[d]; } /* allocate arrays to store position in local neighborhood */ array<unsigned long> neighbor_pos(n_dims); array<unsigned long> neighbor_pos_start(n_dims); array<unsigned long> neighbor_pos_end(n_dims); array<unsigned long> neighborhood_diff(n_dims); /* initialize queue of elements to process */ auto_collection< array<unsigned long>, list< array<unsigned long> > > q( new list< array<unsigned long> >() ); /* initialize labels */ matrix<unsigned long> labels(m._dims); unsigned long next_label = 1; /* initialize position in matrix */ array<unsigned long> pos(n_dims); /* follow connected components from each element */ for (unsigned long n = 0; n < m._size; n++) { /* check if current position begins component */ unsigned long val = m._data[n]; if ((val != 0) && (labels._data[n] == 0)) { /* label it */ labels._data[n] = next_label; /* enqueue current position */ { auto_ptr< array<unsigned long> > pos_copy( new array<unsigned long>(pos) ); q->add(*pos_copy); pos_copy.release(); } /* follow current connected component */ while (!(q->is_empty())) { /* dequeue position */ auto_ptr< array<unsigned long> > curr_pos(&(q->remove_head())); /* initialize indices and position in neighborhood */ unsigned long ind_m = 0; unsigned long ind_mask = 0; for (unsigned long d = 0; d < n_dims; d++) { unsigned long p = (*curr_pos)[d]; unsigned long s_left = mask_size_left[d]; unsigned long s_right = mask_size_right[d]; /* compute start position along dimension d */ unsigned long pos_start_m = 0; if (p >= s_left) { pos_start_m = p - s_left; } else { ind_mask += (s_left - p) * sizes_mask[d]; } ind_m += pos_start_m * sizes_m[d]; /* compute end position along dimension d*/ unsigned long pos_end_m = ((p + s_right) < dims_m[d]) ? (p + s_right) : (dims_m[d] - 1); /* store position in neighborhood */ neighbor_pos[d] = pos_start_m; neighbor_pos_start[d] = pos_start_m; neighbor_pos_end[d] = pos_end_m; neighborhood_diff[d] = pos_end_m - pos_start_m; } /* label and enqueue any unlabeled adjacent positions */ while (true) { /* check if unlabeled and adjacent */ if ((m._data[ind_m] == val) && (labels._data[ind_m] == 0) && (mask._data[ind_mask])) { /* label */ labels._data[ind_m] = next_label; /* enqueue */ { auto_ptr< array<unsigned long> > pos_copy( new array<unsigned long>(neighbor_pos) ); q->add(*pos_copy); pos_copy.release(); } } /* update position in local neighborhood */ unsigned long d = n_dims - 1; while ((neighbor_pos[d] == neighbor_pos_end[d]) && (d > 0)) { ind_m -= neighborhood_diff[d] * sizes_m[d]; ind_mask -= neighborhood_diff[d] * sizes_mask[d]; neighbor_pos[d] = neighbor_pos_start[d]; d--; } if (neighbor_pos[d] < neighbor_pos_end[d]) { ind_m += sizes_m[d]; ind_mask += sizes_mask[d]; neighbor_pos[d]++; } else { break; } } } /* increment next label */ next_label++; } /* update position */ { unsigned long d = n_dims - 1; pos[d]++; while ((pos[d] == dims_m[d]) && (d > 0)) { pos[d] = 0; d--; pos[d]++; } } } return labels; } /* * Label connected components along the specified dimension of the matrix. * * For real-valued matrices, adjacent nonzero elements are considered * connected. For integer-valued matrices, adjacent elements must also * have the same value to be considered connected. In both cases, zero * elements denote empty space. * * As above, labels range from 0 to n, where n is the number of components. */ matrix<unsigned long> lib_image::connected_components( const matrix<>& m, unsigned long d) { /* create integer-valued matrix (map all nonzero values to 1) */ matrix<unsigned long> m_nonzero(m._dims); for (unsigned long n = 0; n < m._size; n++) { if (m._data[n] != 0) m_nonzero._data[n] = 1; } /* compute connected components along dimension */ return lib_image::connected_components(m_nonzero, d); } matrix<unsigned long> lib_image::connected_components( const matrix<unsigned long>& m, unsigned long d) { /* get # steps along dimension */ unsigned long n_dims = m._dims.size(); unsigned long n_steps = (d < n_dims) ? m._dims[d] : 1; /* initialize labels */ matrix<unsigned long> labels(m._dims); /* check that result is nontrivial */ if (labels._size > 0) { /* compute indices along first slice of dimension */ array<unsigned long> inds = matrix<>::linear_indices_slice(m._dims, d); /* compute step size along dimension */ unsigned long step_size = matrix<>::dims_size(m._dims, d); /* compute result matrix */ unsigned long label = 0; unsigned long n_inds = inds.size(); for (unsigned long n = 0; n < n_inds; n++) { unsigned long ind = inds[n]; unsigned long val_prev = 0; for (unsigned long n_step = 0; n_step < n_steps; n_step++) { unsigned long val = m._data[ind]; if (val != 0) { if (val != val_prev) label++; labels._data[ind] = label; } val_prev = val; ind += step_size; } } } return labels; } /* * Return the number of connected components (excluding the zero component) * in a labeled component matrix generated by one of the above functions. * * Since components are numbered in order, this is the same as the maximum * value in the matrix. */ unsigned long lib_image::count_connected_components( const matrix<unsigned long>& labels) { return max(labels); } /*************************************************************************** * Contour and region scanning (2D). ***************************************************************************/ namespace { /* * Compute and return the indices of the cells in a grid that intersect the * specified vertical line segment. * * The entire line segment must lie within the grid. */ auto_ptr< array<unsigned long> > scan_vertical_line_segment( unsigned long x, /* segment x-coordinate */ unsigned long y_start, /* segment starting y-coordinate */ unsigned long y_end, /* segment ending y-coordinate */ unsigned long size_y) /* grid size in y-direction */ { bool direction = (y_end >= y_start); unsigned long n_steps = direction ? (y_end - y_start) : (y_start - y_end); auto_ptr< array<unsigned long> > inds(new array<unsigned long>(n_steps + 1)); unsigned long ind = x * size_y + y_start; (*inds)[0] = ind; for (unsigned long n = 1; n <= n_steps; n++) { if (direction) { ind++; } else { ind--; } (*inds)[n] = ind; } return inds; } /* * Compute and return the indices of the cells in a grid that intersect the * specified horizontal line segment. * * The entire line segment must lie within the grid. */ auto_ptr< array<unsigned long> > scan_horizontal_line_segment( unsigned long y, /* segment y-coordinate */ unsigned long x_start, /* segment starting x-coordinate */ unsigned long x_end, /* segment ending x-coordinate */ unsigned long size_y) /* grid size in y-direction */ { bool direction = (x_end >= x_start); unsigned long n_steps = direction ? (x_end - x_start) : (x_start - x_end); auto_ptr< array<unsigned long> > inds(new array<unsigned long>(n_steps + 1)); unsigned long ind = x_start * size_y + y; (*inds)[0] = ind; for (unsigned long n = 1; n <= n_steps; n++) { if (direction) { ind += size_y; } else { ind -= size_y; } (*inds)[n] = ind; } return inds; } /* * Compute and return the indices of the cells in a grid that intersect the * straight line segment between with the given start and end points. * * The entire line segment must lie within the grid. */ auto_ptr< array<unsigned long> > scan_line_segment( const point_2D& p_start, /* line segment start */ const point_2D& p_end, /* line segment end */ unsigned long size_y, /* grid size in y-direction */ bool allow_diagonal = true) /* allow diagonal connectivity? */ { /* get segment endpoint coordinates */ double x_start = p_start.x(); double y_start = p_start.y(); double x_end = p_end.x(); double y_end = p_end.y(); /* compute grid coordinates */ unsigned long x_start_grid = static_cast<unsigned long>(math::round(x_start)); unsigned long y_start_grid = static_cast<unsigned long>(math::round(y_start)); unsigned long x_end_grid = static_cast<unsigned long>(math::round(x_end)); unsigned long y_end_grid = static_cast<unsigned long>(math::round(y_end)); /* check slope */ if (x_start_grid == x_end_grid) { /* vertical line segment */ return scan_vertical_line_segment( x_start_grid, y_start_grid, y_end_grid, size_y ); } else if (y_start_grid == y_end_grid) { /* horizontal line segment */ return scan_horizontal_line_segment( y_start_grid, x_start_grid, x_end_grid, size_y ); } else { /* compute direction of motion */ bool direction_x = (x_end_grid >= x_start_grid); bool direction_y = (y_end_grid >= y_start_grid); /* compute offsets of next pixel boundaries */ double delta_x = direction_x ? 0.5 : -0.5; double delta_y = direction_y ? 0.5 : -0.5; /* compute equation of line */ double slope = (y_end - y_start) / (x_end - x_start); double offset = y_start - slope * x_start; /* determine how to break ties when moving along diagonal */ bool prefer_vertical = (math::abs(slope) >= 1); /* initialize index array */ unsigned long max_steps_x = direction_x ? (x_end_grid - x_start_grid) : (x_start_grid - x_end_grid); unsigned long max_steps_y = direction_y ? (y_end_grid - y_start_grid) : (y_start_grid - y_end_grid); unsigned long max_steps = max_steps_x + max_steps_y; auto_ptr< array<unsigned long> > inds( new array<unsigned long>(max_steps + 1) ); /* initialize indices */ unsigned long ind = x_start_grid * size_y + y_start_grid; unsigned long ind_end = x_end_grid * size_y + y_end_grid; /* store starting point */ (*inds)[0] = ind; /* initialize current coordinate */ double x = static_cast<double>(x_start_grid); double y = static_cast<double>(y_start_grid); /* initialize segment length */ unsigned long n_points = 1; /* move along line segment */ while ((ind != ind_end) && (n_points <= max_steps)) { /* compute location of next grid cell intersected by segment */ double y_boundary = y + delta_y; double y_at_x_boundary = slope * (x + delta_x) + offset; bool move_vertical = false; bool move_horizontal = false; if (y_boundary < y_at_x_boundary) { move_vertical = direction_y; move_horizontal = !direction_y; } else if (y_boundary > y_at_x_boundary) { move_vertical = !direction_y; move_horizontal = direction_y; } else { move_vertical = allow_diagonal || prefer_vertical; move_horizontal = allow_diagonal || !prefer_vertical; } /* move to next grid cell */ if (move_vertical) { if (direction_y) { y++; ind++; } else { y--; ind--; } } if (move_horizontal) { if (direction_x) { x++; ind += size_y; } else { x--; ind -= size_y; } } /* store index */ (*inds)[n_points++] = ind; } inds->resize(n_points); return inds; } } /* * Check whether the specified point lies within the grid of the given size. */ bool is_in_grid( const point_2D& p, /* point */ unsigned long size_x, /* grid size in x-direction */ unsigned long size_y) /* grid size in y-direction */ { return ((0 <= p.x()) && (p.x() <= (static_cast<double>(size_x) - 1.0)) && (0 <= p.y()) && (p.y() <= (static_cast<double>(size_y) - 1.0))); } /* * Clip the line segment so that only the portion lying completely within the * grid of the specified size remains. Update the line segment endpoint. * * The start point must already lie within the grid. The end point will be * clipped. */ void clip_line_segment_to_grid( const point_2D& p_start, /* line segment start (must be within grid) */ point_2D& p_end, /* line segment end (will be clipped to grid) */ unsigned long size_x, /* grid size in x-direction */ unsigned long size_y) /* grid size in y-direction */ { /* get segment endpoint coordinates */ double x_start = p_start.x(); double y_start = p_start.y(); double x_end = p_end.x(); double y_end = p_end.y(); /* compute bound in each dimension */ double x_bound = static_cast<double>(size_x) - 1.0; double y_bound = static_cast<double>(size_y) - 1.0; /* adjust so that x-coordinate is within range */ if (x_end < 0) { y_end = y_start + (y_end-y_start)/(x_end-x_start) * (-x_start); x_end = 0; } else if (x_end > x_bound) { y_end = y_start + (y_end-y_start)/(x_end-x_start) * (x_bound-x_start); x_end = x_bound; } /* adjust so that y-coordinate is within range */ if (y_end < 0) { x_end = x_start + (x_end-x_start)/(y_end-y_start) * (-y_start); y_end = 0; } else if (y_end > y_bound) { x_end = x_start + (x_end-x_start)/(y_end-y_start) * (y_bound-y_start); y_end = y_bound; } /* update endpoint */ p_end.x() = x_end; p_end.y() = y_end; } /* * Compute and return the indices of the cells in a grid that intersect the * circular disc of radius r around the point p. These indices are computed * by shooting a ray from p to each point with integer coordinates on the * boundary of the disc. We return a collection of index sets, one for each * ray. The complete set of indices is the union of indices in the returned * arrays. * * Note that p must lie within the grid. */ auto_collection< array<unsigned long> > scan_disc( const point_2D& p, /* disc center (must be within grid) */ double r, /* disc radius */ unsigned long size_x, /* grid size in x-direction */ unsigned long size_y) /* grid size in y-direction */ { /* initialize collection of indices */ auto_collection< array<unsigned long> > inds( new list< array<unsigned long> >() ); /* loop over boundary */ r = math::abs(r); unsigned long n_steps = static_cast<unsigned long>(math::ceil(2*M_PIl*r))+1; double step_size = 2*M_PIl / static_cast<double>(n_steps); double theta = 0; for (unsigned long n = 0; n < n_steps; n++, theta += step_size) { /* compute point on disc boundary */ double x_offset = r * math::cos(theta); double y_offset = r * math::sin(theta); point_2D q(p.x() + x_offset, p.y() + y_offset); /* scan line segment from center to boundary */ clip_line_segment_to_grid(p, q, size_x, size_y); auto_ptr< array<unsigned long> > inds_segment = scan_line_segment(p, q, size_y, false); /* store indices */ inds->add(*inds_segment); inds_segment.release(); } return inds; } } /* namespace */ /*************************************************************************** * Contour extraction (2D). ***************************************************************************/ namespace { /* * Create a contour vertex with the specified coordinates. */ auto_ptr<lib_image::contour_vertex> create_contour_vertex( unsigned long x, unsigned long y) { auto_ptr<lib_image::contour_vertex> v(new lib_image::contour_vertex()); /* set vertex identity to defaults */ v->id = 0; v->is_subdivision = false; /* set vertex coordinates */ v->x = x; v->y = y; return v; } /* * Create a contour edge between the two specified vertices. */ auto_ptr<lib_image::contour_edge> create_contour_edge( lib_image::contour_vertex& v_start, lib_image::contour_vertex& v_end) { auto_ptr<lib_image::contour_edge> e(new lib_image::contour_edge()); /* set edge identity to defaults */ e->id = 0; e->contour_equiv_id = 0; e->is_completion = false; /* set edge vertices */ e->vertex_start = &v_start; e->vertex_end = &v_end; /* update vertex edge lists */ e->vertex_start_enum = v_start.edges_start.size(); e->vertex_end_enum = v_end.edges_end.size(); v_start.edges_start.add(*e); v_end.edges_end.add(*e); return e; } } /* namespace */ /* * Return the point representing the contour vertex. */ point_2D lib_image::contour_vertex::point() const { return point_2D( static_cast<double>(this->x), static_cast<double>(this->y) ); } /* * Return the point at the given position along the contour edge. */ point_2D lib_image::contour_edge::point(unsigned long n) const { return point_2D( static_cast<double>(this->x_coords[n]), static_cast<double>(this->y_coords[n]) ); } /* * Return the size (number of interior points) of the contour edge. */ unsigned long lib_image::contour_edge::size() const { return this->x_coords.size(); } /* * Return the length (distance between endpoints) of the contour edge. */ double lib_image::contour_edge::length() const { return abs((this->vertex_end->point()) - (this->vertex_start->point())); } /* * Extract contours from labeled connected components. * * Break each connected component into a set of thin contours that may * intersect only at returned contour vertices. */ lib_image::contour_set::contour_set(const matrix<unsigned long>& labels) : _is_vertex(), _is_edge(), _assignments(), _vertices(new array_list<contour_vertex>()), _edges(new array_list<contour_edge>()), _edges_equiv(new array_list< list<contour_edge> >()) { /* check that label matrix is 2D */ if (labels.dimensionality() != 2) throw ex_invalid_argument("matrix must be 2D"); /* get matrix size */ unsigned long size_x = labels.size(0); unsigned long size_y = labels.size(1); /* initialize pixel assignment map */ _is_vertex.resize(size_x, size_y); _is_edge.resize(size_x, size_y); _assignments.resize(size_x, size_y, 0 /* init value */); /* initialize map of connected component label -> vertex in it */ unsigned long n_labels = lib_image::count_connected_components(labels); array<bool> has_vertex(n_labels); array<unsigned long> label_x(n_labels); array<unsigned long> label_y(n_labels); /* find all vertices */ for (unsigned long ind = 0, x = 0; x < size_x; x++) { for (unsigned long y = 0; y < size_y; y++) { /* check if part of an edge */ unsigned long label = labels[ind]; if (label != 0) { /* check if neighbors have the same label */ bool n = false, s = false, e = false, w = false; bool ne = false, nw = false, se = false, sw = false; neighbor_values_compare_2D( labels.data(), size_x, size_y, x, y, ind, label, n, s, e, w, ne, nw, se, sw ); /* check vertex conditions */ if (is_vertex_2D(n, s, e, w, ne, nw, se, sw)) { /* create vertex and set its id */ auto_ptr<contour_vertex> v = create_contour_vertex(x, y); v->id = _vertices->size(); /* record vertex assignment */ _assignments[ind] = v->id; /* add vertex to vertex set */ _vertices->add(*v); v.release(); /* mark vertex */ _is_vertex[ind] = true; /* indicate vertex found for current label */ has_vertex[label-1] = true; } /* record position of element with current label */ label_x[label-1] = x; label_y[label-1] = y; } /* increment linear coordinate */ ind++; } } /* detect loops and arbitrarily pick a vertex for any loop */ for (unsigned long n = 0; n < n_labels; n++) { if (!has_vertex[n]) { /* create vertex and set its id */ auto_ptr<contour_vertex> v = create_contour_vertex( label_x[n], label_y[n] ); v->id = _vertices->size(); /* record vertex assignment */ _assignments(label_x[n], label_y[n]) = v->id; /* add vertex to vertex set */ _vertices->add(*v); v.release(); /* mark vertex */ _is_vertex(label_x[n], label_y[n]) = true; /* indicate vertex found for current label */ has_vertex[n] = true; } } /* process all vertices */ for (unsigned long v_id = 0; v_id < _vertices->size(); v_id++) { /* grab vertex */ contour_vertex& v = (*_vertices)[v_id]; unsigned long label = labels(v.x, v.y); /* initialize queue of vertex neighbors */ array<unsigned long> q_x(8 /* max # of neighbors */); array<unsigned long> q_y(8 /* max # of neighbors */); unsigned long n_neighbors = 0; /* enqueue coordinates of adjacent neighbors with the same label */ unsigned long x_start = (v.x > 0) ? (v.x - 1) : (v.x + 1); unsigned long x_end = (v.x + 1); for (unsigned long x = x_start; (x <= x_end) && (x < size_x); x += 2) { if (labels(x, v.y) == label) { q_x[n_neighbors] = x; q_y[n_neighbors] = v.y; n_neighbors++; } } unsigned long y_start = (v.y > 0) ? (v.y - 1) : (v.y + 1); unsigned long y_end = (v.y + 1); for (unsigned long y = y_start; (y <= y_end) && (y < size_y); y += 2) { if (labels(v.x, y) == label) { q_x[n_neighbors] = v.x; q_y[n_neighbors] = y; n_neighbors++; } } /* enqueue coordinates of diagonal neighbors with the same label */ /* only consider diagonal neighbors unreachable through adjacent ones */ for (unsigned long x = x_start; (x <= x_end) && (x < size_x); x += 2) { for (unsigned long y = y_start; (y <= y_end) && (y < size_y); y += 2) { if ((labels(x, y) == label) && (labels(v.x, y) != label) && (labels(x, v.y) != label)) { q_x[n_neighbors] = x; q_y[n_neighbors] = y; n_neighbors++; } } } /* process neighbors */ for (unsigned long n = 0; n < n_neighbors; n++) { /* get neighbor index */ unsigned long ind = q_x[n] * size_y + q_y[n]; /* check neighbor status */ if (_is_vertex[ind]) { /* check if vertex with higher id -> make edge */ if (_assignments[ind] > v_id) { /* create edge and set its identity */ contour_vertex& v_end = (*_vertices)[_assignments[ind]]; auto_ptr<contour_edge> e = create_contour_edge(v, v_end); e->id = _edges->size(); e->contour_equiv_id = e->id; /* create edge equivalence class */ auto_ptr< list<contour_edge> > e_equiv(new list<contour_edge>()); e_equiv->add(*e); /* add edge */ _edges->add(*e); e.release(); _edges_equiv->add(*e_equiv); e_equiv.release(); } } else if (!_is_edge[ind]) { /* neighbor not assigned to an edge -> trace edge */ this->trace_edge(labels, v_id, q_x[n], q_y[n]); } } } /* find and remove unused vertices (single pixel islands) */ unsigned long n_vertices = _vertices->size(); for (unsigned long v_id = 0, n = 0; n < n_vertices; n++) { auto_ptr<contour_vertex> v(&(_vertices->remove_head())); if ((v->edges_start.is_empty()) && (v->edges_end.is_empty())) { /* remove vertex */ _is_vertex(v->x, v->y) = false; } else { /* update vertex id */ v->id = v_id++; _assignments(v->x, v->y) = v->id; /* add vertex */ _vertices->add(*v); v.release(); } } } /* * Copy constructor. */ lib_image::contour_set::contour_set(const contour_set& contours) : _is_vertex(contours._is_vertex), _is_edge(contours._is_edge), _assignments(contours._assignments), _vertices(new array_list<contour_vertex>()), _edges(new array_list<contour_edge>()), _edges_equiv(new array_list< list<contour_edge> >()) { /* copy vertices */ for (unsigned long n = 0, n_v = contours._vertices->size(); n < n_v; n++) { /* create vertex copy */ const contour_vertex& v = (*(contours._vertices))[n]; auto_ptr<contour_vertex> v_copy = create_contour_vertex(v.x, v.y); v_copy->id = v.id; v_copy->is_subdivision = v.is_subdivision; /* store vertex copy */ _vertices->add(*v_copy); v_copy.release(); } /* copy edges */ for (unsigned long n = 0, n_e = contours._edges->size(); n < n_e; n++) { /* create edge copy */ const contour_edge& e = (*(contours._edges))[n]; auto_ptr<contour_edge> e_copy = create_contour_edge( (*_vertices)[e.vertex_start->id], (*_vertices)[e.vertex_end->id] ); e_copy->id = e.id; e_copy->contour_equiv_id = e.contour_equiv_id; e_copy->is_completion = e.is_completion; e_copy->x_coords = e.x_coords; e_copy->y_coords = e.y_coords; /* store edge copy */ _edges->add(*e_copy); e_copy.release(); } /* copy edge equivalence classes */ for (unsigned long n = 0, n_e = contours._edges_equiv->size(); n < n_e; n++) { /* create equivalence class copy */ const list<contour_edge>& edge_equiv = (*(contours._edges_equiv))[n]; auto_ptr< list<contour_edge> > edge_equiv_copy(new list<contour_edge>()); for (list<contour_edge>::iterator_t i(edge_equiv); i.has_next(); ) { const contour_edge& e = i.next(); edge_equiv_copy->add((*_edges)[e.id]); } /* store equivalence class copy */ _edges_equiv->add(*edge_equiv_copy); edge_equiv_copy.release(); } } /* * Destructor. */ lib_image::contour_set::~contour_set() { /* do nothing */ } /*************************************************************************** * Contour edge operations. ***************************************************************************/ /* * Given connected component labels, the starting vertex of an edge, * and the next pixel along the edge, trace the entire contour and * add it to the set. */ void lib_image::contour_set::trace_edge( const matrix<unsigned long>& labels, unsigned long v_id, unsigned long x, unsigned long y) { /* get matrix size */ unsigned long size_x = labels.size(0); unsigned long size_y = labels.size(1); /* grab current vertex and label */ contour_vertex& v = (*_vertices)[v_id]; unsigned long ind_v = (v.x) * size_y + (v.y); unsigned long label = labels[ind_v]; /* initialize coordinates along edge */ auto_collection< unsigned long, array_list<unsigned long> > e_x( new array_list<unsigned long>() ); auto_collection< unsigned long, array_list<unsigned long> > e_y( new array_list<unsigned long>() ); /* temporarily mark start vertex as inaccessible */ _is_edge[ind_v] = true; /* trace edge */ unsigned long e_id = _edges->size(); bool endpoint_is_new_vertex = false; do { /* add latest coordinate to edge */ auto_ptr<unsigned long> ptr_x(new unsigned long(x)); auto_ptr<unsigned long> ptr_y(new unsigned long(y)); e_x->add(*ptr_x); ptr_x.release(); e_y->add(*ptr_y); ptr_y.release(); /* mark as edge */ unsigned long ind = x * size_y + y; _is_edge[ind] = true; _assignments[ind] = e_id; /* compute which neighbors are present in matrix */ bool has_n = false, has_s = false, has_e = false, has_w = false; bool has_ne = false, has_nw = false, has_se = false, has_sw = false; neighbor_exists_2D( size_x, size_y, x, y, has_n, has_s, has_e, has_w, has_ne, has_nw, has_se, has_sw ); /* compute indices of neighbors */ unsigned long ind_n = 0, ind_s = 0, ind_e = 0, ind_w = 0; unsigned long ind_ne = 0, ind_nw = 0, ind_se = 0, ind_sw = 0; neighbor_indices_2D( size_y, ind, ind_n, ind_s, ind_e, ind_w, ind_ne, ind_nw, ind_se, ind_sw ); /* check which neighbors are available */ bool av_n = has_n ? ((labels[ind_n] == label) && (!_is_edge[ind_n])) : false; bool av_s = has_s ? ((labels[ind_s] == label) && (!_is_edge[ind_s])) : false; bool av_e = has_e ? ((labels[ind_e] == label) && (!_is_edge[ind_e])) : false; bool av_w = has_w ? ((labels[ind_w] == label) && (!_is_edge[ind_w])) : false; bool av_ne = has_ne ? ((labels[ind_ne] == label) && (!_is_edge[ind_ne])) : false; bool av_nw = has_nw ? ((labels[ind_nw] == label) && (!_is_edge[ind_nw])) : false; bool av_se = has_se ? ((labels[ind_se] == label) && (!_is_edge[ind_se])) : false; bool av_sw = has_sw ? ((labels[ind_sw] == label) && (!_is_edge[ind_sw])) : false; /* check for adjacent non-vertex */ if (av_n) { if (!_is_vertex[ind_n]) { y++; continue; } } if (av_s) { if (!_is_vertex[ind_s]) { y--; continue; } } if (av_e) { if (!_is_vertex[ind_e]) { x++; continue; } } if (av_w) { if (!_is_vertex[ind_w]) { x--; continue; } } /* check for adjacent vertex */ if (av_n) { y++; break; } if (av_s) { y--; break; } if (av_e) { x++; break; } if (av_w) { x--; break; } /* check for diagonal non-vertex */ if (av_ne) { if (!_is_vertex[ind_ne]) { x++; y++; continue; } } if (av_nw) { if (!_is_vertex[ind_nw]) { x--; y++; continue; } } if (av_se) { if (!_is_vertex[ind_se]) { x++; y--; continue; } } if (av_sw) { if (!_is_vertex[ind_sw]) { x--; y--; continue; } } /* check for diagonal vertex */ if (av_ne) { x++; y++; break; } if (av_nw) { x--; y++; break; } if (av_se) { x++; y--; break; } if (av_sw) { x--; y--; break; } /* otherwise, we have discovered a new vertex */ endpoint_is_new_vertex = true; _is_edge[ind] = false; /* last point is a new vertex, not an edge */ } while (!endpoint_is_new_vertex); /* remove inaccessible mark from start vertex */ _is_edge[ind_v] = false; /* add endpoint as vertex (if needed) */ unsigned long ind_end = x * size_y + y; if (endpoint_is_new_vertex) { /* create vertex and set its id */ auto_ptr<contour_vertex> v_end = create_contour_vertex(x, y); v_end->id = _vertices->size(); /* record vertex assignment */ _assignments[ind_end] = v_end->id; /* add vertex to vertex set */ _vertices->add(*v_end); v_end.release(); /* mark vertex */ _is_vertex[ind_end] = true; } /* create edge and set its identity */ contour_vertex& v_e = (*_vertices)[_assignments[ind_end]]; auto_ptr<contour_edge> e = create_contour_edge(v, v_e); e->id = e_id; e->contour_equiv_id = e_id; /* store edge coordinates */ unsigned long n_edge_points = (endpoint_is_new_vertex ? (e_x->size() - 1) : (e_x->size())); e->x_coords.resize(n_edge_points); e->y_coords.resize(n_edge_points); for (unsigned long n = 0; n < n_edge_points; n++) { e->x_coords[n] = (*e_x)[n]; e->y_coords[n] = (*e_y)[n]; } /* create edge equivalence class */ auto_ptr< list<contour_edge> > e_equiv(new list<contour_edge>()); e_equiv->add(*e); /* add edge */ _edges->add(*e); e.release(); _edges_equiv->add(*e_equiv); e_equiv.release(); } /* * Split the contour edge with the given id at the specified position. */ void lib_image::contour_set::split_edge(unsigned long e_id, unsigned long p) { /* get the edge to split */ contour_edge& e = (*_edges)[e_id]; /* check that split position is valid */ unsigned long n_points = e.size(); if (p >= n_points) throw ex_index_out_of_bounds("invalid contour split point", p); /* create split vertex */ auto_ptr<contour_vertex> v_split = create_contour_vertex( e.x_coords[p], e.y_coords[p] ); v_split->id = _vertices->size(); v_split->is_subdivision = true; /* record vertex assignment */ unsigned long ind_v = (v_split->x) * (this->size_y()) + (v_split->y); _assignments[ind_v] = v_split->id; /* mark vertex */ _is_edge[ind_v] = false; _is_vertex[ind_v] = true; /* create split edge */ auto_ptr<contour_edge> e_split(new contour_edge()); e_split->id = _edges->size(); e_split->contour_equiv_id = e.contour_equiv_id; e_split->is_completion = e.is_completion; /* update start and end vertices */ e_split->vertex_start = v_split.get(); e_split->vertex_end = e.vertex_end; e.vertex_end = e_split->vertex_start; /* update existing edge linkage */ e_split->vertex_end->edges_end.replace(e.vertex_end_enum, *e_split); e_split->vertex_end_enum = e.vertex_end_enum; /* add edge linkage to split vertex */ v_split->edges_start.add(*e_split); v_split->edges_end.add(e); e_split->vertex_start_enum = 0; e.vertex_end_enum = 0; /* split points along edge */ unsigned long n_points_left = p; unsigned long n_points_right = (n_points - 1) - p; if (n_points_right > 0) { e_split->x_coords = e.x_coords.subarray((p + 1), (n_points - 1)); e_split->y_coords = e.y_coords.subarray((p + 1), (n_points - 1)); } e.x_coords.resize(n_points_left); e.y_coords.resize(n_points_left); /* update edge assignments */ for (unsigned long n = 0; n < n_points_right; n++) _assignments(e_split->x_coords[n], e_split->y_coords[n]) = e_split->id; /* update vertex set */ _vertices->add(*v_split); v_split.release(); /* update edge set */ (*_edges_equiv)[e_split->contour_equiv_id].add(*e_split); _edges->add(*e_split); e_split.release(); } /* * Sort the list of edges in each edge equivalence class so they appear * in the order encountered on a traversal of the original contour edge. */ void lib_image::contour_set::sort_edges_equiv() { /* initialize map of subdivision vertex id -> next edge */ unsigned long n_vertices = _vertices->size(); unsigned long n_edges = _edges->size(); array<unsigned long> next_edge(n_vertices); array<bool> has_prev(n_vertices); /* process each equivalence class */ unsigned long n_equiv = _edges_equiv->size(); for (unsigned long equiv_id = 0; equiv_id < n_equiv; equiv_id++) { /* get set of edges in equivalence class */ list<contour_edge>& equiv_set = (*_edges_equiv)[equiv_id]; /* build vertex map */ for (list<contour_edge>::iterator_t i(equiv_set); i.has_next(); ) { const contour_edge& e = i.next(); next_edge[e.vertex_start->id] = e.id; has_prev[e.vertex_end->id] = true; } /* find the id of the starting edge */ unsigned long set_size = equiv_set.size(); unsigned long e_id = (set_size == 0) ? n_edges : equiv_set.head().id; for (unsigned long n = 0; n < set_size; n++) { const contour_edge& e = equiv_set.remove_head(); if (!(has_prev[e.vertex_start->id])) e_id = e.id; } /* reconstruct equivalence class in sorted order */ for (unsigned long n = 0; n < set_size; n++) { contour_edge& e = (*_edges)[e_id]; equiv_set.add(e); e_id = next_edge[e.vertex_end->id]; } /* reset vertex previous edge indicators */ for (list<contour_edge>::iterator_t i(equiv_set); i.has_next(); ) { const contour_edge& e = i.next(); has_prev[e.vertex_end->id] = false; } } } /*************************************************************************** * Contour vertex and edge access. ***************************************************************************/ /* * Get image size in the x-dimension. */ unsigned long lib_image::contour_set::size_x() const { return _assignments.size(0); } /* * Get image size in the y-dimension. */ unsigned long lib_image::contour_set::size_y() const { return _assignments.size(1); } /* * Get number of vertices in the contour set. */ unsigned long lib_image::contour_set::vertices_size() const { return _vertices->size(); } /* * Get number of edges in the contour set. */ unsigned long lib_image::contour_set::edges_size() const { return _edges->size(); } /* * Get the number of edge equivalence classes. * Each equivalence class represents a contour before subdivision. */ unsigned long lib_image::contour_set::edges_equiv_size() const { return _edges_equiv->size(); } /* * Return the specified vertex (by reference). */ const lib_image::contour_vertex& lib_image::contour_set::vertex( unsigned long v_id) const { if (v_id >= _vertices->size()) throw ex_index_out_of_bounds("invalid contour vertex id", v_id); return (*_vertices)[v_id]; } /* * Return the specified edge (by reference). */ const lib_image::contour_edge& lib_image::contour_set::edge( unsigned long e_id) const { if (e_id >= _edges->size()) throw ex_index_out_of_bounds("invalid contour edge id", e_id); return (*_edges)[e_id]; } /* * Return the specified edge equivalence class (by reference). * * The edges are listed in the order encountered on a traversal of the * original contour before subdivision. */ const list<lib_image::contour_edge>& lib_image::contour_set::edge_equiv( unsigned long equiv_id) const { if (equiv_id >= _edges_equiv->size()) throw ex_index_out_of_bounds("invalid contour equivalence id", equiv_id); return (*_edges_equiv)[equiv_id]; } /* * Check if the specified pixel is a vertex. */ bool lib_image::contour_set::is_vertex(unsigned long n) const { return _is_vertex[n]; } /* * Check if the specified pixel is a vertex. */ bool lib_image::contour_set::is_vertex(unsigned long x, unsigned long y) const { return _is_vertex(x,y); } /* * Check if the specified pixel lies on a (non-completion) edge interior. */ bool lib_image::contour_set::is_edge(unsigned long n) const { return _is_edge[n]; } /* * Check if the specified pixel lies on a (non-completion) edge interior. */ bool lib_image::contour_set::is_edge(unsigned long x, unsigned long y) const { return _is_edge(x,y); } /* * Return the id of the vertex at the given pixel. * Throw an exception (ex_not_found) if no such vertex exists. */ unsigned long lib_image::contour_set::vertex_id(unsigned long n) const { if (!(_is_vertex[n])) throw ex_not_found("vertex not found at specified pixel location"); return _assignments[n]; } /* * Return the id of the vertex at the given pixel. * Throw an exception (ex_not_found) if no such vertex exists. */ unsigned long lib_image::contour_set::vertex_id( unsigned long x, unsigned long y) const { if (!(_is_vertex(x,y))) throw ex_not_found("vertex not found at specified pixel location"); return _assignments(x,y); } /* * Return the id of the (non-completion) edge whos interior contains the * given pixel. Throw an exception (ex_not_found) if no such edge exists. */ unsigned long lib_image::contour_set::edge_id(unsigned long n) const { if (!(_is_edge[n])) throw ex_not_found("edge not found at specified pixel location"); return _assignments[n]; } /* * Return the id of the (non-completion) edge whos interior contains the * given pixel. Throw an exception (ex_not_found) if no such edge exists. */ unsigned long lib_image::contour_set::edge_id( unsigned long x, unsigned long y) const { if (!(_is_edge(x,y))) throw ex_not_found("edge not found at specified pixel location"); return _assignments(x,y); } /*************************************************************************** * Contour subdivision. ***************************************************************************/ /* * Recursively subdivide the contours until they are approximately linear * using the following local criteria: * * (1) Break a contour if the angle formed by the ray from one contour * endpoint to the other and the ray from that endpoint to another * point on the contour exceeds the maximum deviation angle. * * (2) Break a contour if the distance from any point on it to the line * segment connecting its endpoints both exceeds some fraction of the * length of this segment and is greater than the tolerance distance. * * A contour is always subdivided at the point that is maximally distant * from the line segment between its endpoints, regardless of whether * criterion (1) or (2) triggered the subdivision. */ void lib_image::contour_set::subdivide_local( bool enforce_angle, double max_angle, bool enforce_dist, double max_dist_dev, double tol_dist) { /* intialize queue of edges to check */ list<contour_edge> q(*_edges); /* repeatedly dequeue and process edges */ while (!(q.is_empty())) { /* dequeue edge */ contour_edge& e = q.remove_head(); /* get endpoints of line segment approximation */ point_2D p_start = e.vertex_start->point(); point_2D p_end = e.vertex_end->point(); /* compute distance threshold */ point_2D r_start_end = p_end - p_start; double len_start_end = abs(r_start_end); double max_dist = max_dist_dev * len_start_end; /* initialize split position and distance */ unsigned long split_pos = 0; double split_dist = 0; /* determine whether edge should be split */ bool split = false; unsigned long n_points = e.size(); for (unsigned long n = 0; n < n_points; n++) { /* get current point along contour */ point_2D p = e.point(n); /* compute distance from point to segment */ double dist = p.distance_to_segment(p_start, p_end); /* update optimal split position */ if (dist > split_dist) { split_pos = n; split_dist = dist; } /* check distance constraint */ if ((!split) && (enforce_dist)) split = ((dist > max_dist) && (dist > tol_dist)); /* check angle constraint */ if ((!split) && (enforce_angle)) { /* compute angle between point and segment */ point_2D r_start_p = p - p_start; point_2D r_end_p = p - p_end; double angle_start = math::acos( dot(r_start_p, r_start_end) / (abs(r_start_p) * len_start_end) ); double angle_end = math::acos( dot(r_end_p, -r_start_end) / (abs(r_end_p) * len_start_end) ); double angle = (angle_start > angle_end) ? angle_start : angle_end; /* update split flag */ split = (angle > max_angle); } } /* split edge if it violates constraints */ if (split) { /* split edge */ this->split_edge(e.id, split_pos); /* enqueue split edges */ q.add(e); q.add(_edges->tail()); } } /* order edges in equivalence classes by traversal of original contour */ this->sort_edges_equiv(); } namespace { /* * Find and return the position of the point on the contour closest to the * line passing through the specified points. * * Throw an exception if the contour has no interior points. */ unsigned long find_contour_point_closest_to_line( const lib_image::contour_edge& e, const point_2D& p, const point_2D& q) { /* check that contour is nonempty */ unsigned long n_points = e.size(); if (n_points == 0) throw ex_invalid_argument("contour has no interior points"); /* initialize position and minimum distance */ unsigned long pos = 0; double min_dist = e.point(pos).distance_to_line(p, q); /* find closest point */ for (unsigned long n = 1; n < n_points; n++) { double dist = e.point(n).distance_to_line(p, q); if (dist < min_dist) { pos = n; min_dist = dist; } } return pos; } /* * Find and return the position of the point on the contour closest to the * line segment passing through the specified points. * * Throw an exception if the contour has no interior points. */ unsigned long find_contour_point_closest_to_segment( const lib_image::contour_edge& e, const point_2D& p, const point_2D& q) { /* check that contour is nonempty */ unsigned long n_points = e.size(); if (n_points == 0) throw ex_invalid_argument("contour has no interior points"); /* initialize position and minimum distance */ unsigned long pos = 0; double min_dist = e.point(pos).distance_to_segment(p, q); /* find closest point */ for (unsigned long n = 1; n < n_points; n++) { double dist = e.point(n).distance_to_segment(p, q); if (dist < min_dist) { pos = n; min_dist = dist; } } return pos; } /* * Find and return the position of the point on the contour farthest from the * line passing through the specified points. * * Throw an exception if the contour has no interior points. */ unsigned long find_contour_point_farthest_from_line( const lib_image::contour_edge& e, const point_2D& p, const point_2D& q) { /* check that contour is nonempty */ unsigned long n_points = e.size(); if (n_points == 0) throw ex_invalid_argument("contour has no interior points"); /* initialize position and maximum distance */ unsigned long pos = 0; double max_dist = 0; /* find closest point */ for (unsigned long n = 0; n < n_points; n++) { double dist = e.point(n).distance_to_line(p, q); if (dist > max_dist) { pos = n; max_dist = dist; } } return pos; } /* * Find and return the position of the point on the contour farthest from the * line segment passing through the specified points. * * Throw an exception if the contour has no interior points. */ unsigned long find_contour_point_farthest_from_segment( const lib_image::contour_edge& e, const point_2D& p, const point_2D& q) { /* check that contour is nonempty */ unsigned long n_points = e.size(); if (n_points == 0) throw ex_invalid_argument("contour has no interior points"); /* initialize position and maximum distance */ unsigned long pos = 0; double max_dist = 0; /* find closest point */ for (unsigned long n = 0; n < n_points; n++) { double dist = e.point(n).distance_to_segment(p, q); if (dist > max_dist) { pos = n; max_dist = dist; } } return pos; } } /* namespace */ /* * Recursively subdivide the contours until their straight line segment * approximation respects the true contour topology. * * Enforce the global criteria that the line segments between contour * endpoints intersect only at contour vertices. */ void lib_image::contour_set::subdivide_global() { /* create comparison functor for sorting edges by vertex id */ class edge_compare : public comparable_functor<contour_edge> { public: int operator()(const contour_edge& e0, const contour_edge& e1) const { bool v0_cmp = (e0.vertex_start->id < e0.vertex_end->id); bool v1_cmp = (e1.vertex_start->id < e1.vertex_end->id); unsigned long min0 = v0_cmp ? e0.vertex_start->id : e0.vertex_end->id; unsigned long max0 = v0_cmp ? e0.vertex_end->id : e0.vertex_start->id; unsigned long min1 = v1_cmp ? e1.vertex_start->id : e1.vertex_end->id; unsigned long max1 = v1_cmp ? e1.vertex_end->id : e1.vertex_start->id; int cmp_min = (min0 < min1) ? -1 : ((min0 > min1) ? 1 : 0); int cmp_max = (max0 < max1) ? -1 : ((max0 > max1) ? 1 : 0); return ((cmp_min == 0) ? cmp_max : cmp_min); } }; static const edge_compare e_compare; /* subdivide edges which share both vertices */ { /* sort edges by vertex ids */ array_list<contour_edge> edges_sorted(*_edges); edges_sorted.sort(e_compare); /* find edges sharing both vertices */ unsigned long n_edges = edges_sorted.size(); unsigned long prev = 0; for (unsigned long curr = 1; curr < n_edges; curr++) { /* get edges with possibly identical vertices */ contour_edge& e_prev = edges_sorted[prev]; contour_edge& e_curr = edges_sorted[curr]; /* check if edges overlap at both vertices */ if (e_compare(e_prev, e_curr) == 0) { /* get common endpoints */ point_2D p = e_prev.vertex_start->point(); point_2D q = e_prev.vertex_end->point(); /* determine which edge to split */ bool can_split_prev = (e_prev.size() > 0); bool can_split_curr = (e_curr.size() > 0); bool split_prev = false; if (can_split_prev && can_split_curr) { /* compute split position along each edge */ unsigned long pos_prev = find_contour_point_farthest_from_segment(e_prev, p, q); unsigned long pos_curr = find_contour_point_farthest_from_segment(e_curr, p, q); /* compute distance from split point to line segment */ double dist_prev = e_prev.point(pos_prev).distance_to_segment(p, q); double dist_curr = e_curr.point(pos_curr).distance_to_segment(p, q); /* select the least straight edge */ split_prev = (dist_prev > dist_curr); } else if (can_split_prev) { /* set previous edge to be split */ split_prev = true; } else if (!can_split_curr) { /* neither edge can be split - cannot make topology consistent */ throw ex_invalid_argument( "cannot subdivide indentical edges to be nonoverlapping" ); } /* split edge */ contour_edge* e = (split_prev) ? (&e_prev) : (&e_curr); unsigned long split_pos = find_contour_point_farthest_from_segment(*e, p, q); this->split_edge(e->id, split_pos); /* update index of previous edge */ if (split_prev) { prev = curr; } } else { /* update index of previous edge */ prev = curr; } } } /* repeatedly subdivide intersecting edges until topology is consistent */ while (true) { /* create points corresponding to vertices */ auto_collection< point_2D, array_list<point_2D> > points( new array_list<point_2D>() ); unsigned long n_vertices = _vertices->size(); for (unsigned long n = 0; n < n_vertices; n++) { const contour_vertex& v = (*_vertices)[n]; auto_ptr<point_2D> p( new point_2D(static_cast<double>(v.x), static_cast<double>(v.y)) ); points->add(*p); p.release(); } /* create segments corresponding to edges */ unsigned long n_edges = _edges->size(); array<unsigned long> segment_start_ids(n_edges); array<unsigned long> segment_end_ids(n_edges); for (unsigned long n = 0; n < n_edges; n++) { const contour_edge& e = (*_edges)[n]; segment_start_ids[n] = e.vertex_start->id; segment_end_ids[n] = e.vertex_end->id; } /* compute segment intersections */ seg_intersect seg_int(*points, segment_start_ids, segment_end_ids); /* initialize edge modification flags */ array<bool> do_split(n_edges, false); bool found_intersection = false; /* mark edges which must be split */ unsigned long n_v = seg_int.vertices_size(); for (unsigned long n = 0; n < n_v; n++) { /* skip endpoint only intersections */ if (!(seg_int.is_interior_intersection(n))) continue; found_intersection = true; /* get segments whos interiors/endpoints pass through intersection */ array<unsigned long> interior_ids = seg_int.interior_intersection(n); array<unsigned long> endpoint_ids = seg_int.endpoint_intersection(n); /* check intersection type */ if (endpoint_ids.is_empty()) { /* intersection of edge interiors only - mark all but one edge */ const contour_edge* ea = &((*_edges)[interior_ids[0]]); unsigned long n_interior = interior_ids.size(); for (unsigned long ne = 1; ne < n_interior; ne++) { const contour_edge* eb = &((*_edges)[interior_ids[ne]]); /* check if contours can be split */ if (ea->size() == 0) { /* only eb can be split */ do_split[eb->id] = true; continue; } else if (eb->size() == 0) { /* only ea can be split */ do_split[ea->id] = true; ea = eb; continue; } /* get contour endpoints */ point_2D pa = ea->vertex_start->point(); point_2D qa = ea->vertex_end->point(); point_2D pb = eb->vertex_start->point(); point_2D qb = eb->vertex_end->point(); /* compute distance from contour ea to segment defined by eb */ unsigned long pos_a = find_contour_point_closest_to_segment(*ea, pb, qb); double dist_a = ea->point(pos_a).distance_to_segment(pb, qb); /* compute distance from contour eb to segment defined by ea */ unsigned long pos_b = find_contour_point_closest_to_segment(*eb, pa, qa); double dist_b = eb->point(pos_b).distance_to_segment(pa, qa); /* compare distances */ if (dist_a < dist_b) { /* contour ea intersects segment eb - split contour eb */ do_split[eb->id] = true; } else { /* contour eb intersects segment ea - split contour ea */ do_split[ea->id] = true; ea = eb; } } } else { /* mark all edges with interiors passing through intersection */ unsigned long n_interior = interior_ids.size(); for (unsigned long ne = 0; ne < n_interior; ne++) do_split[interior_ids[ne]] = true; } } /* check if finished (no interior intersections) */ if (!found_intersection) break; /* split marked edges */ for (unsigned long n = 0; n < n_edges; n++) { if (do_split[n]) { /* get edge, check that it can be split */ contour_edge& e = (*_edges)[n]; if (e.size() == 0) { throw ex_invalid_argument( "cannot subdivide edges to make topology consistent" ); } /* split edge */ point_2D p = e.vertex_start->point(); point_2D q = e.vertex_end->point(); unsigned long split_pos = find_contour_point_farthest_from_segment(e, p, q); this->split_edge(e.id, split_pos); } } } /* order edges in equivalence classes by traversal of original contour */ this->sort_edges_equiv(); } /*************************************************************************** * Contour completion. ***************************************************************************/ /* * Add the four bounding corners of the image to the set of contour * vertices if they neither currently exist in the vertex set nor lie * on an existing contour. */ void lib_image::contour_set::add_bounding_vertices() { /* get image dimensions */ unsigned long size_x = _assignments.size(0); unsigned long size_y = _assignments.size(1); /* check image dimensions */ if ((size_x == 0) || (size_y == 0)) return; /* assemble corner vertex coordinates */ unsigned long xs[] = { 0, 0, (size_x-1), (size_x-1) }; unsigned long ys[] = { 0, (size_y-1), 0, (size_y-1) }; /* check if corner vertices are covered */ for (unsigned long n = 0; n < 4; n++) { unsigned long x = xs[n]; unsigned long y = ys[n]; if (!(_is_vertex(x,y) || _is_edge(x,y))) { /* vertex doesn't exist - create it */ auto_ptr<contour_vertex> v = create_contour_vertex(x, y); v->id = _vertices->size(); /* record vertex assignment */ _assignments(x,y) = v->id; /* add vertex to vertex set */ _vertices->add(*v); v.release(); /* mark vertex */ _is_vertex(x,y) = true; } } } /* * Completion edges from constrained Delaunay triangulation (CDT). * * Compute the CDT of the straight line segment approximation of the * contour edges. Update the contour set to include all new edges * appearing in the CDT as completion edges. * * Optionally, return the CDT vertices (points which correspond to * the contour vertices), and the CDT data structure itself (which * references the CDT vertices). * * Note that the line segment approximation must respect the true * contour topology in order to guarantee the existence of the CDT. * The subdivide_global() method enforces this property and should * be called prior to computing the CDT. */ void lib_image::contour_set::completion_cdt() { auto_collection< point_2D, array_list<point_2D> > cdt_vertices; auto_ptr<triangulation> cdt; this->completion_cdt(cdt_vertices, cdt); } void lib_image::contour_set::completion_cdt( auto_collection< point_2D, array_list<point_2D> >& cdt_vertices, auto_ptr<triangulation>& cdt) { /* create points corresponding to contour vertices */ auto_collection< point_2D, array_list<point_2D> > points( new array_list<point_2D>() ); unsigned long n_vertices = _vertices->size(); for (unsigned long n = 0; n < n_vertices; n++) { const contour_vertex& v = (*_vertices)[n]; auto_ptr<point_2D> p( new point_2D(static_cast<double>(v.x), static_cast<double>(v.y)) ); points->add(*p); p.release(); } /* create constraints corresponding to contour edges */ unsigned long n_edges = _edges->size(); array<unsigned long> constraint_start_ids(n_edges); array<unsigned long> constraint_end_ids(n_edges); for (unsigned long n = 0; n < n_edges; n++) { const contour_edge& e = (*_edges)[n]; constraint_start_ids[n] = e.vertex_start->id; constraint_end_ids[n] = e.vertex_end->id; } /* compute cdt */ auto_ptr<triangulation> t = triangulation::delaunay( *points, constraint_start_ids, constraint_end_ids ); /* create contour edges for cdt completion edges */ unsigned long n_edges_cdt = t->edges_size(); for (unsigned long n = n_edges; n < n_edges_cdt; n++) { /* create edge and set its identity */ auto_ptr<contour_edge> e = create_contour_edge( (*_vertices)[t->edge_vertex_id(n,0)], (*_vertices)[t->edge_vertex_id(n,1)] ); e->id = n; e->contour_equiv_id = _edges_equiv->size(); e->is_completion = true; /* compute coordinates of points along edge */ const point_2D& p_start = t->vertex(e->vertex_start->id); const point_2D& p_end = t->vertex(e->vertex_end->id); unsigned long size_y = this->size_y(); auto_ptr< array<unsigned long> > inds = scan_line_segment( p_start, p_end, size_y, true ); unsigned long n_inds = inds->size(); unsigned long n_coords = (n_inds > 2) ? (n_inds - 2) : 0; e->x_coords.resize(n_coords); e->y_coords.resize(n_coords); for (unsigned long n = 0; n < n_coords; n++) { unsigned long ind = (*inds)[n+1]; e->x_coords[n] = ind / size_y; e->y_coords[n] = ind % size_y; } /* create edge equivalence class */ auto_ptr< list<contour_edge> > e_equiv(new list<contour_edge>()); e_equiv->add(*e); /* add edge */ _edges->add(*e); e.release(); _edges_equiv->add(*e_equiv); e_equiv.release(); } /* return cdt */ cdt_vertices = points; cdt = t; } /*************************************************************************** * Contour traversal state machine. ***************************************************************************/ namespace { /* * A contour traversal is a directed traversal of the boundary of the pixels * lying on the contour. The direction of traversal specifies whether the * left or right side (as viewed when moving from the start vertex to the end * vertex) of the contour is traced out. * * At each step of the traversal, the current state is defined by the position * along the contour (a pixel), and an oriented boundary of that pixel. Each * pixel has eight oriented boundaries, as shown below in Figure 1. * * Successive pixels along the contour must be neighbors in a 3x3 grid, and the * state machine makes use of the labeling of these neighbors shown in Figure 2. * * 0 4 * --+ +-- * 3 + | 1 5 | + 7 * | + + | * +-- --+ * 2 6 * * clockwise states counterclockwise states * * Figure 1: Labeling of states representing the directed boundary of a pixel. * * * 2 5 8 * ^ * | 1 * 7 * y * 0 3 6 * * x --> * * Figure 2: Labeling of neighbors offset from the center pixel (*). */ /* * Given the coordinates of two adjacent contour points, compute the label * describing the relative position of the second with respect to the first. * The labeling scheme is shown above in Figure 2. */ unsigned long contour_traversal_compute_offset( unsigned long x, unsigned long y, unsigned long x_next, unsigned long y_next) { unsigned long x_offset = 1 + x_next - x; unsigned long y_offset = 1 + y_next - y; return (x_offset*3 + y_offset); } /* * Compute the label of the next element along the contour given the index * of the current element. If the current element is the last point on the * contour, compute the offset of the end vertex. */ unsigned long contour_traversal_compute_offset( const lib_image::contour_edge& e, /* contour edge */ unsigned long ind) /* current position */ { unsigned long n_coords = e.size(); unsigned long ind_next = ind + 1; if (ind_next < n_coords) { return contour_traversal_compute_offset( e.x_coords[ind], e.y_coords[ind], e.x_coords[ind_next], e.y_coords[ind_next] ); } else { return contour_traversal_compute_offset( e.x_coords[ind], e.y_coords[ind], e.vertex_end->x, e.vertex_end->y ); } } /* * Return the initial state for traversal of the left side of the contour. */ int contour_traversal_init_state_left(unsigned long offset) { static const int init_state_map[] = { 3, 0, 0, 3, -1, 1, 2, 2, 1 }; return init_state_map[offset]; } /* * Return the initial state for traversal of the left side of the contour. */ int contour_traversal_init_state_left(const lib_image::contour_edge& e) { return contour_traversal_init_state_left( contour_traversal_compute_offset( e.x_coords[0], e.y_coords[0], e.vertex_start->x, e.vertex_start->y ) ); } /* * Return the initial state for traversal of the right side of the contour. */ int contour_traversal_init_state_right(unsigned long offset) { static const int init_state_map[] = { 6, 6, 5, 7, -1, 5, 7, 4, 4 }; return init_state_map[offset]; } /* * Return the initial state for traversal of the right side of the contour. */ int contour_traversal_init_state_right(const lib_image::contour_edge& e) { return contour_traversal_init_state_right( contour_traversal_compute_offset( e.x_coords[0], e.y_coords[0], e.vertex_start->x, e.vertex_start->y ) ); } /* * Move to the next boundary element in a contour traversal. */ void contour_traversal_update_state( unsigned long& ind, /* current position */ int& state, /* current state */ unsigned long offset) /* offset of next element */ { /* contour traversal state machine */ static const int state_rotate[] = { 1, 2, 3, 0, 5, 6, 7, 4 }; static const int state_lift[] = { 3, 0, 1, 2, 7, 4, 5, 6 }; /* offset indices which correspond to state changes */ static const unsigned long offset_continue[] = { 7, 3, 1, 5, 1, 3, 7, 5 }; static const unsigned long offset_lift_head[] = { 8, 6, 0, 2, 2, 0, 6, 8 }; static const unsigned long offset_lift_tail[] = { 5, 7, 3, 1, 5, 1, 3, 7 }; /* update state */ if (offset == 4) { /* contour contains duplicate pixels */ ind++; } else if (offset_continue[state] == offset) { /* next pixel on contour is aligned with current */ ind++; } else if ((offset_lift_head[state] == offset) || (offset_lift_tail[state] == offset)) { /* move to next boundary pixel and update boundary direction */ ind++; state = state_lift[state]; } else { /* rotate around boundary of current pixel */ state = state_rotate[state]; } } } /* namespace */ /*************************************************************************** * Region extraction (2D). ***************************************************************************/ namespace { /* * Scan rays in the direction of the normal from each point along a traversal * of the edge. The returned rays sweep out a region of the specified width. */ auto_collection< array<unsigned long> > extract_edge_side( const lib_image::contour_edge& e, /* contour edge */ bool side, /* false = left, true = right */ double width, /* region width */ unsigned long size_x, /* grid size in x-direction */ unsigned long size_y) /* grid size in y-direction */ { /* allocate collection of rays scanned from the edge */ auto_collection< array<unsigned long> > rays( new list< array<unsigned long> >() ); /* check that contour is nonempty */ unsigned long n_points = e.size(); if (n_points > 0) { /* compute angle of normal to contour side */ point_2D p_start = e.vertex_start->point(); point_2D p_end = e.vertex_end->point(); double theta = arg(p_end - p_start) + M_PI_2l; if (side) { theta += M_PIl; } /* compute angular change for moving ~1/8 of a grid cell along boundary */ double delta = 0.125 * (2*M_PIl) / (math::ceil(2*M_PIl*width)+1); /* compute rays bounding a thin cone in the direction to scan */ point_2D p_ray_prev( width * math::cos(theta - delta), width * math::sin(theta - delta) ); point_2D p_ray_next( width * math::cos(theta + delta), width * math::sin(theta + delta) ); /* initialize traversal state */ int state = side ? contour_traversal_init_state_right(e) : contour_traversal_init_state_left(e); /* traverse edge */ unsigned long ind = 0; while ((ind < n_points) && (state != -1)) { /* get current point on edge */ point_2D p = e.point(ind); /* move to adjacent point on correct side of boundary */ if ((state == 0) || (state == 4)) { (p.y())++; } else if ((state == 1) || (state == 7)) { (p.x())++; } else if ((state == 2) || (state == 6)) { (p.y())--; } else /* ((state == 3) || (state == 5)) */ { (p.x())--; } /* check that point lies within grid */ if (is_in_grid(p, size_x, size_y)) { /* compute segment end points */ point_2D q_prev = p + p_ray_prev; point_2D q_next = p + p_ray_next; clip_line_segment_to_grid(p, q_prev, size_x, size_y); clip_line_segment_to_grid(p, q_next, size_x, size_y); /* scan segments */ auto_ptr< array<unsigned long> > ray_prev = scan_line_segment( p, q_prev, size_y, false ); auto_ptr< array<unsigned long> > ray_next = scan_line_segment( p, q_next, size_y, false ); /* store scanned rays */ rays->add(*ray_prev); ray_prev.release(); rays->add(*ray_next); ray_next.release(); } /* update traversal state */ unsigned long offset = contour_traversal_compute_offset(e, ind); contour_traversal_update_state(ind, state, offset); } } return rays; } /* * Scan rays in a full disc at the given subdivision vertex along a contour. */ auto_collection< array<unsigned long> > extract_vertex_side( const lib_image::contour_vertex& v, /* subdivision vertex */ unsigned long x_prev, unsigned long y_prev, /* previous point on contour */ unsigned long x_next, unsigned long y_next, /* next point on contour */ bool side, /* false = left, true = right */ double width, /* region width */ unsigned long size_x, /* grid size in x-direction */ unsigned long size_y) /* grid size in y-direction */ { /* allocate collection of rays scanned from the vertex */ auto_collection< array<unsigned long> > rays( new list< array<unsigned long> >() ); /* compute offsets of previous/next contour points */ unsigned long offset_prev = contour_traversal_compute_offset( v.x, v.y, x_prev, y_prev ); unsigned long offset_next = contour_traversal_compute_offset( v.x, v.y, x_next, y_next ); /* initialize traversal state along boundary of vertex */ int state = side ? contour_traversal_init_state_right(offset_prev) : contour_traversal_init_state_left(offset_prev); /* traverse vertex boundary */ unsigned long ind = 0; while ((ind == 0) && (state != -1)) { /* get point corresponding to vertex */ point_2D p = v.point(); /* move to adjacent point on correct side of boundary */ if ((state == 0) || (state == 4)) { (p.y())++; } else if ((state == 1) || (state == 7)) { (p.x())++; } else if ((state == 2) || (state == 6)) { (p.y())--; } else /* ((state == 3) || (state == 5)) */ { (p.x())--; } /* check that point lies within grid */ if (is_in_grid(p, size_x, size_y)) { /* scan disc */ auto_collection< array<unsigned long> > disc_rays = scan_disc( p, width, size_x, size_y ); rays->add(*disc_rays); delete (disc_rays.release()); } /* update traversal state */ contour_traversal_update_state(ind, state, offset_next); } return rays; } /* * Given a collection of scanned rays (each containing indices of grid elements * that lie on a line segment), extract the visible region. Traversing each ray * until it is blocked by one of the following conditions carves out the visible * region. A ray is blocked at the first point it hits which (1) has the * specified id or (2) has visibility greater than the specified visibility. */ void extract_visible_region( const collection< array<unsigned long> >& rays, /* scanned rays */ unsigned long id, /* current id */ const matrix<unsigned long>& id_map, /* id map */ double vis, /* current vis */ const matrix<>& visibility, /* visibility map */ array<unsigned long>& region) /* returned region */ { /* traverse rays, computing where they are blocked */ unsigned long n_rays = rays.size(); array<unsigned long> ray_len(n_rays); unsigned long total_len = 0; { auto_ptr< iterator< array<unsigned long> > > i = rays.iter_create(); for (unsigned long n = 0; n < n_rays; n++) { /* get ray */ const array<unsigned long>& ray = i->next(); unsigned long len = ray.size(); /* traverse ray */ for (unsigned long pos = 0; pos < len; pos++) { unsigned long ind = ray[pos]; if ((id_map[ind] == id) || (visibility[ind] > vis)) len = pos; } ray_len[n] = len; total_len += len; } } /* assemble region */ region.resize(total_len); { unsigned long r_pos = 0; auto_ptr< iterator< array<unsigned long> > > i = rays.iter_create(); for (unsigned long n = 0; n < n_rays; n++) { /* get ray */ const array<unsigned long>& ray = i->next(); unsigned long len = ray_len[n]; /* add visible portion to region */ for (unsigned long pos = 0; pos < len; pos++) region[r_pos++] = ray[pos]; } } /* compute unique region membership */ region.unique(); } /* * Edge region extractor. */ class edge_region_extractor : public runnable { public: /* * Constructor. */ explicit edge_region_extractor( const lib_image::contour_edge& e, /* contour edge */ double width, /* region width */ const matrix<unsigned long>& id_map, /* id map */ double vis, /* edge visibility */ const matrix<>& visibility, /* visibility map */ array<unsigned long>& region_left, /* returned left region */ array<unsigned long>& region_right) /* returned right region */ : _e(e), _width(width), _id_map(id_map), _vis(vis), _visibility(visibility), _region_left(region_left), _region_right(region_right) { } /* * Destructor. */ virtual ~edge_region_extractor() { /* do nothing */ } /* * Extract regions on both sides of the edge. */ virtual void run() { /* scan each side of the edge */ unsigned long size_x = _id_map.size(0); unsigned long size_y = _id_map.size(1); auto_collection< array<unsigned long> > rays_left = extract_edge_side( _e, false, _width, size_x, size_y ); auto_collection< array<unsigned long> > rays_right = extract_edge_side( _e, true, _width, size_x, size_y ); /* extract visible regions */ unsigned long id = _e.contour_equiv_id; extract_visible_region( *rays_left, id, _id_map, _vis, _visibility, _region_left ); extract_visible_region( *rays_right, id, _id_map, _vis, _visibility, _region_right ); } protected: const lib_image::contour_edge& _e; /* contour edge */ double _width; /* region width */ const matrix<unsigned long>& _id_map; /* id map */ double _vis; /* edge visibility */ const matrix<>& _visibility; /* visibility map */ array<unsigned long>& _region_left; /* returned left region */ array<unsigned long>& _region_right; /* returned right region */ }; /* * Vertex region extractor. */ class vertex_region_extractor : public runnable { public: /* * Constructor. */ explicit vertex_region_extractor( const lib_image::contour_vertex& v, /* contour vertex */ const lib_image::contour_edge& e_prev, /* previous edge */ const lib_image::contour_edge& e_next, /* next edge */ double width, /* region width */ const matrix<unsigned long>& id_map, /* id map */ double vis, /* edge visibility */ const matrix<>& visibility, /* visibility map */ array<unsigned long>& region_left, /* returned left region */ array<unsigned long>& region_right) /* returned right region */ : _v(v), _e_prev(e_prev), _e_next(e_next), _width(width), _id_map(id_map), _vis(vis), _visibility(visibility), _region_left(region_left), _region_right(region_right) { } /* * Destructor. */ virtual ~vertex_region_extractor() { /* do nothing */ } /* * Extract regions on both sides of the subdivision vertex. */ virtual void run() { /* get previous/next vertices */ const lib_image::contour_vertex* v_prev = _e_prev.vertex_start; const lib_image::contour_vertex* v_next = _e_next.vertex_end; /* compute coordinates of previous point on contour */ unsigned long n_points_prev = _e_prev.size(); bool use_e_prev = (n_points_prev > 0); unsigned long x_prev = use_e_prev ? _e_prev.x_coords[n_points_prev-1] : v_prev->x; unsigned long y_prev = use_e_prev ? _e_prev.y_coords[n_points_prev-1] : v_prev->y; /* compute coordinates of next point on contour */ unsigned long n_points_next = _e_next.size(); bool use_e_next = (n_points_next > 0); unsigned long x_next = use_e_next ? _e_next.x_coords[0] : v_next->x; unsigned long y_next = use_e_next ? _e_next.y_coords[0] : v_next->y; /* scan each side of the vertex */ unsigned long size_x = _id_map.size(0); unsigned long size_y = _id_map.size(1); auto_collection< array<unsigned long> > rays_left = extract_vertex_side( _v, x_prev, y_prev, x_next, y_next, false, _width, size_x, size_y ); auto_collection< array<unsigned long> > rays_right = extract_vertex_side( _v, x_prev, y_prev, x_next, y_next, true, _width, size_x, size_y ); /* extract visible regions */ unsigned long id = _e_prev.contour_equiv_id; extract_visible_region( *rays_left, id, _id_map, _vis, _visibility, _region_left ); extract_visible_region( *rays_right, id, _id_map, _vis, _visibility, _region_right ); } protected: const lib_image::contour_vertex& _v; /* contour vertex */ const lib_image::contour_edge& _e_prev; /* previous edge */ const lib_image::contour_edge& _e_next; /* next edge */ double _width; /* region width */ const matrix<unsigned long>& _id_map; /* id map */ double _vis; /* edge visibility */ const matrix<>& _visibility; /* visibility map */ array<unsigned long>& _region_left; /* returned left region */ array<unsigned long>& _region_right; /* returned right region */ }; /* * Region combiner. */ class region_combiner : public runnable { public: /* * Constructor. */ explicit region_combiner( const list<lib_image::contour_edge>& equiv_set, /* contour equiv set */ const array< array<unsigned long> >& v_regions, /* vertex regions */ const array< array<unsigned long> >& e_regions, /* edge regions */ array<unsigned long>& region) /* combined region */ : _equiv_set(equiv_set), _v_regions(v_regions), _e_regions(e_regions), _region(region) { } /* * Destructor. */ virtual ~region_combiner() { /* do nothing */ } /* * Combine regions associated with a subdivided contour to produce the * region associated with the original contour before subdivision. */ virtual void run() { /* compute total size of region */ unsigned long r_size = 0; for (list<lib_image::contour_edge>::iterator_t i(_equiv_set); i.has_next(); ) { const lib_image::contour_edge& e = i.next(); r_size += _e_regions[e.id].size(); if (i.has_next()) r_size += _v_regions[e.vertex_end->id].size(); } /* resize region */ _region.resize(r_size); /* copy membership of component regions */ unsigned long r_pos = 0; for (list<lib_image::contour_edge>::iterator_t i(_equiv_set); i.has_next(); ) { const lib_image::contour_edge& e = i.next(); const array<unsigned long>& e_region = _e_regions[e.id]; for (unsigned long n = 0, size = e_region.size(); n < size; n++) _region[r_pos++] = e_region[n]; if (i.has_next()) { const array<unsigned long>& v_region = _v_regions[e.vertex_end->id]; for (unsigned long n = 0, size = v_region.size(); n < size; n++) _region[r_pos++] = v_region[n]; } } /* compute unique region membership */ _region.unique(); } protected: const list<lib_image::contour_edge>& _equiv_set; /* contour equiv set */ const array< array<unsigned long> >& _v_regions; /* vertex regions */ const array< array<unsigned long> >& _e_regions; /* edge regions */ array<unsigned long>& _region; /* combined region */ }; } /* namespace */ /* * Extract the regions lying on the left and right sides of each of the * given contours. * * The width of both the left and right regions is determined as the * specified fraction of the length of the corresponding contour edge, * with a minimum width used for short edges. In this manner, region * size scales with contour length. */ lib_image::region_set::region_set( const contour_set& contours, double width, double width_min) { /* set all visibilities to zero (so no boundaries are seen) */ array<double> edge_vis(contours.edges_size()); matrix<> visibility(contours.size_x(), contours.size_y()); /* extract regions */ this->extract_regions(contours, width, width_min, edge_vis, visibility); } /* * Extract regions bounded by intervening contours. * * When computing region membership, take into account boundaries implied * by other non-completion contours in the following manner. Denote the * specified relative scale sensitivity by s. The region surrounding * contour C extends to the given width except where it is blocked by * a non-completion contour C' such that: * * L(C') > s * L(C) * * where L(*) denotes contour length. * * In other words, a contour sees all boundaries implied by other contours * whose length is greater than s times larger than its own length. * * Setting s = 0 means each contour sees all other contours. Setting s * to infinity is equivalent to the above version of region extraction, * in which each contour ignores all others. */ lib_image::region_set::region_set( const contour_set& contours, double width, double width_min, double scale) { /* compute length of each original contour (equivalence class) */ array<double> edge_equiv_len(contours.edges_equiv_size()); unsigned long n_edges = contours.edges_size(); for (unsigned long e_id = 0; e_id < n_edges; e_id++) { const contour_edge& e = (*(contours._edges))[e_id]; edge_equiv_len[e.contour_equiv_id] += e.length(); } /* set edge and pixel visibilities to contour lengths */ array<double> edge_vis(n_edges); matrix<> visibility(contours.size_x(), contours.size_y()); for (unsigned long e_id = 0; e_id < n_edges; e_id++) { /* set edge visibility */ const contour_edge& e = (*(contours._edges))[e_id]; double vis = edge_equiv_len[e.contour_equiv_id]; edge_vis[e_id] = scale * vis; /* skip setting pixel visibilities of completion edges */ if (e.is_completion) continue; /* set pixel visibility for points on edge */ unsigned long n_points = e.size(); for (unsigned long n = 0; n < n_points; n++) visibility(e.x_coords[n], e.y_coords[n]) = vis; /* set pixel visibility for edge vertices */ if (visibility(e.vertex_start->x, e.vertex_start->y) < vis) visibility(e.vertex_start->x, e.vertex_start->y) = vis; if (visibility(e.vertex_end->x, e.vertex_end->y) < vis) visibility(e.vertex_end->x, e.vertex_end->y) = vis; } /* extract regions */ this->extract_regions(contours, width, width_min, edge_vis, visibility); } /* * Extract regions using a custom intervening contour cue. * * Instead of using contour length to determine visibility, define a per * pixel visibility map and a minimum visibility for each contour. The * region surrounding a contour C extends to the given width except where * it is blocked by a pixel p such that: * * V(p) > V(C) * * where V(*) denotes visibility. */ lib_image::region_set::region_set( const contour_set& contours, double width, double width_min, const array<double>& edge_vis, const matrix<>& visibility) { this->extract_regions(contours, width, width_min, edge_vis, visibility); } /* * Extract regions using a custom intervening contour cue. */ void lib_image::region_set::extract_regions( const contour_set& contours, double width, double width_min, const array<double>& edge_vis, const matrix<>& visibility) { /* allocate map of pixel -> id of contour equivalence class */ unsigned long n_equiv = contours.edges_equiv_size(); matrix<unsigned long> id_map(contours.size_x(), contours.size_y(), n_equiv); /* set id map entries */ unsigned long n_edges = contours.edges_size(); for (unsigned long e_id = 0; e_id < n_edges; e_id++) { /* get edge, skip if completion */ const contour_edge& e = (*(contours._edges))[e_id]; if (e.is_completion) continue; /* set id for points on edge */ unsigned long n_points = e.size(); for (unsigned long n = 0; n < n_points; n++) id_map(e.x_coords[n], e.y_coords[n]) = e.contour_equiv_id; /* set id for edge vertices (if subdivision) */ if (e.vertex_start->is_subdivision) id_map(e.vertex_start->x, e.vertex_start->y) = e.contour_equiv_id; if (e.vertex_end->is_subdivision) id_map(e.vertex_end->x, e.vertex_end->y) = e.contour_equiv_id; } /* compute length of each original contour (equivalence class) */ array<double> edge_equiv_len(contours.edges_equiv_size()); for (unsigned long e_id = 0; e_id < n_edges; e_id++) { const contour_edge& e = (*(contours._edges))[e_id]; edge_equiv_len[e.contour_equiv_id] += e.length(); } /* resize arrays to hold returned vertex and edge regions */ unsigned long n_vertices = contours.vertices_size(); _vertex_regions_left.resize(n_vertices); _vertex_regions_right.resize(n_vertices); _edge_regions_left.resize(n_edges); _edge_regions_right.resize(n_edges); /* allocate collection of region extractors */ auto_collection< runnable, list<runnable> > region_extractors( new list<runnable>() ); /* setup region extractors */ for (unsigned long equiv_id = 0; equiv_id < n_equiv; equiv_id++) { /* get contour equivalence set */ const list<contour_edge>& equiv_set = (*(contours._edges_equiv))[equiv_id]; /* compute absolute region width to use for contour */ double w = width * edge_equiv_len[equiv_id]; if (w < width_min) { w = width_min; } /* create region extractors for edges and subdivision vertices */ const contour_edge* e_prev = NULL; for (list<contour_edge>::iterator_t i(equiv_set); i.has_next(); ) { /* get current edge */ const contour_edge& e = i.next(); /* create extractor for edge region */ { auto_ptr<edge_region_extractor> e_region_extractor( new edge_region_extractor( e, w, id_map, edge_vis[e.id], visibility, _edge_regions_left[e.id], _edge_regions_right[e.id] ) ); region_extractors->add(*e_region_extractor); e_region_extractor.release(); } /* create extractor for vertex region (if subdivision) */ if ((e.vertex_start->is_subdivision) && (e_prev != NULL)) { /* compute vertex visibility */ double vis_e_prev = edge_vis[e_prev->id]; double vis_e = edge_vis[e.id]; double vis = (vis_e_prev > vis_e) ? vis_e_prev : vis_e; /* create region extractor */ auto_ptr<vertex_region_extractor> v_region_extractor( new vertex_region_extractor( *(e.vertex_start), *e_prev, e, w, id_map, vis, visibility, _vertex_regions_left[e.vertex_start->id], _vertex_regions_right[e.vertex_start->id] ) ); region_extractors->add(*v_region_extractor); v_region_extractor.release(); } /* record previous edge */ e_prev = &e; } } /* extract regions */ child_thread::run(*region_extractors); /* resize arrays to hold returned contour regions */ _edge_equiv_regions_left.resize(n_equiv); _edge_equiv_regions_right.resize(n_equiv); /* allocate collection of region combiners */ auto_collection< runnable, list<runnable> > region_combiners( new list<runnable>() ); /* setup region combiners */ for (unsigned long equiv_id = 0; equiv_id < n_equiv; equiv_id++) { /* create combiner for left side of contour */ auto_ptr<region_combiner> region_left_combiner( new region_combiner( (*(contours._edges_equiv))[equiv_id], _vertex_regions_left, _edge_regions_left, _edge_equiv_regions_left[equiv_id] ) ); region_combiners->add(*region_left_combiner); region_left_combiner.release(); /* create combiner for right side of contour */ auto_ptr<region_combiner> region_right_combiner( new region_combiner( (*(contours._edges_equiv))[equiv_id], _vertex_regions_right, _edge_regions_right, _edge_equiv_regions_right[equiv_id] ) ); region_combiners->add(*region_right_combiner); region_right_combiner.release(); } /* combine vertex and edge regions associated with the same contour */ child_thread::run(*region_combiners); } /* * Copy constructor. */ lib_image::region_set::region_set(const region_set& regions) : _vertex_regions_left(regions._vertex_regions_left), _vertex_regions_right(regions._vertex_regions_right), _edge_regions_left(regions._edge_regions_left), _edge_regions_right(regions._edge_regions_right), _edge_equiv_regions_left(regions._edge_equiv_regions_left), _edge_equiv_regions_right(regions._edge_equiv_regions_right) { } /* * Destructor. */ lib_image::region_set::~region_set() { /* do nothing */ } /*************************************************************************** * Region access. ***************************************************************************/ /* * Get number of vertices in the corresponding contour set. */ unsigned long lib_image::region_set::vertices_size() const { return _vertex_regions_left.size(); } /* * Get number of edges in the region set. */ unsigned long lib_image::region_set::edges_size() const { return _edge_regions_left.size(); } /* * Get the number of edge equivalence classes. * Each equivalence class represents a contour before subdivision. */ unsigned long lib_image::region_set::edges_equiv_size() const { return _edge_equiv_regions_left.size(); } /* * Return the region (by reference) on the left side of the vertex. * Only subdivision vertices are associated with nonempty regions. */ const array<unsigned long>& lib_image::region_set::vertex_region_left( unsigned long v_id) const { if (v_id >= _vertex_regions_left.size()) throw ex_index_out_of_bounds("invalid contour vertex id", v_id); return _vertex_regions_left[v_id]; } /* * Return the region (by reference) on the right side of the vertex. * Only subdivision vertices are associated with nonempty regions. */ const array<unsigned long>& lib_image::region_set::vertex_region_right( unsigned long v_id) const { if (v_id >= _vertex_regions_right.size()) throw ex_index_out_of_bounds("invalid contour vertex id", v_id); return _vertex_regions_right[v_id]; } /* * Return the region (by reference) on the left side of the edge. */ const array<unsigned long>& lib_image::region_set::edge_region_left( unsigned long e_id) const { if (e_id >= _edge_regions_left.size()) throw ex_index_out_of_bounds("invalid contour edge id", e_id); return _edge_regions_left[e_id]; } /* * Return the region (by reference) on the right side of the edge. */ const array<unsigned long>& lib_image::region_set::edge_region_right( unsigned long e_id) const { if (e_id >= _edge_regions_right.size()) throw ex_index_out_of_bounds("invalid contour edge id", e_id); return _edge_regions_right[e_id]; } /* * Return the region (by reference) on the left side of the given * edge equivalence class (original contour before subdivision). */ const array<unsigned long>& lib_image::region_set::edge_equiv_region_left( unsigned long equiv_id) const { if (equiv_id >= _edge_equiv_regions_left.size()) throw ex_index_out_of_bounds("invalid contour equivalence id", equiv_id); return _edge_equiv_regions_left[equiv_id]; } /* * Return the region (by reference) on the right side of the given * edge equivalence class (original contour before subdivision). */ const array<unsigned long>& lib_image::region_set::edge_equiv_region_right( unsigned long equiv_id) const { if (equiv_id >= _edge_equiv_regions_right.size()) throw ex_index_out_of_bounds("invalid contour equivalence id", equiv_id); return _edge_equiv_regions_right[equiv_id]; } matrix<> lib_image::line_inds( double x0, double y0, double x1, double y1, double sx) { point_2D p_start(x0,y0); point_2D p_end(x1,y1); auto_ptr< array<unsigned long> > a = scan_line_segment(p_start,p_end,static_cast<unsigned long>(sx),false); unsigned long s = a->size(); matrix<> m(s,1); for (unsigned long n = 0; n < s; n++) m[n] = static_cast<double>((*a)[n]); return m; } } /* namespace libraries */ } /* namespace math */
36.656976
110
0.596757
[ "geometry", "object", "shape", "vector", "transform" ]
abe144a635d5f9abb8ebefa2d12eb2ad9f12390e
7,223
cpp
C++
plugins/digFlood.cpp
eswald/dfhack
5c0588dd34f51d104ef654f952147c2f3a2f4d77
[ "BSD-2-Clause" ]
null
null
null
plugins/digFlood.cpp
eswald/dfhack
5c0588dd34f51d104ef654f952147c2f3a2f4d77
[ "BSD-2-Clause" ]
null
null
null
plugins/digFlood.cpp
eswald/dfhack
5c0588dd34f51d104ef654f952147c2f3a2f4d77
[ "BSD-2-Clause" ]
null
null
null
#include "Core.h" #include "DataDefs.h" #include "Export.h" #include "PluginManager.h" #include "modules/EventManager.h" #include "modules/MapCache.h" #include "modules/Maps.h" #include "df/coord.h" #include "df/global_objects.h" #include "df/job.h" #include "df/map_block.h" #include "df/tile_dig_designation.h" #include "df/world.h" #include <set> #include <string> #include <vector> using namespace DFHack; using namespace std; using df::global::world; // using df::global::process_jobs; // using df::global::process_dig; command_result digFlood (color_ostream &out, std::vector <std::string> & parameters); DFHACK_PLUGIN("digFlood"); void onDig(color_ostream& out, void* ptr); void maybeExplore(color_ostream& out, MapExtras::MapCache& cache, df::coord pt, set<df::coord>& jobLocations); EventManager::EventHandler digHandler(onDig, 0); //bool enabled = false; DFHACK_PLUGIN_IS_ENABLED(enabled); bool digAll = false; set<string> autodigMaterials; DFhackCExport command_result plugin_enable(color_ostream& out, bool enable) { if (enabled == enable) return CR_OK; enabled = enable; if ( enabled ) { EventManager::registerListener(EventManager::EventType::JOB_COMPLETED, digHandler, plugin_self); } else { EventManager::unregisterAll(plugin_self); } return CR_OK; } DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands) { commands.push_back(PluginCommand( "digFlood", "Automatically dig out veins as you discover them.", digFlood, false, "Example:\n" " digFlood 0\n" " disable plugin\n" " digFlood 1\n" " enable plugin\n" " digFlood 0 MICROCLINE COAL_BITUMINOUS 1\n" " disable plugin and remove microcline and bituminous coal from being monitored, then re-enable plugin" " digFlood 1 MICROCLINE 0 COAL_BITUMINOUS 1\n" " do monitor microcline, don't monitor COAL_BITUMINOUS, then enable plugin\n" " digFlood CLEAR\n" " remove all inorganics from monitoring\n" " digFlood digAll1\n" " enable digAll mode: dig any vein, regardless of the monitor list\n" " digFlood digAll0\n" " disable digAll mode\n" "\n" "Note that while order matters, multiple commands can be sequenced in one line. It is recommended to alter your dfhack.init file so that you won't have to type in every mineral type you want to dig every time you start the game. Material names are case sensitive.\n" )); return CR_OK; } void onDig(color_ostream& out, void* ptr) { CoreSuspender bob; df::job* job = (df::job*)ptr; if ( job->completion_timer > 0 ) return; if ( job->job_type != df::enums::job_type::Dig && job->job_type != df::enums::job_type::CarveUpwardStaircase && job->job_type != df::enums::job_type::CarveDownwardStaircase && job->job_type != df::enums::job_type::CarveUpDownStaircase && job->job_type != df::enums::job_type::CarveRamp && job->job_type != df::enums::job_type::DigChannel ) return; set<df::coord> jobLocations; for ( df::job_list_link* link = &world->job_list; link != NULL; link = link->next ) { if ( link->item == NULL ) continue; if ( link->item->job_type != df::enums::job_type::Dig && link->item->job_type != df::enums::job_type::CarveUpwardStaircase && link->item->job_type != df::enums::job_type::CarveDownwardStaircase && link->item->job_type != df::enums::job_type::CarveUpDownStaircase && link->item->job_type != df::enums::job_type::CarveRamp && link->item->job_type != df::enums::job_type::DigChannel ) continue; jobLocations.insert(link->item->pos); } MapExtras::MapCache cache; df::coord pos = job->pos; for ( int16_t a = -1; a <= 1; a++ ) { for ( int16_t b = -1; b <= 1; b++ ) { maybeExplore(out, cache, df::coord(pos.x+a,pos.y+b,pos.z), jobLocations); } } cache.trash(); } void maybeExplore(color_ostream& out, MapExtras::MapCache& cache, df::coord pt, set<df::coord>& jobLocations) { if ( !Maps::isValidTilePos(pt) ) { return; } df::map_block* block = Maps::getTileBlock(pt); if (!block) return; if ( block->designation[pt.x&0xF][pt.y&0xF].bits.hidden ) return; df::tiletype type = block->tiletype[pt.x&0xF][pt.y&0xF]; if ( ENUM_ATTR(tiletype, material, type) != df::enums::tiletype_material::MINERAL ) return; if ( ENUM_ATTR(tiletype, shape, type) != df::enums::tiletype_shape::WALL ) return; if ( block->designation[pt.x&0xF][pt.y&0xF].bits.dig != df::enums::tile_dig_designation::No ) return; uint32_t xMax,yMax,zMax; Maps::getSize(xMax,yMax,zMax); if ( pt.x == 0 || pt.y == 0 || pt.x+1 == xMax*16 || pt.y+1 == yMax*16 ) return; if ( jobLocations.find(pt) != jobLocations.end() ) { return; } int16_t mat = cache.veinMaterialAt(pt); if ( mat == -1 ) return; if ( !digAll ) { df::inorganic_raw* inorganic = world->raws.inorganics[mat]; if ( autodigMaterials.find(inorganic->id) == autodigMaterials.end() ) { return; } } block->designation[pt.x&0xF][pt.y&0xF].bits.dig = df::enums::tile_dig_designation::Default; block->flags.bits.designated = true; // *process_dig = true; // *process_jobs = true; } command_result digFlood (color_ostream &out, std::vector <std::string> & parameters) { bool adding = true; set<string> toAdd, toRemove; for ( size_t a = 0; a < parameters.size(); a++ ) { int32_t i = (int32_t)strtol(parameters[a].c_str(), NULL, 0); if ( i == 0 && parameters[a] == "0" ) { plugin_enable(out, false); adding = false; continue; } else if ( i == 1 ) { plugin_enable(out, true); adding = true; continue; } if ( parameters[a] == "CLEAR" ) autodigMaterials.clear(); if ( parameters[a] == "digAll0" ) { digAll = false; continue; } if ( parameters[a] == "digAll1" ) { digAll = true; continue; } for ( size_t b = 0; b < world->raws.inorganics.size(); b++ ) { df::inorganic_raw* inorganic = world->raws.inorganics[b]; if ( parameters[a] == inorganic->id ) { if ( adding ) toAdd.insert(parameters[a]); else toRemove.insert(parameters[a]); goto loop; } } out.print("Could not find material \"%s\".\n", parameters[a].c_str()); return CR_WRONG_USAGE; loop: continue; } autodigMaterials.insert(toAdd.begin(), toAdd.end()); for ( auto a = toRemove.begin(); a != toRemove.end(); a++ ) autodigMaterials.erase(*a); return CR_OK; }
33.439815
274
0.590198
[ "shape", "vector" ]
abe1672410687de943c4a186b1202e2901e0e12f
14,888
cc
C++
caffe2/operators/group_norm_op.cc
brooks-anderson/pytorch
dd928097938b6368fc7e2dc67721550d50ab08ea
[ "Intel" ]
7
2021-05-29T16:31:51.000Z
2022-02-21T18:52:25.000Z
caffe2/operators/group_norm_op.cc
brooks-anderson/pytorch
dd928097938b6368fc7e2dc67721550d50ab08ea
[ "Intel" ]
1
2021-05-10T01:18:33.000Z
2021-05-10T01:18:33.000Z
caffe2/operators/group_norm_op.cc
brooks-anderson/pytorch
dd928097938b6368fc7e2dc67721550d50ab08ea
[ "Intel" ]
1
2021-06-21T14:41:30.000Z
2021-06-21T14:41:30.000Z
// ------------------------------------------------------------------ // GroupNorm op in Caffe2 for CPU // Written by Kaiming He // Improved by Xiaomeng Yang // see https://arxiv.org/abs/1803.08494 // This is a stand-alone op: Y = gamma * (X - mu) / sig + beta // ------------------------------------------------------------------ #include "caffe2/operators/group_norm_op.h" #include "caffe2/utils/eigen_utils.h" namespace caffe2 { // Math: // Y = gamma * (X - mu) * rsig + beta // let s = gamma * rsig // let b = beta - gamma * mu * rsig // Y = s * X + b // let n = K * HxW // dL/dX = dL/dY * dY/dX = dL/dY * (d(s * X)/dX + db/dX) // d(s * X)/dX = s + X * ds/dX = s + gamma * X * drsig/dX // db/dX = -gamma * u * drsig/dX - gamma * rsig * dmu/dX // drsig/dX = -rsig^3 * (X - mu) / n // dmu/dX = 1 / n namespace { template <typename T, StorageOrder kOrder> void ComputeInternalGradients( int N, int C, int HxW, const T* dY, const T* X, T* ds, T* db); template <> void ComputeInternalGradients<float, StorageOrder::NCHW>( const int N, const int C, const int HxW, const float* dY, const float* X, float* ds, float* db) { ConstEigenArrayMap<float> dY_arr(dY, HxW, N * C); ConstEigenArrayMap<float> X_arr(X, HxW, N * C); for (int i = 0; i < N * C; ++i) { ds[i] = (dY_arr.col(i) * X_arr.col(i)).sum(); db[i] = dY_arr.col(i).sum(); } } template <> void ComputeInternalGradients<float, StorageOrder::NHWC>( const int N, const int C, const int HxW, const float* dY, const float* X, float* ds, float* db) { EigenArrayMap<float> ds_arr(ds, C, N); EigenArrayMap<float> db_arr(db, C, N); for (int i = 0; i < N; ++i) { ConstEigenArrayMap<float> dY_arr(dY + i * C * HxW, C, HxW); ConstEigenArrayMap<float> X_arr(X + i * C * HxW, C, HxW); ds_arr.col(i) = dY_arr.col(0) * X_arr.col(0); db_arr.col(i) = dY_arr.col(0); for (int j = 1; j < HxW; ++j) { ds_arr.col(i) += dY_arr.col(j) * X_arr.col(j); db_arr.col(i) += dY_arr.col(j); } } } template <typename T> void ComputeGradientFusedParams( const int N, const int G, const int K, const int HxW, const T* ds, const T* db, const T* mu, const T* rsig, const T* gamma, T* dY_scale, T* X_scale, T* bias) { ConstEigenArrayMap<T> rsig_arr(rsig, G, N); ConstEigenArrayMap<T> gamma_arr(gamma, K, G); for (int i = 0; i < N; ++i) { EigenArrayMap<T>(dY_scale + i * G * K, K, G) = gamma_arr.rowwise() * (rsig_arr.col(i).transpose()); } ConstEigenVectorArrayMap<T> mu_arr(mu, N * G); ConstEigenVectorArrayMap<T> rsig_vec(rsig, N * G); EigenVectorArrayMap<T> X_scale_arr(X_scale, N * G); EigenVectorArrayMap<T> bias_arr(bias, N * G); for (int i = 0; i < N; ++i) { ConstEigenArrayMap<T> ds_arr(ds + i * G * K, K, G); ConstEigenArrayMap<T> db_arr(db + i * G * K, K, G); for (int j = 0; j < G; ++j) { X_scale_arr(i * G + j) = (ds_arr.col(j) * gamma_arr.col(j)).sum(); bias_arr(i * G + j) = (db_arr.col(j) * gamma_arr.col(j)).sum(); } } const T alpha = T(1) / static_cast<T>(K * HxW); X_scale_arr = (bias_arr * mu_arr - X_scale_arr) * rsig_vec.cube() * alpha; bias_arr = -X_scale_arr * mu_arr - bias_arr * rsig_vec * alpha; } template <typename T, StorageOrder kOrder> void GroupNormBackward( int N, int G, int K, int HxW, const T* dY_scale, const T* dY, const T* X_scale, const T* X, const T* bias, T* dX); template <> void GroupNormBackward<float, StorageOrder::NCHW>( const int N, const int G, const int K, const int HxW, const float* dY_scale, const float* dY, const float* X_scale, const float* X, const float* bias, float* dX) { const int C = G * K; ConstEigenArrayMap<float> dY_arr(dY, HxW, N * C); ConstEigenArrayMap<float> X_arr(X, HxW, N * C); EigenArrayMap<float> dX_arr(dX, HxW, N * C); for (int i = 0; i < N * G; ++i) { for (int j = 0; j < K; ++j) { const int c = i * K + j; dX_arr.col(c) = dY_arr.col(c) * dY_scale[c] + X_arr.col(c) * X_scale[i] + bias[i]; } } } template <> void GroupNormBackward<float, StorageOrder::NHWC>( const int N, const int G, const int K, const int HxW, const float* dY_scale, const float* dY, const float* X_scale, const float* X, const float* bias, float* dX) { const int C = G * K; ConstEigenArrayMap<float> X_scale_arr(X_scale, G, N); ConstEigenArrayMap<float> bias_arr(bias, G, N); for (int n = 0; n < N; ++n) { ConstEigenArrayMap<float> dY_scale_arr(dY_scale + n * C, K, G); for (int i = 0; i < HxW; ++i) { const int m = n * HxW + i; ConstEigenArrayMap<float> dY_arr(dY + m * C, K, G); ConstEigenArrayMap<float> X_arr(X + m * C, K, G); EigenArrayMap<float> dX_arr(dX + m * C, K, G); dX_arr = (dY_arr * dY_scale_arr + X_arr.rowwise() * X_scale_arr.col(n).transpose()) .rowwise() + bias_arr.col(n).transpose(); } } } template <typename T> void GammaBetaBackward( const int N, const int G, const int K, const T* ds, const T* db, const T* mu, const T* rsig, T* dgamma, T* dbeta) { const int C = G * K; ConstEigenArrayMap<T> ds0_arr(ds, K, G); ConstEigenArrayMap<T> db0_arr(db, K, G); ConstEigenArrayMap<T> mu_arr(mu, G, N); ConstEigenArrayMap<T> rsig_arr(rsig, G, N); EigenArrayMap<T> dgamma_arr(dgamma, K, G); EigenArrayMap<T> dbeta_arr(dbeta, K, G); dgamma_arr = (ds0_arr - db0_arr.rowwise() * mu_arr.col(0).transpose()).rowwise() * rsig_arr.col(0).transpose(); dbeta_arr = db0_arr; for (int i = 1; i < N; ++i) { ConstEigenArrayMap<T> dsi_arr(ds + i * C, K, G); ConstEigenArrayMap<T> dbi_arr(db + i * C, K, G); dgamma_arr += (dsi_arr - dbi_arr.rowwise() * mu_arr.col(i).transpose()).rowwise() * rsig_arr.col(i).transpose(); dbeta_arr += dbi_arr; } } } // namespace template <> void GroupNormOp<float, CPUContext>::ComputeFusedParams( const int N, const int G, const int K, const float* mu, const float* rsig, const float* gamma, const float* beta, float* scale, float* bias) { const int C = G * K; ConstEigenArrayMap<float> mu_arr(mu, G, N); ConstEigenArrayMap<float> rsig_arr(rsig, G, N); ConstEigenArrayMap<float> gamma_arr(gamma, K, G); ConstEigenArrayMap<float> beta_arr(beta, K, G); for (int i = 0; i < N; ++i) { EigenArrayMap<float> scale_arr(scale + i * C, K, G); EigenArrayMap<float> bias_arr(bias + i * C, K, G); scale_arr = gamma_arr.rowwise() * rsig_arr.col(i).transpose(); bias_arr = beta_arr - scale_arr.rowwise() * mu_arr.col(i).transpose(); } } template <> void GroupNormOp<float, CPUContext>::GroupNormForwardNCHW( const int N, const int C, const int HxW, const float* X, const float* scale, const float* bias, float* Y) { EigenArrayMap<float>(Y, HxW, N * C) = (ConstEigenArrayMap<float>(X, HxW, N * C).rowwise() * ConstEigenVectorArrayMap<float>(scale, N * C).transpose()) .rowwise() + ConstEigenVectorArrayMap<float>(bias, N * C).transpose(); } template <> void GroupNormOp<float, CPUContext>::GroupNormForwardNHWC( const int N, const int C, const int HxW, const float* X, const float* scale, const float* bias, float* Y) { const int stride = HxW * C; for (int i = 0; i < N; ++i) { EigenArrayMap<float>(Y + i * stride, C, HxW) = (ConstEigenArrayMap<float>(X + i * stride, C, HxW).colwise() * ConstEigenVectorArrayMap<float>(scale + i * C, C)) .colwise() + ConstEigenVectorArrayMap<float>(bias + i * C, C); } } template <> bool GroupNormOp<float, CPUContext>::RunOnDeviceWithOrderNHWC( const int N, const int G, const int K, const int HxW, const float* X, const float* gamma, const float* beta, float* Y, float* mu, float* rsig) { const int C = G * K; ReinitializeTensor(&scale_, {N, C}, at::dtype<float>().device(CPU)); ReinitializeTensor(&bias_, {N, C}, at::dtype<float>().device(CPU)); float* scale_data = scale_.mutable_data<float>(); float* bias_data = bias_.mutable_data<float>(); EigenVectorArrayMap<float> mu_arr(mu, N * G); EigenVectorArrayMap<float> rsig_arr(rsig, N * G); mu_arr.setZero(); rsig_arr.setZero(); for (int n = 0; n < N; ++n) { for (int i = 0; i < HxW; ++i) { const int m = n * HxW + i; ConstEigenArrayMap<float> X_arr(X + m * C, K, G); for (int j = 0; j < G; ++j) { mu_arr(n * G + j) += X_arr.col(j).sum(); rsig_arr(n * G + j) += X_arr.col(j).square().sum(); } } } const float scale = 1.0f / static_cast<float>(K * HxW); mu_arr *= scale; rsig_arr = (rsig_arr * scale - mu_arr.square() + epsilon_).rsqrt(); ComputeFusedParams(N, G, K, mu, rsig, gamma, beta, scale_data, bias_data); GroupNormForwardNHWC(N, C, HxW, X, scale_data, bias_data, Y); return true; } // Math: // let: s = gamma * rsig // let: b = beta - mu * gamma * rsig // then: Y = s * X + b template <> bool GroupNormGradientOp<float, CPUContext>::RunOnDeviceWithOrderNCHW( const int N, const int G, const int K, const int HxW, const float* dY_data, const float* X_data, const float* mu_data, const float* rsig_data, const float* gamma_data, float* dX_data, float* dgamma_data, float* dbeta_data) { const int C = G * K; ReinitializeTensor(&ds_, {N, C}, at::dtype<float>().device(CPU)); ReinitializeTensor(&db_, {N, C}, at::dtype<float>().device(CPU)); ReinitializeTensor(&dY_scale_, {N, C}, at::dtype<float>().device(CPU)); ReinitializeTensor(&X_scale_, {N, G}, at::dtype<float>().device(CPU)); ReinitializeTensor(&bias_, {N, G}, at::dtype<float>().device(CPU)); float* ds_data = ds_.mutable_data<float>(); float* db_data = db_.mutable_data<float>(); float* dY_scale_data = dY_scale_.mutable_data<float>(); float* X_scale_data = X_scale_.mutable_data<float>(); float* bias_data = bias_.mutable_data<float>(); ComputeInternalGradients<float, StorageOrder::NCHW>( N, C, HxW, dY_data, X_data, ds_data, db_data); ComputeGradientFusedParams<float>( N, G, K, HxW, ds_data, db_data, mu_data, rsig_data, gamma_data, dY_scale_data, X_scale_data, bias_data); GroupNormBackward<float, StorageOrder::NCHW>( N, G, K, HxW, dY_scale_data, dY_data, X_scale_data, X_data, bias_data, dX_data); GammaBetaBackward<float>( N, G, K, ds_data, db_data, mu_data, rsig_data, dgamma_data, dbeta_data); return true; } template <typename T, class Context> bool GroupNormGradientOp<T, Context>::RunOnDeviceWithOrderNHWC( const int N, const int G, const int K, const int HxW, const T* dY_data, const T* X_data, const T* mu_data, const T* rsig_data, const T* gamma_data, T* dX_data, T* dgamma_data, T* dbeta_data) { const int C = G * K; ReinitializeTensor(&ds_, {N, C}, at::dtype<float>().device(CPU)); ReinitializeTensor(&db_, {N, C}, at::dtype<float>().device(CPU)); ReinitializeTensor(&dY_scale_, {N, C}, at::dtype<float>().device(CPU)); ReinitializeTensor(&X_scale_, {N, G}, at::dtype<float>().device(CPU)); ReinitializeTensor(&bias_, {N, G}, at::dtype<float>().device(CPU)); float* ds_data = ds_.mutable_data<float>(); float* db_data = db_.mutable_data<float>(); float* dY_scale_data = dY_scale_.mutable_data<float>(); float* X_scale_data = X_scale_.mutable_data<float>(); float* bias_data = bias_.mutable_data<float>(); ComputeInternalGradients<float, StorageOrder::NHWC>( N, C, HxW, dY_data, X_data, ds_data, db_data); ComputeGradientFusedParams<float>( N, G, K, HxW, ds_data, db_data, mu_data, rsig_data, gamma_data, dY_scale_data, X_scale_data, bias_data); GroupNormBackward<float, StorageOrder::NHWC>( N, G, K, HxW, dY_scale_data, dY_data, X_scale_data, X_data, bias_data, dX_data); GammaBetaBackward<float>( N, G, K, ds_data, db_data, mu_data, rsig_data, dgamma_data, dbeta_data); return true; } // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(GroupNorm, GroupNormOp<float, CPUContext>); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR( GroupNormGradient, GroupNormGradientOp<float, CPUContext>); // Warning: mu and rsig are for backward usage or reference. They should NOT be // used as forward activations as they have no direct gradients computed. // Input: X, gamma, beta; Output: Y, mu, sig // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(GroupNorm) .NumInputs(3) .NumOutputs({1, 3}) .SetDoc(R"DOC( Group Normalization (GN) operation: https://arxiv.org/abs/1803.08494 )DOC") .Arg("num_groups", "(int) default 32; number of groups used by GN.") .Arg("epsilon", "(float) default 1e-5; small constant added to var.") .Input( 0, "X", ">=4D feature map input of shape (N, C, H, W) or (N, C, T, H, W)") .Input( 1, "gamma", "The scale as a 1-dimensional tensor of size C to be applied to the " "output.") .Input( 2, "beta", "The bias as a 1-dimensional tensor of size C to be applied to the " "output.") .Output(0, "Y", "The output >=4-dimensional tensor of the same shape as X.") .Output( 1, "mean", "The mean of shape (N, G). " "For backward usage or reference. " "Cannot be used as activations.") .Output( 2, "std", "The std of shape (N, G). " "For backward usage or reference. " "Cannot be used as activations."); // Input: dY, X, gamma, beta, mu, sig; Output: dX, dgamma, dbeta // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,cppcoreguidelines-avoid-magic-numbers) OPERATOR_SCHEMA(GroupNormGradient).NumInputs(6).NumOutputs(3); namespace { class GetGroupNormGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; std::vector<OperatorDef> GetGradientDefs() override { return SingleGradientDef( "GroupNormGradient", "", std::vector<std::string>{GO(0), I(0), I(1), I(2), O(1), O(2)}, std::vector<std::string>{GI(0), GI(1), GI(2)}); } }; } // namespace // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_GRADIENT(GroupNorm, GetGroupNormGradient); } // namespace caffe2
29.59841
107
0.606394
[ "shape", "vector" ]
7447870046f484e64eae7f98b0bc457cfeac93c8
2,778
cc
C++
tensorflow_lite_support/examples/task/audio/desktop/audio_classifier_demo.cc
khanhlvg/tflite-support
a4febca66974ae51fecc45bb7ecbc31794bbc4fc
[ "Apache-2.0" ]
242
2020-06-01T03:20:05.000Z
2022-03-29T23:45:38.000Z
tensorflow_lite_support/examples/task/audio/desktop/audio_classifier_demo.cc
khanhlvg/tflite-support
a4febca66974ae51fecc45bb7ecbc31794bbc4fc
[ "Apache-2.0" ]
140
2020-07-01T03:56:01.000Z
2022-03-31T14:08:54.000Z
tensorflow_lite_support/examples/task/audio/desktop/audio_classifier_demo.cc
khanhlvg/tflite-support
a4febca66974ae51fecc45bb7ecbc31794bbc4fc
[ "Apache-2.0" ]
82
2020-07-01T10:30:41.000Z
2022-03-27T12:28:24.000Z
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Example usage: // bazel run -c opt \ // tensorflow_lite_support/examples/task/audio/desktop:audio_classifier_demo \ // -- \ // --model_path=/path/to/model.tflite \ // --audio_wav_path=/path/to/audio.wav #include <cstddef> #include <iostream> #include <limits> #include "absl/flags/flag.h" // from @com_google_absl #include "absl/flags/parse.h" // from @com_google_absl #include "tensorflow_lite_support/examples/task/audio/desktop/audio_classifier_lib.h" ABSL_FLAG(std::string, model_path, "", "Absolute path to the '.tflite' audio classification model."); ABSL_FLAG(std::string, audio_wav_path, "", "Absolute path to the 16-bit PCM WAV file to classify. The WAV " "file must be monochannel and has a sampling rate matches the model " "expected sampling rate (as in the Metadata). If the WAV file is " "longer than what the model requires, only the beginning section is " "used for inference."); ABSL_FLAG(float, score_threshold, 0.001f, "Apply a filter on the results. Only display classes with score " "higher than the threshold."); ABSL_FLAG(bool, use_coral, false, "If true, inference will be delegated to a connected Coral Edge TPU " "device."); int main(int argc, char** argv) { // Parse command line arguments and perform sanity checks. absl::ParseCommandLine(argc, argv); if (absl::GetFlag(FLAGS_model_path).empty()) { std::cerr << "Missing mandatory 'model_path' argument.\n"; return 1; } if (absl::GetFlag(FLAGS_audio_wav_path).empty()) { std::cerr << "Missing mandatory 'audio_wav_path' argument.\n"; return 1; } // Run classification. auto result = tflite::task::audio::Classify( absl::GetFlag(FLAGS_model_path), absl::GetFlag(FLAGS_audio_wav_path), absl::GetFlag(FLAGS_use_coral)); if (result.ok()) { tflite::task::audio::Display(result.value(), absl::GetFlag(FLAGS_score_threshold)); } else { std::cerr << "Classification failed: " << result.status().message() << "\n"; return 1; } }
39.685714
85
0.674226
[ "model" ]
744869dcb5a09f3d59afed7eb0315f1cfa9b3da1
18,559
cc
C++
scann/scann/hashes/asymmetric_hashing2/searcher.cc
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
1
2021-01-08T03:21:19.000Z
2021-01-08T03:21:19.000Z
scann/scann/hashes/asymmetric_hashing2/searcher.cc
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
null
null
null
scann/scann/hashes/asymmetric_hashing2/searcher.cc
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The Google Research 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 "scann/hashes/asymmetric_hashing2/searcher.h" #include <math.h> #include <memory> #include <typeinfo> #include "scann/base/search_parameters.h" #include "scann/base/single_machine_base.h" #include "scann/data_format/dataset.h" #include "scann/distance_measures/distance_measures.h" #include "scann/hashes/asymmetric_hashing2/querying.h" #include "scann/hashes/asymmetric_hashing2/serialization.h" #include "scann/hashes/internal/asymmetric_hashing_postprocess.h" #include "tensorflow/core/platform/cpu_info.h" #include "scann/oss_wrappers/scann_serialize.h" #include "scann/utils/datapoint_utils.h" #include "scann/utils/types.h" #include "tensorflow/core/lib/core/errors.h" namespace tensorflow { namespace scann_ops { namespace asymmetric_hashing2 { namespace { shared_ptr<DenseDataset<uint8_t>> PreprocessHashedDataset( shared_ptr<DenseDataset<uint8_t>> hashed_dataset, const AsymmetricHasherConfig::QuantizationScheme quantization_scheme, const size_t num_blocks) { if (quantization_scheme == AsymmetricHasherConfig::PRODUCT_AND_BIAS) { auto dataset_no_bias = std::make_shared<DenseDataset<uint8_t>>(); if (hashed_dataset->empty()) { return dataset_no_bias; } dataset_no_bias->set_dimensionality((*hashed_dataset)[0].nonzero_entries() - sizeof(float)); dataset_no_bias->Reserve(hashed_dataset->size()); for (const auto& dp : *hashed_dataset) { auto dptr = MakeDatapointPtr(dp.values(), dp.nonzero_entries() - sizeof(float)); TF_CHECK_OK(dataset_no_bias->Append(dptr, "")); } return dataset_no_bias; } else if (quantization_scheme == AsymmetricHasherConfig::PRODUCT_AND_PACK) { auto dataset_unpacked = std::make_shared<DenseDataset<uint8_t>>(); dataset_unpacked->set_dimensionality(num_blocks); dataset_unpacked->Reserve(hashed_dataset->size()); Datapoint<uint8_t> unpacked_dp; for (const auto& dptr : *hashed_dataset) { UnpackNibblesDatapoint(dptr, &unpacked_dp); TF_CHECK_OK(dataset_unpacked->Append(unpacked_dp.ToPtr(), "")); } return dataset_unpacked; } return hashed_dataset; } } // namespace template <typename T> Searcher<T>::Searcher(shared_ptr<TypedDataset<T>> dataset, shared_ptr<DenseDataset<uint8_t>> hashed_dataset, SearcherOptions<T> opts, int32_t default_pre_reordering_num_neighbors, float default_pre_reordering_epsilon) : SingleMachineSearcherBase<T>( dataset, PreprocessHashedDataset(hashed_dataset, opts.quantization_scheme(), opts.num_blocks()), default_pre_reordering_num_neighbors, default_pre_reordering_epsilon), opts_(std::move(opts)), limited_inner_product_( (opts_.asymmetric_queryer_ && typeid(*opts_.asymmetric_queryer_->lookup_distance()) == typeid(const LimitedInnerProductDistance))), lut16_(opts_.asymmetric_lookup_type_ == AsymmetricHasherConfig::INT8_LUT16 && opts_.asymmetric_queryer_) { DCHECK(hashed_dataset); if (lut16_) { packed_dataset_ = ::tensorflow::scann_ops::asymmetric_hashing2::CreatePackedDataset( *this->hashed_dataset()); const size_t l2_cache_bytes = 256 * 1024; if (packed_dataset_.bit_packed_data.size() <= l2_cache_bytes / 2) { optimal_low_level_batch_size_ = 3; max_low_level_batch_size_ = 3; } else { if (RuntimeSupportsAvx2()) { if (packed_dataset_.num_blocks <= 300) { optimal_low_level_batch_size_ = 7; } else { optimal_low_level_batch_size_ = 5; } } else { if (packed_dataset_.num_blocks <= 300) { optimal_low_level_batch_size_ = 6; } else { optimal_low_level_batch_size_ = 5; } } } } if (opts_.quantization_scheme() == AsymmetricHasherConfig::PRODUCT_AND_BIAS) { bias_.reserve(hashed_dataset->size()); if (!hashed_dataset->empty()) { const int dim = hashed_dataset->at(0).nonzero_entries(); for (int i = 0; i < hashed_dataset->size(); i++) { const float bias = strings::KeyToFloat(string_view( reinterpret_cast<const char*>((*hashed_dataset)[i].values() + dim - sizeof(float)), sizeof(float))); bias_.push_back(-bias); } } } if (limited_inner_product_) { CHECK(opts_.indexer_) << "Indexer must be non-null if " "limited inner product searcher is being used."; for (DatapointIndex dp_idx : Seq(hashed_dataset->size())) { Datapoint<FloatingTypeFor<T>> dp; TF_CHECK_OK(opts_.indexer_->Reconstruct((*hashed_dataset)[dp_idx], &dp)); double norm = SquaredL2Norm(dp.ToPtr()); norm_inv_.push_back(static_cast<float>(norm == 0 ? 0 : 1 / sqrt(norm))); } } } template <typename T> Searcher<T>::~Searcher() {} template <typename T> Status Searcher<T>::FindNeighborsImpl(const DatapointPtr<T>& query, const SearchParameters& params, NNResultsVector* result) const { if (limited_inner_product_) { if (opts_.symmetric_queryer_) { return FailedPreconditionError( "LimitedInnerProduct does not work with symmetric queryer."); } float query_norm = static_cast<float>(sqrt(SquaredL2Norm(query))); asymmetric_hashing_internal::LimitedInnerFunctor functor(query_norm, norm_inv_); return FindNeighborsTopNDispatcher< asymmetric_hashing_internal::LimitedInnerFunctor>(query, params, functor, result); } else if (opts_.quantization_scheme() == AsymmetricHasherConfig::PRODUCT_AND_BIAS) { asymmetric_hashing_internal::AddBiasFunctor functor( bias_, query.values_slice().back()); return FindNeighborsTopNDispatcher< asymmetric_hashing_internal::AddBiasFunctor>(query, params, functor, result); } else { return FindNeighborsTopNDispatcher< asymmetric_hashing_internal::IdentityPostprocessFunctor>( query, params, asymmetric_hashing_internal::IdentityPostprocessFunctor(), result); } } template <typename T> Status Searcher<T>::FindNeighborsBatchedImpl( const TypedDataset<T>& queries, ConstSpan<SearchParameters> params, MutableSpan<NNResultsVector> results) const { bool crowding_enabled_for_any_query = false; for (const auto& p : params) { if (p.pre_reordering_crowding_enabled()) { crowding_enabled_for_any_query = true; break; } } if (opts_.symmetric_queryer_ || !lut16_ || limited_inner_product_ || crowding_enabled_for_any_query || opts_.quantization_scheme() == AsymmetricHasherConfig::PRODUCT_AND_BIAS) { return SingleMachineSearcherBase<T>::FindNeighborsBatchedImpl( queries, params, results); } return FindNeighborsBatchedInternal< asymmetric_hashing_internal::IdentityPostprocessFunctor>( [&queries](DatapointIndex i) { return queries[i]; }, params, asymmetric_hashing_internal::IdentityPostprocessFunctor(), results); } template <typename T> StatusOr<const LookupTable*> Searcher<T>::GetOrCreateLookupTable( const DatapointPtr<T>& query, const SearchParameters& params, LookupTable* created_lookup_table_storage) const { DCHECK(created_lookup_table_storage); auto per_query_opts = dynamic_cast<const AsymmetricHashingOptionalParameters*>( params.searcher_specific_optional_parameters()); if (per_query_opts && !per_query_opts->precomputed_lookup_table_.empty()) { return &per_query_opts->precomputed_lookup_table_; } else { TF_ASSIGN_OR_RETURN(*created_lookup_table_storage, opts_.asymmetric_queryer_->CreateLookupTable( query, opts_.asymmetric_lookup_type_, opts_.fixed_point_lut_conversion_options_)); return created_lookup_table_storage; } } template <typename T> template <typename PostprocessFunctor> Status Searcher<T>::FindNeighborsTopNDispatcher( const DatapointPtr<T>& query, const SearchParameters& params, PostprocessFunctor postprocessing_functor, NNResultsVector* result) const { if (params.pre_reordering_crowding_enabled()) { return FailedPreconditionError("Crowding is not supported."); } else { auto ah_optional_params = params.searcher_specific_optional_parameters< AsymmetricHashingOptionalParameters>(); if (ah_optional_params && ah_optional_params->top_n() && !opts_.symmetric_queryer_) { auto queryer_opts = GetQueryerOptions(postprocessing_functor); queryer_opts.first_dp_index = ah_optional_params->starting_dp_idx_; queryer_opts.lut16_bias = ah_optional_params->lut16_bias_; LookupTable lookup_table_storage; TF_ASSIGN_OR_RETURN( const LookupTable* lookup_table, GetOrCreateLookupTable(query, params, &lookup_table_storage)); SCANN_RETURN_IF_ERROR(AsymmetricQueryer<T>::FindApproximateNeighbors( *lookup_table, params, std::move(queryer_opts), ah_optional_params->top_n_)); } else { TopNeighbors<float> top_n(params.pre_reordering_num_neighbors()); SCANN_RETURN_IF_ERROR(FindNeighborsQueryerDispatcher( query, params, postprocessing_functor, &top_n)); *result = top_n.TakeUnsorted(); } } return OkStatus(); } template <typename T> template <typename PostprocessFunctor> QueryerOptions<PostprocessFunctor> Searcher<T>::GetQueryerOptions( PostprocessFunctor postprocessing_functor) const { QueryerOptions<PostprocessFunctor> queryer_options; std::shared_ptr<DefaultDenseDatasetView<uint8_t>> hashed_dataset_view; if (this->hashed_dataset()) { hashed_dataset_view = std::make_shared<DefaultDenseDatasetView<uint8_t>>( *this->hashed_dataset()); } queryer_options.hashed_dataset = hashed_dataset_view; queryer_options.postprocessing_functor = std::move(postprocessing_functor); if (lut16_) queryer_options.lut16_packed_dataset = &packed_dataset_; return queryer_options; } template <typename T> template <typename PostprocessFunctor, typename TopN> Status Searcher<T>::FindNeighborsQueryerDispatcher( const DatapointPtr<T>& query, const SearchParameters& params, PostprocessFunctor postprocessing_functor, TopN* result) const { auto queryer_options = GetQueryerOptions(postprocessing_functor); if (opts_.symmetric_queryer_) { auto view = queryer_options.hashed_dataset.get(); Datapoint<uint8_t> hashed_query; SCANN_RETURN_IF_ERROR(opts_.indexer_->Hash(query, &hashed_query)); SCANN_RETURN_IF_ERROR(opts_.symmetric_queryer_->FindApproximateNeighbors( hashed_query.ToPtr(), view, params, std::move(queryer_options), result)); } else { LookupTable lookup_table_storage; TF_ASSIGN_OR_RETURN( const LookupTable* lookup_table, GetOrCreateLookupTable(query, params, &lookup_table_storage)); SCANN_RETURN_IF_ERROR(AsymmetricQueryer<T>::FindApproximateNeighbors( *lookup_table, params, std::move(queryer_options), result)); } return OkStatus(); } template <typename T> template <typename PostprocessFunctor> Status Searcher<T>::FindNeighborsBatchedInternal( std::function<DatapointPtr<T>(DatapointIndex)> get_query, ConstSpan<SearchParameters> params, PostprocessFunctor postprocessing_functor, MutableSpan<NNResultsVector> results) const { using QueryerOptionsT = QueryerOptions<PostprocessFunctor>; QueryerOptionsT queryer_options; if (this->hashed_dataset()) { queryer_options.hashed_dataset = std::make_shared<DefaultDenseDatasetView<uint8_t>>( *this->hashed_dataset()); } queryer_options.postprocessing_functor = std::move(postprocessing_functor); queryer_options.lut16_packed_dataset = &packed_dataset_; const size_t num_queries = params.size(); size_t low_level_batch_start = 0; while (low_level_batch_start < num_queries) { const size_t low_level_batch_size = [&] { const size_t queries_left = num_queries - low_level_batch_start; if (queries_left <= max_low_level_batch_size_) return queries_left; if (queries_left >= 2 * max_low_level_batch_size_) { return optimal_low_level_batch_size_; } return queries_left / 2; }(); switch (low_level_batch_size) { case 9: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<9>( low_level_batch_start, get_query, params, queryer_options, results)); break; case 8: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<8>( low_level_batch_start, get_query, params, queryer_options, results)); break; case 7: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<7>( low_level_batch_start, get_query, params, queryer_options, results)); break; case 6: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<6>( low_level_batch_start, get_query, params, queryer_options, results)); break; case 5: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<5>( low_level_batch_start, get_query, params, queryer_options, results)); break; case 4: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<4>( low_level_batch_start, get_query, params, queryer_options, results)); break; case 3: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<3>( low_level_batch_start, get_query, params, queryer_options, results)); break; case 2: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<2>( low_level_batch_start, get_query, params, queryer_options, results)); break; case 1: SCANN_RETURN_IF_ERROR(FindOneLowLevelBatchOfNeighbors<1>( low_level_batch_start, get_query, params, queryer_options, results)); break; default: LOG(FATAL) << "Can't happen"; } low_level_batch_start += low_level_batch_size; } return OkStatus(); } template <typename T> template <size_t kNumQueries, typename PostprocessFunctor> Status Searcher<T>::FindOneLowLevelBatchOfNeighbors( size_t low_level_batch_start, std::function<DatapointPtr<T>(DatapointIndex)> get_query, ConstSpan<SearchParameters> params, const QueryerOptions<PostprocessFunctor>& queryer_options, MutableSpan<NNResultsVector> results) const { std::array<LookupTable, kNumQueries> lookup_storages; std::array<const LookupTable*, kNumQueries> lookup_ptrs; std::array<TopNeighbors<float>, kNumQueries> top_ns_storage; std::array<TopNeighbors<float>*, kNumQueries> top_ns; std::array<const SearchParameters*, kNumQueries> cur_batch_params; for (size_t batch_idx = 0; batch_idx < kNumQueries; ++batch_idx) { TF_ASSIGN_OR_RETURN( lookup_ptrs[batch_idx], GetOrCreateLookupTable(get_query(low_level_batch_start + batch_idx), params[low_level_batch_start + batch_idx], &lookup_storages[batch_idx])); top_ns_storage[batch_idx] = TopNeighbors<float>(params[low_level_batch_start + batch_idx] .pre_reordering_num_neighbors()); top_ns[batch_idx] = &top_ns_storage[batch_idx]; cur_batch_params[batch_idx] = &params[low_level_batch_start + batch_idx]; } SCANN_RETURN_IF_ERROR(AsymmetricQueryer<T>::FindApproximateNeighborsBatched( lookup_ptrs, cur_batch_params, queryer_options, top_ns)); for (size_t batch_idx = 0; batch_idx < kNumQueries; ++batch_idx) { results[low_level_batch_start + batch_idx] = top_ns_storage[batch_idx].ExtractUnsorted(); } return OkStatus(); } template <typename T> StatusOr<unique_ptr<SearcherSpecificOptionalParameters>> PrecomputedAsymmetricLookupTableCreator<T>:: CreateLeafSearcherOptionalParameters(const DatapointPtr<T>& query) const { TF_ASSIGN_OR_RETURN(auto lookup_table, queryer_->CreateLookupTable(query, lookup_type_)); return unique_ptr<SearcherSpecificOptionalParameters>( new AsymmetricHashingOptionalParameters(std::move(lookup_table))); } template <typename T> StatusOr<SingleMachineFactoryOptions> Searcher<T>::ExtractSingleMachineFactoryOptions() { TF_ASSIGN_OR_RETURN( auto opts, SingleMachineSearcherBase<T>::ExtractSingleMachineFactoryOptions()); if (opts_.asymmetric_queryer_) { auto centers = opts_.asymmetric_queryer_->model()->centers(); opts.ah_codebook = std::make_shared<CentersForAllSubspaces>(); *opts.ah_codebook = DatasetSpanToCentersProto(centers, opts_.quantization_scheme()); if (opts_.asymmetric_lookup_type_ == AsymmetricHasherConfig::INT8_LUT16) opts.hashed_dataset = make_shared<DenseDataset<uint8_t>>(UnpackDataset(packed_dataset_)); } return opts; } template Status Searcher<float>::FindNeighborsBatchedInternal< asymmetric_hashing_internal::IdentityPostprocessFunctor>( std::function<DatapointPtr<float>(DatapointIndex)> get_query, ConstSpan<SearchParameters> params, asymmetric_hashing_internal::IdentityPostprocessFunctor postprocessing_functor, MutableSpan<NNResultsVector> results) const; SCANN_INSTANTIATE_TYPED_CLASS(, SearcherOptions); SCANN_INSTANTIATE_TYPED_CLASS(, Searcher); SCANN_INSTANTIATE_TYPED_CLASS(, PrecomputedAsymmetricLookupTableCreator); } // namespace asymmetric_hashing2 } // namespace scann_ops } // namespace tensorflow
40.170996
80
0.708066
[ "model" ]
744bcb7e974585be7a567cc1648377886cd48dda
662
hpp
C++
series2_warmup/2d-poissonlFEM/shape.hpp
westernmagic/NumPDE
98786723b0944d48202f32bc8b9a0185835e03e8
[ "MIT" ]
null
null
null
series2_warmup/2d-poissonlFEM/shape.hpp
westernmagic/NumPDE
98786723b0944d48202f32bc8b9a0185835e03e8
[ "MIT" ]
6
2017-04-01T22:52:16.000Z
2017-04-30T16:21:55.000Z
series2_warmup/2d-poissonlFEM/shape.hpp
westernmagic/NumPDE
98786723b0944d48202f32bc8b9a0185835e03e8
[ "MIT" ]
null
null
null
#pragma once //! The shape function (on the reference element) //! //! We have three shape functions. //! //! lambda(0, x, y) should be 1 in the point (0,0) and zero in (1,0) and (0,1) //! lambda(1, x, y) should be 1 in the point (1,0) and zero in (0,0) and (0,1) //! lambda(2, x, y) should be 1 in the point (0,1) and zero in (0,0) and (1,0) //! //! @param i integer between 0 and 2 (inclusive). Decides which shape function to return. //! @param x x coordinate in the reference element. //! @param y y coordinate in the reference element. inline double lambda(int i, double x, double y) { // (write your solution here) return 0; //remove when implemented }
36.777778
89
0.661631
[ "shape" ]
7455ff586ffc3e391342ca631a1ad27401136834
29,260
cpp
C++
test/unittests/libstorage/test_CachedStorage.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
test/unittests/libstorage/test_CachedStorage.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
test/unittests/libstorage/test_CachedStorage.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
/** * @CopyRight: * FISCO-BCOS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FISCO-BCOS 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 FISCO-BCOS. If not, see <http://www.gnu.org/licenses/> * (c) 2016-2018 fisco-dev contributors. * * @brief * * @file test_CachedStorage.cpp * @author: monan * @date 2019-04-13 */ #include "MemoryStorage2.h" #include <libdevcore/FixedHash.h> #include <libstorage/CachedStorage.h> #include <libstorage/StorageException.h> #include <libstorage/Table.h> #include <tbb/parallel_for.h> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <boost/test/unit_test.hpp> #include <chrono> #include <thread> using namespace dev; using namespace dev::storage; namespace test_CachedStorage { class MockStorage : public Storage { public: Entries::Ptr select(int64_t, TableInfo::Ptr tableInfo, const std::string& key, Condition::Ptr condition) override { if (commited) { BOOST_TEST(false); return nullptr; } auto entries = std::make_shared<Entries>(); BOOST_TEST(condition != nullptr); if (tableInfo->name == SYS_CURRENT_STATE && key == SYS_KEY_CURRENT_ID) { Entry::Ptr entry = std::make_shared<Entry>(); entry->setID(1); entry->setNum(100); entry->setField(SYS_KEY, SYS_KEY_CURRENT_ID); entry->setField(SYS_VALUE, "100"); entry->setStatus(0); entries->addEntry(entry); return entries; } if (tableInfo->name == "t_test") { if (key == "LiSi") { Entry::Ptr entry = std::make_shared<Entry>(); entry->setID(1); entry->setNum(100); entry->setField("Name", "LiSi"); entry->setField("id", "1"); entry->setStatus(0); entries->addEntry(entry); } } return entries; } size_t commit(int64_t num, const std::vector<TableData::Ptr>& datas) override { (void)datas; BOOST_CHECK(num == commitNum); BOOST_CHECK(datas.size() == 1); for (auto it : datas) { if (it->info->name == "t_test") { BOOST_CHECK(it->newEntries->size() == 1); } else if (it->info->name == SYS_CURRENT_STATE) { // BOOST_CHECK(it->dirtyEntries->size() == 1); } else { BOOST_CHECK(false); } } commited = true; return 0; } bool onlyCommitDirty() override { return true; } bool commited = false; int64_t commitNum = 50; }; class MockStorageParallel : public Storage { public: MockStorageParallel() { for (size_t i = 100; i < 200; ++i) { auto tableName = "t_test" + boost::lexical_cast<std::string>(i); Entry::Ptr entry = std::make_shared<Entry>(); entry->setField("Name", "LiSi1"); entry->setField("id", boost::lexical_cast<std::string>(i)); entry->setID(1000 + i); tableKey2Entry.insert(std::make_pair(tableName + entry->getField("Name"), entry)); entry = std::make_shared<Entry>(); entry->setField("Name", "LiSi2"); entry->setField("id", boost::lexical_cast<std::string>(i + 1)); entry->setID(1001 + i); tableKey2Entry.insert(std::make_pair(tableName + entry->getField("Name"), entry)); entry = std::make_shared<Entry>(); entry->setField("Name", "LiSi3"); entry->setField("id", boost::lexical_cast<std::string>(i + 2)); entry->setID(1002 + i); tableKey2Entry.insert(std::make_pair(tableName + entry->getField("Name"), entry)); } } Entries::Ptr select(int64_t num, TableInfo::Ptr tableInfo, const std::string& key, Condition::Ptr condition) override { (void)num; (void)condition; auto tableKey = tableInfo->name + key; auto it = tableKey2Entry.find(tableKey); auto entries = std::make_shared<Entries>(); entries->addEntry(it->second); return entries; } size_t commit(int64_t num, const std::vector<TableData::Ptr>& datas) override { BOOST_CHECK(num == commitNum); BOOST_CHECK(datas.size() == 100); for (size_t i = 0; i < 100; ++i) { auto tableData = datas[i]; BOOST_TEST( tableData->info->name == "t_test" + boost::lexical_cast<std::string>(100 + i)); BOOST_TEST(tableData->dirtyEntries->size() == 3); BOOST_TEST(tableData->newEntries->size() == 3); for (size_t j = 0; j < 3; ++j) { auto entry = tableData->dirtyEntries->get(j); BOOST_TEST(entry->getID() == 1000 + 100 + i + j); BOOST_TEST(entry->getField("id") == boost::lexical_cast<std::string>(i + 100 + j)); BOOST_TEST( entry->getField("Name") == "LiSi" + boost::lexical_cast<std::string>(j + 1)); auto tableKey = tableData->info->name + entry->getField(tableData->info->key); auto it = tableKey2Entry.find(tableKey); BOOST_TEST(entry->getField("Name") == it->second->getField("Name")); BOOST_TEST(entry->getField("id") == it->second->getField("id")); BOOST_TEST(entry->getID() == it->second->getID()); entry = tableData->newEntries->get(j); BOOST_TEST( entry->getField("id") == boost::lexical_cast<std::string>(i + 100 + 100 + j)); // BOOST_TEST(entry->getID() == i * 3 + j + 2); BOOST_TEST(entry->getField("Name") == "ZhangSan"); } } commited = true; return 0; } bool onlyCommitDirty() override { return true; } bool commited = false; int64_t commitNum = 50; tbb::concurrent_unordered_map<std::string, Entry::Ptr> tableKey2Entry; }; struct CachedStorageFixture { CachedStorageFixture() { cachedStorage = std::make_shared<CachedStorage>(); mockStorage = std::make_shared<MockStorage>(); cachedStorage->setBackend(mockStorage); cachedStorage->setMaxForwardBlock(51); } ~CachedStorageFixture() { cachedStorage->stop(); } Entries::Ptr getEntries() { Entries::Ptr entries = std::make_shared<Entries>(); Entry::Ptr entry = std::make_shared<Entry>(); entry->setField("Name", "LiSi"); entry->setField("id", "2"); entries->addEntry(entry); return entries; } dev::storage::CachedStorage::Ptr cachedStorage; std::shared_ptr<MockStorage> mockStorage; }; BOOST_FIXTURE_TEST_SUITE(CachedStorageTest, CachedStorageFixture) BOOST_AUTO_TEST_CASE(onlyDirty) { BOOST_CHECK_EQUAL(cachedStorage->onlyCommitDirty(), true); } BOOST_AUTO_TEST_CASE(setBackend) { auto backend = Storage::Ptr(); cachedStorage->setBackend(backend); } BOOST_AUTO_TEST_CASE(init) { cachedStorage->init(); } BOOST_AUTO_TEST_CASE(empty_select) { cachedStorage->init(); h256 h(0x01); int num = 1; std::string table("t_test"); std::string key("id"); auto tableInfo = std::make_shared<TableInfo>(); tableInfo->name = table; Entries::Ptr entries = cachedStorage->select(num, tableInfo, key, std::make_shared<Condition>()); BOOST_CHECK_EQUAL(entries->size(), 0u); } BOOST_AUTO_TEST_CASE(select_condition) { // query from backend h256 h(0x01); int num = 1; std::string table("t_test"); auto condition = std::make_shared<Condition>(); condition->EQ("id", "2"); auto tableInfo = std::make_shared<TableInfo>(); tableInfo->name = table; Entries::Ptr entries = cachedStorage->select(num, tableInfo, "LiSi", condition); BOOST_CHECK_EQUAL(entries->size(), 0u); // query from cache mockStorage->commited = true; condition = std::make_shared<Condition>(); condition->EQ("id", "1"); tableInfo = std::make_shared<TableInfo>(); tableInfo->name = table; entries = cachedStorage->select(num, tableInfo, "LiSi", condition); BOOST_CHECK_EQUAL(entries->size(), 1u); } BOOST_AUTO_TEST_CASE(commit_single_data) { h256 h; int64_t num = 50; cachedStorage->setMaxForwardBlock(100); std::vector<dev::storage::TableData::Ptr> datas; dev::storage::TableData::Ptr tableData = std::make_shared<dev::storage::TableData>(); tableData->info->name = "t_test"; tableData->info->key = "Name"; tableData->info->fields.push_back("id"); Entries::Ptr entries = getEntries(); tableData->newEntries = entries; datas.push_back(tableData); BOOST_TEST(cachedStorage->syncNum() == 0); mockStorage->commitNum = 50; size_t c = cachedStorage->commit(num, datas); std::this_thread::sleep_for(std::chrono::milliseconds(100)); BOOST_TEST(cachedStorage->syncNum() == 50); BOOST_CHECK_EQUAL(c, 1u); std::string table("t_test"); std::string key("LiSi"); auto tableInfo = std::make_shared<TableInfo>(); tableInfo->name = table; tableInfo->key = "Name"; entries = cachedStorage->select(num, tableInfo, key, std::make_shared<Condition>()); BOOST_CHECK_EQUAL(entries->size(), 2u); for (size_t i = 0; i < entries->size(); ++i) { auto entry = entries->get(i); if (entry->getField("id") == "1") { BOOST_TEST(entry->getID() == 1); } else if (entry->getField("id") == "2") { // BOOST_TEST(entry->getID() == 2); } else { BOOST_TEST(false); } } } BOOST_AUTO_TEST_CASE(commit_multi_data) { h256 h; int64_t num = 50; cachedStorage->setMaxForwardBlock(100); std::vector<dev::storage::TableData::Ptr> datas; dev::storage::TableData::Ptr tableData = std::make_shared<dev::storage::TableData>(); tableData->info->name = "t_test"; tableData->info->key = "Name"; tableData->info->fields.push_back("id"); Entries::Ptr entries = getEntries(); tableData->newEntries = entries; datas.push_back(tableData); BOOST_TEST(cachedStorage->syncNum() == 0); mockStorage->commitNum = 50; size_t c = cachedStorage->commit(num, datas); std::this_thread::sleep_for(std::chrono::milliseconds(100)); BOOST_TEST(cachedStorage->syncNum() == 50); BOOST_CHECK_EQUAL(c, 1u); std::string table("t_test"); std::string key("LiSi"); auto tableInfo = std::make_shared<TableInfo>(); tableInfo->name = table; tableInfo->key = "Name"; entries = cachedStorage->select(num, tableInfo, key, std::make_shared<Condition>()); BOOST_CHECK_EQUAL(entries->size(), 2u); for (size_t i = 0; i < entries->size(); ++i) { auto entry = entries->get(i); if (entry->getField("id") == "1") { BOOST_TEST(entry->getID() == 1); } else if (entry->getField("id") == "2") { // BOOST_TEST(entry->getID() == 2); } else { BOOST_TEST(false); } } } BOOST_AUTO_TEST_CASE(parllel_commit) { h256 h; int64_t num = 50; std::vector<dev::storage::TableData::Ptr> datas; cachedStorage->setMaxForwardBlock(100); for (size_t i = 100; i < 200; ++i) { dev::storage::TableData::Ptr tableData = std::make_shared<dev::storage::TableData>(); tableData->info->name = "t_test" + boost::lexical_cast<std::string>(i); tableData->info->key = "Name"; tableData->info->fields.push_back("id"); Entries::Ptr entries = std::make_shared<Entries>(); Entry::Ptr entry = std::make_shared<Entry>(); entry->setField("Name", "LiSi1"); entry->setField("id", boost::lexical_cast<std::string>(i)); entry->setID(1000 + i); entries->addEntry(entry); entry = std::make_shared<Entry>(); entry->setField("Name", "LiSi2"); entry->setField("id", boost::lexical_cast<std::string>(i + 1)); entry->setID(1001 + i); entries->addEntry(entry); entry = std::make_shared<Entry>(); entry->setField("Name", "LiSi3"); entry->setField("id", boost::lexical_cast<std::string>(i + 2)); entry->setID(1002 + i); entries->addEntry(entry); tableData->dirtyEntries = entries; entries = std::make_shared<Entries>(); entry = std::make_shared<Entry>(); entry->setField("Name", "ZhangSan"); entry->setField("id", boost::lexical_cast<std::string>(i + 100)); entry->setForce(true); entries->addEntry(entry); entry = std::make_shared<Entry>(); entry->setField("Name", "ZhangSan"); entry->setField("id", boost::lexical_cast<std::string>(i + 101)); entry->setForce(true); entries->addEntry(entry); entry = std::make_shared<Entry>(); entry->setField("Name", "ZhangSan"); entry->setField("id", boost::lexical_cast<std::string>(i + 102)); entry->setForce(true); entries->addEntry(entry); tableData->newEntries = entries; datas.push_back(tableData); } cachedStorage->setBackend(std::make_shared<MockStorageParallel>()); BOOST_TEST(cachedStorage->syncNum() == 0); mockStorage->commitNum = 50; size_t c = cachedStorage->commit(num, datas); std::this_thread::sleep_for(std::chrono::milliseconds(100)); BOOST_TEST(cachedStorage->syncNum() == 50); BOOST_CHECK_EQUAL(c, 600u); #if 0 std::string table("t_test"); std::string key("LiSi"); auto tableInfo = std::make_shared<TableInfo>(); tableInfo->name = table; entries = cachedStorage->select(num, tableInfo, key, std::make_shared<Condition>()); BOOST_CHECK_EQUAL(entries->size(), 2u); for (size_t i = 0; i < entries->size(); ++i) { auto entry = entries->get(i); if (entry->getField("id") == "1") { BOOST_TEST(entry->getID() == 1); } else if (entry->getField("id") == "2") { BOOST_TEST(entry->getID() == 2); } else { BOOST_TEST(false); } } #endif } BOOST_AUTO_TEST_CASE(ordered_commit) { cachedStorage->init(); cachedStorage->setBackend(dev::storage::Storage::Ptr()); dev::storage::TableData::Ptr tableData = std::make_shared<dev::storage::TableData>(); tableData->info->name = "t_test"; tableData->info->key = "Name"; tableData->info->fields.push_back("id"); Entries::Ptr entries = std::make_shared<Entries>(); for (size_t i = 0; i < 50; ++i) { boost::random::mt19937 rng; boost::random::uniform_int_distribution<> rand(0, 1000); int num = rand(rng); Entry::Ptr entry = std::make_shared<Entry>(); entry->setField("Name", "node"); entry->setField("id", boost::lexical_cast<std::string>(num)); entries->addEntry(entry); } tableData->newEntries = entries; std::vector<dev::storage::TableData::Ptr> datas; datas.push_back(tableData); cachedStorage->commit(0, datas); auto result = cachedStorage->selectNoCondition(0, tableData->info, "node", std::make_shared<Condition>()); auto cache = std::get<1>(result); ssize_t currentID = -1; for (auto it : *(cache->entries())) { if (currentID == -1) { currentID = it->getID(); } else { BOOST_TEST(currentID <= it->getID()); currentID = it->getID(); } LOG(TRACE) << "CurrentID: " << it->getID(); } } BOOST_AUTO_TEST_CASE(parallel_samekey_commit) { cachedStorage->init(); cachedStorage->setBackend(Storage::Ptr()); auto tableInfo = std::make_shared<TableInfo>(); tableInfo->name = "t_test"; tableInfo->key = "key"; tableInfo->fields.push_back("value"); auto entry = std::make_shared<Entry>(); entry->setField("key", "1"); entry->setField("value", "200"); auto data = std::make_shared<dev::storage::TableData>(); data->newEntries->addEntry(entry); data->info = tableInfo; std::vector<dev::storage::TableData::Ptr> datas; datas.push_back(data); cachedStorage->commit(99, datas); for (size_t i = 0; i < 100; ++i) { auto result = cachedStorage->selectNoCondition(0, tableInfo, "1", dev::storage::Condition::Ptr()); Cache::Ptr caches = std::get<1>(result); BOOST_TEST(caches->key() == "1"); BOOST_TEST(caches->num() == 99); } } BOOST_AUTO_TEST_CASE(checkAndClear) { cachedStorage->setMaxCapacity(0); cachedStorage->setMaxForwardBlock(0); auto backend = std::make_shared<CachedStorage>(); cachedStorage->setBackend(backend); ordered_commit_invoker(); parllel_commit_invoker(); select_condition_invoker(); } BOOST_AUTO_TEST_CASE(dirtyAndNew) { #if 0 cachedStorage->setMaxCapacity(2000 * 1024 * 1024); cachedStorage->setMaxForwardBlock(10000); auto userTable = std::make_shared<TableInfo>(); userTable->key = "key"; userTable->fields.push_back("value"); userTable->name = "_dag_transfer_"; auto txTable = std::make_shared<TableInfo>(); txTable->key = "txhash"; txTable->fields.push_back("number"); txTable->name = "_sys_txhash_2_block_"; TableData::Ptr newUserData = std::make_shared<TableData>(); newUserData->info = userTable; TableData::Ptr newTXData = std::make_shared<TableData>(); newTXData->info = txTable; Entries::Ptr newUser = std::make_shared<Entries>(); Entries::Ptr newTX = std::make_shared<Entries>(); for (auto i = 0; i < 10000; ++i) { Entry::Ptr entry = std::make_shared<Entry>(); entry->setField("key", boost::lexical_cast<std::string>(i)); entry->setField("value", "0"); entry->setForce(true); newUser->addEntry(entry); Entry::Ptr entry2 = std::make_shared<Entry>(); entry2->setField("txhash", boost::lexical_cast<std::string>(i)); entry2->setField("number", "0"); entry2->setForce(true); newTX->addEntry(entry2); } newUserData->newEntries = newUser; newTXData->newEntries = newTX; std::vector<TableData::Ptr> datas = {newUserData, newTXData}; auto c = cachedStorage->commit(1, datas); BOOST_TEST(c == 20000); std::map<int, int> totalCount; for (auto i = 0; i < 100; ++i) { TableData::Ptr updateUserData = std::make_shared<TableData>(); updateUserData->info = userTable; TableData::Ptr newTxData = std::make_shared<TableData>(); newTxData->info = txTable; tbb::parallel_for( tbb::blocked_range<size_t>(0, 10000), [&](const tbb::blocked_range<size_t>& range) { for (size_t j = range.begin(); j < range.end(); ++j) { auto data = cachedStorage->select(i + 2, userTable, boost::lexical_cast<std::string>(j), std::make_shared<Condition>()); BOOST_TEST(data->size() == 1); auto entry = data->get(0); auto value = boost::lexical_cast<int>(entry->getField("value")); entry->setField("value", boost::lexical_cast<std::string>(value + 1)); updateUserData->dirtyEntries->addEntry(entry); auto txEntry = std::make_shared<Entry>(); txEntry->setField("txhash", boost::lexical_cast<std::string>(100000 + i)); txEntry->setField("number", "0"); txEntry->setForce(true); newTxData->newEntries->addEntry(txEntry); } }); auto blockDatas = std::vector<TableData::Ptr>(); blockDatas.push_back(updateUserData); blockDatas.push_back(newTxData); cachedStorage->commit(i + 2, blockDatas); } tbb::parallel_for( tbb::blocked_range<size_t>(0, 10000), [&](const tbb::blocked_range<size_t>& range) { for (size_t i = range.begin(); i < range.end(); ++i) { auto data = cachedStorage->select(1002, userTable, boost::lexical_cast<std::string>(i), std::make_shared<Condition>()); BOOST_TEST(data->size() == 1); auto entry = data->get(0); auto value = boost::lexical_cast<int>(entry->getField("value")); BOOST_TEST(entry->getField("key") == "key"); BOOST_TEST(value == 1000); } }); #endif } class CommitCheckMock : public Storage { public: Entries::Ptr select(int64_t, TableInfo::Ptr tableInfo, const std::string& key, Condition::Ptr condition) override { (void)tableInfo; (void)key; (void)condition; return Entries::Ptr(); } size_t commit(int64_t num, const std::vector<TableData::Ptr>& datas) override { tbb::mutex::scoped_lock lock(m_mutex); if (m_num != 0) { for (size_t i = 0; i < m_datas.size(); ++i) { auto m_tableData = m_datas[i]; auto tableData = datas[i]; BOOST_TEST(m_tableData->info->name == tableData->info->name); BOOST_TEST(m_tableData->info->key == tableData->info->key); BOOST_TEST(m_tableData->info->fields == tableData->info->fields); if (tableData->info->name != "_sys_current_state_") { for (size_t j = 0; j < m_tableData->dirtyEntries->size(); ++j) { auto m_entry = m_tableData->dirtyEntries->get(j); auto entry = tableData->dirtyEntries->get(j); // BOOST_TEST(*(m_entry->fields()) == *(entry->fields())); BOOST_TEST(m_entry->getID() == entry->getID()); BOOST_TEST(m_entry->getStatus() == entry->getStatus()); BOOST_TEST(m_entry->getTempIndex() == entry->getTempIndex()); // BOOST_TEST(m_entry->num() == entry->num()); BOOST_TEST(m_entry->dirty() == entry->dirty()); BOOST_TEST(m_entry->force() == entry->force()); // BOOST_TEST(m_entry->refCount() == entry->refCount()); BOOST_TEST(m_entry->deleted() == entry->deleted()); BOOST_TEST(m_entry->capacity() == entry->capacity()); } } } } m_num = num; m_datas = datas; return 0; } h256 m_hash; int64_t m_num = 0; std::vector<TableData::Ptr> m_datas; tbb::mutex m_mutex; }; BOOST_AUTO_TEST_CASE(commitCheck) { cachedStorage = std::make_shared<CachedStorage>(); cachedStorage->setMaxCapacity(256 * 1024 * 1024); cachedStorage->setMaxForwardBlock(100); auto backend = std::make_shared<CommitCheckMock>(); cachedStorage->setBackend(backend); auto userTable = std::make_shared<TableInfo>(); userTable->key = "key"; userTable->fields.push_back("value"); userTable->name = "_dag_transfer_"; auto txTable = std::make_shared<TableInfo>(); txTable->key = "txhash"; txTable->fields.push_back("number"); txTable->name = "_sys_txhash_2_block_"; TableData::Ptr newUserData = std::make_shared<TableData>(); TableData::Ptr newTXData = std::make_shared<TableData>(); Entries::Ptr newUser = std::make_shared<Entries>(); Entries::Ptr newTX = std::make_shared<Entries>(); for (auto i = 0; i < 100; ++i) { Entry::Ptr entry = std::make_shared<Entry>(); entry->setField("key", boost::lexical_cast<std::string>(i)); entry->setField("value", "value " + boost::lexical_cast<std::string>(i)); entry->setForce(true); entry->setID(i); newUser->addEntry(entry); Entry::Ptr entry2 = std::make_shared<Entry>(); entry2->setField("txhash", boost::lexical_cast<std::string>(i)); entry2->setField("number", boost::lexical_cast<std::string>(i + 100)); entry->setID(100 + i); entry2->setForce(true); newTX->addEntry(entry2); } newUserData->newEntries = newUser; newUserData->info = userTable; newTXData->newEntries = newTX; newTXData->info = txTable; std::vector<TableData::Ptr> datas = {newUserData, newTXData}; cachedStorage->commit(1, datas); for (size_t idx = 0; idx < 100; ++idx) { TableData::Ptr newUserData = std::make_shared<TableData>(); TableData::Ptr newTXData = std::make_shared<TableData>(); Entries::Ptr newUser = std::make_shared<Entries>(); Entries::Ptr newTX = std::make_shared<Entries>(); for (auto i = 0; i < 100; ++i) { auto entries = cachedStorage->select(idx + 1, userTable, boost::lexical_cast<std::string>(i), std::make_shared<Condition>()); auto entry = entries->get(0); entry->setField("key", boost::lexical_cast<std::string>(i)); entry->setField("value", "value " + boost::lexical_cast<std::string>(i)); newUser->addEntry(entry); Entry::Ptr entry2 = std::make_shared<Entry>(); entry2->setField("txhash", boost::lexical_cast<std::string>(i)); entry2->setField("number", boost::lexical_cast<std::string>(i + 100)); newTX->addEntry(entry2); } newUserData->dirtyEntries = newUser; newUserData->info = userTable; newTXData->newEntries = newTX; newTXData->info = txTable; std::vector<TableData::Ptr> datas = {newUserData, newTXData}; cachedStorage->commit(idx + 1, datas); } } BOOST_AUTO_TEST_CASE(clearCommitCheck) { cachedStorage = std::make_shared<CachedStorage>(); cachedStorage->setMaxCapacity(256 * 1024 * 1024); cachedStorage->setMaxForwardBlock(100); auto backend = std::make_shared<MemoryStorage2>(); cachedStorage->setBackend(backend); cachedStorage->setMaxCapacity(10); // byte cachedStorage->setClearInterval(1); // ms cachedStorage->startClearThread(); auto userTable = std::make_shared<TableInfo>(); userTable->key = "key"; userTable->fields.push_back("value"); userTable->name = "t_multi_entry"; auto txTable = std::make_shared<TableInfo>(); txTable->key = "txhash"; txTable->fields.push_back("number"); txTable->name = "txTable"; TableData::Ptr newUserData = std::make_shared<TableData>(); TableData::Ptr newTXData = std::make_shared<TableData>(); Entries::Ptr newUser = std::make_shared<Entries>(); Entries::Ptr newTX = std::make_shared<Entries>(); for (auto i = 0; i < 10; ++i) { Entry::Ptr entry = std::make_shared<Entry>(); entry->setField("key", boost::lexical_cast<std::string>(1)); entry->setField("value", "value " + boost::lexical_cast<std::string>(i)); entry->setID(i); newUser->addEntry(entry); Entry::Ptr entry2 = std::make_shared<Entry>(); entry2->setField("txhash", boost::lexical_cast<std::string>(1)); entry2->setField("number", boost::lexical_cast<std::string>(i + 100)); entry->setID(100000 + i); newTX->addEntry(entry2); } newUserData->newEntries = newUser; newUserData->info = userTable; newTXData->newEntries = newTX; newTXData->info = txTable; std::vector<TableData::Ptr> datas = {newUserData, newTXData}; cachedStorage->commit(1, datas); newUserData->dirtyEntries = newUser; newUserData->newEntries = std::make_shared<Entries>(); newUserData->dirtyEntries = newUser; for (auto i = 2; i < 10; ++i) { cachedStorage->commit(i, datas); } cachedStorage->stop(); } BOOST_AUTO_TEST_CASE(exception) { #if 0 h256 h(0x01); int num = 1; h256 blockHash(0x11231); std::vector<dev::storage::TableData::Ptr> datas; dev::storage::TableData::Ptr tableData = std::make_shared<dev::storage::TableData>(); tableData->info->name = "e"; tableData->info->key = "Name"; tableData->info->fields.push_back("id"); Entries::Ptr entries = getEntries(); entries->get(0)->setField("Name", "Exception"); tableData->entries = entries; datas.push_back(tableData); BOOST_CHECK_THROW(AMOP->commit(num, datas, blockHash), boost::exception); std::string table("e"); std::string key("Exception"); BOOST_CHECK_THROW(AMOP->select(num, table, key, std::make_shared<Condition>()), boost::exception); #endif } BOOST_AUTO_TEST_SUITE_END() } // namespace test_CachedStorage
31.978142
102
0.59337
[ "vector" ]
7457e6a88d40a2947d1be795cf7e1b70361fbf89
25,575
cpp
C++
Source/Engine/Renderer/CanvasRenderer.cpp
CodeLikeCXK/AngieEngine
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
[ "MIT" ]
24
2019-07-15T22:48:44.000Z
2021-11-02T04:42:48.000Z
Source/Engine/Renderer/CanvasRenderer.cpp
CodeLikeCXK/AngieEngine
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
[ "MIT" ]
1
2021-11-02T09:41:31.000Z
2021-11-05T18:35:14.000Z
Source/Engine/Renderer/CanvasRenderer.cpp
CodeLikeCXK/AngieEngine
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
[ "MIT" ]
3
2020-02-03T08:34:50.000Z
2021-07-28T05:19:22.000Z
/* Angie Engine Source Code MIT License Copyright (C) 2017-2021 Alexander Samusev. This file is part of the Angie Engine Source Code. 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 "CanvasRenderer.h" #include "RenderLocal.h" #include <Runtime/Public/Runtime.h> using namespace RenderCore; ACanvasRenderer::ACanvasRenderer() { GDevice->CreateResourceTable( &ResourceTable ); // // Create pipelines // CreatePresentViewPipeline(); CreatePipelines(); } void ACanvasRenderer::CreatePresentViewPipeline() { SPipelineDesc pipelineCI; SRasterizerStateInfo & rsd = pipelineCI.RS; rsd.CullMode = POLYGON_CULL_DISABLED; rsd.bScissorEnable = true; SDepthStencilStateInfo & dssd = pipelineCI.DSS; dssd.bDepthEnable = false; dssd.bDepthWrite = false; static const SVertexAttribInfo vertexAttribs[] = { { "InPosition", 0, // location 0, // buffer input slot VAT_FLOAT2, VAM_FLOAT, 0, // InstanceDataStepRate AN_OFS( SHUDDrawVert, Position ) }, { "InTexCoord", 1, // location 0, // buffer input slot VAT_FLOAT2, VAM_FLOAT, 0, // InstanceDataStepRate AN_OFS( SHUDDrawVert, TexCoord ) }, { "InColor", 2, // location 0, // buffer input slot VAT_UBYTE4N, VAM_FLOAT, 0, // InstanceDataStepRate AN_OFS( SHUDDrawVert, Color ) } }; CreateVertexShader( "canvas/presentview.vert", vertexAttribs, AN_ARRAY_SIZE( vertexAttribs ), pipelineCI.pVS ); CreateFragmentShader( "canvas/presentview.frag", pipelineCI.pFS ); SPipelineInputAssemblyInfo & inputAssembly = pipelineCI.IA; inputAssembly.Topology = PRIMITIVE_TRIANGLES; SVertexBindingInfo vertexBinding[1] = {}; vertexBinding[0].InputSlot = 0; vertexBinding[0].Stride = sizeof( SHUDDrawVert ); vertexBinding[0].InputRate = INPUT_RATE_PER_VERTEX; pipelineCI.NumVertexBindings = AN_ARRAY_SIZE( vertexBinding ); pipelineCI.pVertexBindings = vertexBinding; pipelineCI.NumVertexAttribs = AN_ARRAY_SIZE( vertexAttribs ); pipelineCI.pVertexAttribs = vertexAttribs; SSamplerDesc samplerCI; samplerCI.Filter = FILTER_NEAREST;//FILTER_LINEAR;//FILTER_NEAREST; // linear is better for dynamic resolution samplerCI.AddressU = SAMPLER_ADDRESS_CLAMP; samplerCI.AddressV = SAMPLER_ADDRESS_CLAMP; samplerCI.AddressW = SAMPLER_ADDRESS_CLAMP; pipelineCI.ResourceLayout.NumSamplers = 1; pipelineCI.ResourceLayout.Samplers = &samplerCI; SBufferInfo bufferInfo; bufferInfo.BufferBinding = BUFFER_BIND_CONSTANT; pipelineCI.ResourceLayout.NumBuffers = 1; pipelineCI.ResourceLayout.Buffers = &bufferInfo; for ( int i = 0 ; i < COLOR_BLENDING_MAX ; i++ ) { if ( i == COLOR_BLENDING_DISABLED ) { pipelineCI.BS.RenderTargetSlots[0].SetBlendingPreset( BLENDING_NO_BLEND ); } else if ( i == COLOR_BLENDING_ALPHA ) { pipelineCI.BS.RenderTargetSlots[0].SetBlendingPreset( BLENDING_ALPHA ); } else { pipelineCI.BS.RenderTargetSlots[0].SetBlendingPreset( (BLENDING_PRESET)(BLENDING_NO_BLEND + i) ); } GDevice->CreatePipeline( pipelineCI, &PresentViewPipeline[i] ); } } void ACanvasRenderer::CreatePipelines() { SPipelineDesc pipelineCI; SRasterizerStateInfo & rsd = pipelineCI.RS; rsd.CullMode = POLYGON_CULL_DISABLED; rsd.bScissorEnable = true; SDepthStencilStateInfo & dssd = pipelineCI.DSS; dssd.bDepthEnable = false; dssd.bDepthWrite = false; static const SVertexAttribInfo vertexAttribs[] = { { "InPosition", 0, // location 0, // buffer input slot VAT_FLOAT2, VAM_FLOAT, 0, // InstanceDataStepRate AN_OFS( SHUDDrawVert, Position ) }, { "InTexCoord", 1, // location 0, // buffer input slot VAT_FLOAT2, VAM_FLOAT, 0, // InstanceDataStepRate AN_OFS( SHUDDrawVert, TexCoord ) }, { "InColor", 2, // location 0, // buffer input slot VAT_UBYTE4N, VAM_FLOAT, 0, // InstanceDataStepRate AN_OFS( SHUDDrawVert, Color ) } }; TRef< IShaderModule > vertexShaderModule, fragmentShaderModule; CreateVertexShader( "canvas/canvas.vert", vertexAttribs, AN_ARRAY_SIZE( vertexAttribs ), vertexShaderModule ); CreateFragmentShader( "canvas/canvas.frag", fragmentShaderModule ); SPipelineInputAssemblyInfo & inputAssembly = pipelineCI.IA; inputAssembly.Topology = PRIMITIVE_TRIANGLES; pipelineCI.pVS = vertexShaderModule; pipelineCI.pFS = fragmentShaderModule; SVertexBindingInfo vertexBinding[1] = {}; vertexBinding[0].InputSlot = 0; vertexBinding[0].Stride = sizeof( SHUDDrawVert ); vertexBinding[0].InputRate = INPUT_RATE_PER_VERTEX; pipelineCI.NumVertexBindings = AN_ARRAY_SIZE( vertexBinding ); pipelineCI.pVertexBindings = vertexBinding; pipelineCI.NumVertexAttribs = AN_ARRAY_SIZE( vertexAttribs ); pipelineCI.pVertexAttribs = vertexAttribs; SSamplerDesc samplerCI; pipelineCI.ResourceLayout.NumSamplers = 1; pipelineCI.ResourceLayout.Samplers = &samplerCI; SBufferInfo bufferInfo; bufferInfo.BufferBinding = BUFFER_BIND_CONSTANT; pipelineCI.ResourceLayout.NumBuffers = 1; pipelineCI.ResourceLayout.Buffers = &bufferInfo; for ( int i = 0 ; i < COLOR_BLENDING_MAX ; i++ ) { if ( i == COLOR_BLENDING_DISABLED ) { pipelineCI.BS.RenderTargetSlots[0].SetBlendingPreset( BLENDING_NO_BLEND ); } else if ( i == COLOR_BLENDING_ALPHA ) { pipelineCI.BS.RenderTargetSlots[0].SetBlendingPreset( BLENDING_ALPHA ); } else { pipelineCI.BS.RenderTargetSlots[0].SetBlendingPreset( (BLENDING_PRESET)(BLENDING_NO_BLEND + i) ); } for ( int j = 0 ; j < HUD_SAMPLER_MAX ; j++ ) { samplerCI.Filter = (j & 1) ? FILTER_NEAREST : FILTER_LINEAR; samplerCI.AddressU = samplerCI.AddressV = samplerCI.AddressW = (SAMPLER_ADDRESS_MODE)(j >> 1); GDevice->CreatePipeline( pipelineCI, &Pipelines[i][j] ); } } } void ACanvasRenderer::Render(AFrameGraph& FrameGraph, TPodVector<FGTextureProxy*>& pRenderViewTexture, ITexture* pBackBuffer) { if ( !GFrameData->DrawListHead ) { return; } ARenderPass& pass = FrameGraph.AddTask<ARenderPass>("Draw HUD"); for ( int i = 0 ; i < GFrameData->NumViews ; i++ ) { pass.AddResource(pRenderViewTexture[i], FG_RESOURCE_ACCESS_READ); } FGTextureProxy* SwapChainColorBuffer = FrameGraph.AddExternalResource<FGTextureProxy>("SwapChainColorAttachment", pBackBuffer); pass.SetColorAttachment(STextureAttachment(SwapChainColorBuffer) .SetLoadOp(ATTACHMENT_LOAD_OP_LOAD)); pass.SetRenderArea(GFrameData->CanvasWidth, GFrameData->CanvasHeight); pass.AddSubpass({0}, [this, pRenderViewTexture](ARenderPassContext& RenderPassContext, ACommandBuffer& CommandBuffer) { struct SCanvasConstants { Float4x4 OrthoProjection; }; struct SCanvasBinding { size_t Offset; size_t Size; }; SCanvasBinding canvasBinding; AStreamedMemoryGPU* streamedMemory = GRuntime->GetStreamedMemoryGPU(); canvasBinding.Size = sizeof(SCanvasConstants); canvasBinding.Offset = streamedMemory->AllocateConstant(canvasBinding.Size); void* pMemory = streamedMemory->Map(canvasBinding.Offset); SCanvasConstants* pCanvasCBuf = (SCanvasConstants*)pMemory; pCanvasCBuf->OrthoProjection = GFrameData->CanvasOrthoProjection; SRect2D scissorRect; SDrawIndexedCmd drawCmd; drawCmd.InstanceCount = 1; drawCmd.StartInstanceLocation = 0; drawCmd.BaseVertexLocation = 0; rcmd->BindResourceTable(ResourceTable); for (SHUDDrawList* drawList = GFrameData->DrawListHead; drawList; drawList = drawList->pNext) { // Process render commands for (SHUDDrawCmd* cmd = drawList->Commands; cmd < &drawList->Commands[drawList->CommandsCount]; cmd++) { switch (cmd->Type) { case HUD_DRAW_CMD_VIEWPORT: { // Draw just rendered scene on the canvas rcmd->BindPipeline(PresentViewPipeline[cmd->Blending]); rcmd->BindVertexBuffer(0, GStreamBuffer, drawList->VertexStreamOffset); rcmd->BindIndexBuffer(GStreamBuffer, INDEX_TYPE_UINT16, drawList->IndexStreamOffset); // Use constant buffer from rendered view ResourceTable->BindBuffer(0, GStreamBuffer, GRenderViewContext[cmd->ViewportIndex].ViewConstantBufferBindingBindingOffset, GRenderViewContext[cmd->ViewportIndex].ViewConstantBufferBindingBindingSize); // Set texture ResourceTable->BindTexture(0, pRenderViewTexture[cmd->ViewportIndex]->Actual()); scissorRect.X = cmd->ClipMins.X; scissorRect.Y = cmd->ClipMins.Y; scissorRect.Width = cmd->ClipMaxs.X - cmd->ClipMins.X; scissorRect.Height = cmd->ClipMaxs.Y - cmd->ClipMins.Y; rcmd->SetScissor(scissorRect); drawCmd.IndexCountPerInstance = cmd->IndexCount; drawCmd.StartIndexLocation = cmd->StartIndexLocation; drawCmd.BaseVertexLocation = cmd->BaseVertexLocation; rcmd->Draw(&drawCmd); break; } case HUD_DRAW_CMD_MATERIAL: { AN_ASSERT(cmd->MaterialFrameData); AMaterialGPU* pMaterial = cmd->MaterialFrameData->Material; AN_ASSERT(pMaterial->MaterialType == MATERIAL_TYPE_HUD); rcmd->BindPipeline(pMaterial->HUDPipeline); rcmd->BindVertexBuffer(0, GStreamBuffer, drawList->VertexStreamOffset); rcmd->BindIndexBuffer(GStreamBuffer, INDEX_TYPE_UINT16, drawList->IndexStreamOffset); // Set constant buffer ResourceTable->BindBuffer(0, GStreamBuffer, canvasBinding.Offset, canvasBinding.Size); BindTextures(ResourceTable, cmd->MaterialFrameData, cmd->MaterialFrameData->NumTextures); // FIXME: What about material constants? scissorRect.X = cmd->ClipMins.X; scissorRect.Y = cmd->ClipMins.Y; scissorRect.Width = cmd->ClipMaxs.X - cmd->ClipMins.X; scissorRect.Height = cmd->ClipMaxs.Y - cmd->ClipMins.Y; rcmd->SetScissor(scissorRect); drawCmd.IndexCountPerInstance = cmd->IndexCount; drawCmd.StartIndexLocation = cmd->StartIndexLocation; drawCmd.BaseVertexLocation = cmd->BaseVertexLocation; rcmd->Draw(&drawCmd); break; } default: { IPipeline* pPipeline = Pipelines[cmd->Blending][cmd->SamplerType]; rcmd->BindPipeline(pPipeline); rcmd->BindVertexBuffer(0, GStreamBuffer, drawList->VertexStreamOffset); rcmd->BindIndexBuffer(GStreamBuffer, INDEX_TYPE_UINT16, drawList->IndexStreamOffset); // Set constant buffer ResourceTable->BindBuffer(0, GStreamBuffer, canvasBinding.Offset, canvasBinding.Size); // Set texture ResourceTable->BindTexture(0, cmd->Texture); scissorRect.X = cmd->ClipMins.X; scissorRect.Y = cmd->ClipMins.Y; scissorRect.Width = cmd->ClipMaxs.X - cmd->ClipMins.X; scissorRect.Height = cmd->ClipMaxs.Y - cmd->ClipMins.Y; rcmd->SetScissor(scissorRect); drawCmd.IndexCountPerInstance = cmd->IndexCount; drawCmd.StartIndexLocation = cmd->StartIndexLocation; drawCmd.BaseVertexLocation = cmd->BaseVertexLocation; rcmd->Draw(&drawCmd); break; } } } } }); #if 0 std::function<void(SHUDDrawList*, SHUDDrawCmd*, FGTextureProxy*)> ProcessDrawLists = [&](SHUDDrawList* drawList, SHUDDrawCmd* cmd, FGTextureProxy* pViewTexture) { AN_ASSERT(drawList); FGTextureProxy* SwapChainColorBuffer = FrameGraph.AddTextureView("SwapChainColorAttachment", pBackBufferRTV); ARenderPass& pass = FrameGraph.AddTask<ARenderPass>("Draw HUD"); if (pViewTexture) pass.AddResource(pViewTexture, FG_RESOURCE_ACCESS_READ); pass.SetColorAttachment(STextureAttachment(SwapChainColorBuffer) .SetLoadOp(ATTACHMENT_LOAD_OP_LOAD)); pass.SetRenderArea(GFrameData->CanvasWidth, GFrameData->CanvasHeight); pass.AddSubpass( {0}, [this, cmd, drawList, pViewTexture, canvasBinding](ARenderPassContext& RenderPassContext, ACommandBuffer& CommandBuffer) { SRect2D scissorRect; SDrawIndexedCmd drawCmd; drawCmd.InstanceCount = 1; drawCmd.StartInstanceLocation = 0; drawCmd.BaseVertexLocation = 0; rcmd->BindResourceTable(ResourceTable); SHUDDrawCmd* curCmd = cmd; if (pViewTexture) { // Draw just rendered scene on the canvas rcmd->BindPipeline(PresentViewPipeline[curCmd->Blending]); rcmd->BindVertexBuffer(0, GStreamBuffer, drawList->VertexStreamOffset); rcmd->BindIndexBuffer(GStreamBuffer, INDEX_TYPE_UINT16, drawList->IndexStreamOffset); // Use constant buffer from rendered view ResourceTable->BindBuffer(0, GStreamBuffer, GViewConstantBufferBindingBindingOffset, GViewConstantBufferBindingBindingSize); // Set texture ResourceTable->BindTexture(0, pViewTexture->Actual()); scissorRect.X = curCmd->ClipMins.X; scissorRect.Y = curCmd->ClipMins.Y; scissorRect.Width = curCmd->ClipMaxs.X - curCmd->ClipMins.X; scissorRect.Height = curCmd->ClipMaxs.Y - curCmd->ClipMins.Y; rcmd->SetScissor(scissorRect); drawCmd.IndexCountPerInstance = curCmd->IndexCount; drawCmd.StartIndexLocation = curCmd->StartIndexLocation; drawCmd.BaseVertexLocation = curCmd->BaseVertexLocation; rcmd->Draw(&drawCmd); // Switch to next cmd curCmd++; } SHUDDrawList* curDrawList = drawList; for (; curDrawList; curDrawList = curDrawList->pNext) { // Process render commands for (; curCmd < &curDrawList->Commands[curDrawList->CommandsCount] && curCmd->Type != HUD_DRAW_CMD_VIEWPORT; curCmd++) { switch (curCmd->Type) { case HUD_DRAW_CMD_MATERIAL: { AN_ASSERT(curCmd->MaterialFrameData); AMaterialGPU* pMaterial = curCmd->MaterialFrameData->Material; AN_ASSERT(pMaterial->MaterialType == MATERIAL_TYPE_HUD); rcmd->BindPipeline(pMaterial->HUDPipeline); rcmd->BindVertexBuffer(0, GStreamBuffer, curDrawList->VertexStreamOffset); rcmd->BindIndexBuffer(GStreamBuffer, INDEX_TYPE_UINT16, curDrawList->IndexStreamOffset); // Set constant buffer ResourceTable->BindBuffer(0, GStreamBuffer, canvasBinding.Offset, canvasBinding.Size); BindTextures(ResourceTable, curCmd->MaterialFrameData, curCmd->MaterialFrameData->NumTextures); // FIXME: What about material constants? scissorRect.X = curCmd->ClipMins.X; scissorRect.Y = curCmd->ClipMins.Y; scissorRect.Width = curCmd->ClipMaxs.X - curCmd->ClipMins.X; scissorRect.Height = curCmd->ClipMaxs.Y - curCmd->ClipMins.Y; rcmd->SetScissor(scissorRect); drawCmd.IndexCountPerInstance = curCmd->IndexCount; drawCmd.StartIndexLocation = curCmd->StartIndexLocation; drawCmd.BaseVertexLocation = curCmd->BaseVertexLocation; rcmd->Draw(&drawCmd); break; } default: { IPipeline* pPipeline = Pipelines[curCmd->Blending][curCmd->SamplerType]; rcmd->BindPipeline(pPipeline); rcmd->BindVertexBuffer(0, GStreamBuffer, curDrawList->VertexStreamOffset); rcmd->BindIndexBuffer(GStreamBuffer, INDEX_TYPE_UINT16, curDrawList->IndexStreamOffset); // Set constant buffer ResourceTable->BindBuffer(0, GStreamBuffer, canvasBinding.Offset, canvasBinding.Size); // Set texture ResourceTable->BindTexture(0, curCmd->Texture); scissorRect.X = curCmd->ClipMins.X; scissorRect.Y = curCmd->ClipMins.Y; scissorRect.Width = curCmd->ClipMaxs.X - curCmd->ClipMins.X; scissorRect.Height = curCmd->ClipMaxs.Y - curCmd->ClipMins.Y; rcmd->SetScissor(scissorRect); drawCmd.IndexCountPerInstance = curCmd->IndexCount; drawCmd.StartIndexLocation = curCmd->StartIndexLocation; drawCmd.BaseVertexLocation = curCmd->BaseVertexLocation; rcmd->Draw(&drawCmd); break; } } } if (curCmd < &curDrawList->Commands[curDrawList->CommandsCount] && curCmd->Type == HUD_DRAW_CMD_VIEWPORT) { break; } } } ); if (drawList && cmd < &drawList->Commands[drawList->CommandsCount] && cmd->Type == HUD_DRAW_CMD_VIEWPORT) { // Render scene to viewport AN_ASSERT(cmd->ViewportIndex >= 0 && cmd->ViewportIndex < GFrameData->NumViews); SRenderView* pRenderView = &GFrameData->RenderViews[cmd->ViewportIndex]; FGTextureProxy* pTexture = nullptr; RenderViewCB(pRenderView, &pTexture); ProcessDrawLists(drawList, cmd, pTexture); } }; if (GFrameData->DrawListHead) { ProcessDrawLists(GFrameData->DrawListHead, GFrameData->DrawListHead->Commands, nullptr); } #endif }
46.16426
164
0.491691
[ "render" ]
7460b6cc08bf4a46e4262c7992ef0f32b64ed566
2,176
cc
C++
multiSeg/src/vector.cc
vishalanand/MultiSeg
100318f18e61e53e2d5694ec6af600be0eec363f
[ "MIT" ]
1
2020-09-30T14:45:45.000Z
2020-09-30T14:45:45.000Z
multiSeg/src/vector.cc
vishalanand/MultiSeg
100318f18e61e53e2d5694ec6af600be0eec363f
[ "MIT" ]
null
null
null
multiSeg/src/vector.cc
vishalanand/MultiSeg
100318f18e61e53e2d5694ec6af600be0eec363f
[ "MIT" ]
null
null
null
/** * Copyright (c) 2019-present, Vishal Anand * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "vector.h" #include "matrix.h" namespace parfasttext { Vector::Vector(int64_t m) : data_(m) {} Vector::Vector(Vector&& other) noexcept : data_(std::move(other.data_)) {} Vector& Vector::operator=(Vector&& other) { data_ = std::move(other.data_); return *this; } void Vector::zero() { std::fill(data_.begin(), data_.end(), 0.0); } void Vector::mul(real a) { for (int64_t i = 0; i < size(); i++) { data_[i] *= a; } } void Vector::addRow_bilingual(const Matrix& A, int64_t i, const Matrix& other_subword_model_A) { //void Vector::addRow_bilingual(const Matrix& A, int64_t i) { assert(i >= 0); //assert(i < A.size(0)); assert(i < other_subword_model_A.size(0)); assert(size() == other_subword_model_A.size(1)); assert(size() == A.size(1)); //A.size(0) may not be equal to other_subword_model_A.size(0) //A.size(1) == other_subword_model_A.size(1) //std::cout << "Vector add-row" << std::endl; for (int64_t j = 0; j < A.size(1); j++) { //data_[j] += A.at(i, j); data_[j] += other_subword_model_A.at(i, j); } } void Vector::addRow(const Matrix& A, int64_t i) { assert(i >= 0); assert(i < A.size(0)); assert(size() == A.size(1)); for (int64_t j = 0; j < A.size(1); j++) { data_[j] += A.at(i, j); } } void Vector::addRow(const Matrix& A, int64_t i, real a) { assert(i >= 0); assert(i < A.size(0)); assert(size() == A.size(1)); for (int64_t j = 0; j < A.size(1); j++) { data_[j] += a * A.at(i, j); } } std::ostream& operator<<(std::ostream& os, const Vector& v) { os << std::setprecision(5); for (int64_t j = 0; j < v.size(); j++) { os << v[j] << ' '; } return os; } std::istream& operator>>(std::istream& is, Vector& v) { for (int64_t j = 0; j < v.size(); j++) { is >> v[j]; } return is; } //void Vector::readVector(std::istream& is, Vector& v) { // for (int64_t j = 0; j < v.size(); j++) { // is >> v[j]; // } // return is; //} } // namespace parfasttext
23.652174
96
0.588235
[ "vector" ]
7464c2ebf463a06a5fb8106eff99593f6ed9536c
48,258
cc
C++
chromeos/printing/ppd_provider_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
chromeos/printing/ppd_provider_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chromeos/printing/ppd_provider_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 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 "chromeos/printing/ppd_provider.h" #include <algorithm> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" #include "base/task/single_thread_task_runner.h" #include "base/test/bind.h" #include "base/test/simple_test_clock.h" #include "base/test/task_environment.h" #include "base/test/test_message_loop.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" #include "base/version.h" #include "chromeos/printing/fake_printer_config_cache.h" #include "chromeos/printing/ppd_cache.h" #include "chromeos/printing/ppd_metadata_manager.h" #include "chromeos/printing/printer_config_cache.h" #include "chromeos/printing/printer_configuration.h" #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace { using PrinterDiscoveryType = PrinterSearchData::PrinterDiscoveryType; using ::testing::AllOf; using ::testing::Eq; using ::testing::Field; using ::testing::StrEq; using ::testing::UnorderedElementsAre; // A pseudo-ppd that should get cupsFilter lines extracted from it. const char kCupsFilterPpdContents[] = R"( Other random contents that we don't care about. *cupsFilter: "application/vnd.cups-raster 0 my_filter" More random contents that we don't care about *cupsFilter: "application/vnd.cups-awesome 0 a_different_filter" *cupsFilter: "application/vnd.cups-awesomesauce 0 filter3" Yet more randome contents that we don't care about. More random contents that we don't care about. )"; // A pseudo-ppd that should get cupsFilter2 lines extracted from it. // We also have cupsFilter lines in here, but since cupsFilter2 lines // exist, the cupsFilter lines should be ignored. const char kCupsFilter2PpdContents[] = R"( Other random contents that we don't care about. *cupsFilter: "application/vnd.cups-raster 0 my_filter" More random contents that we don't care about *cupsFilter2: "foo bar 0 the_real_filter" *cupsFilter2: "bar baz 381 another_real_filter" Yet more randome contents that we don't care about. More random contents that we don't care about. )"; // Known number of public method calls that the PpdProvider will defer // before posting failures directly. // * This value is left unspecified in the header. // * This value must be kept in sync with the exact value in the // implementation of PpdProvider. constexpr int kMethodDeferralLimitForTesting = 20; // Default manufacturers metadata used for these tests. const char kDefaultManufacturersJson[] = R"({ "filesMap": { "Manufacturer A": "manufacturer_a-en.json", "Manufacturer B": "manufacturer_b-en.json" } })"; // Unowned raw pointers to helper classes composed into the // PpdProvider at construct time. Used throughout to activate testing // codepaths. struct PpdProviderComposedMembers { FakePrinterConfigCache* config_cache = nullptr; FakePrinterConfigCache* manager_config_cache = nullptr; PpdMetadataManager* metadata_manager = nullptr; }; class PpdProviderTest : public ::testing::Test { public: // * Determines where the PpdCache class runs. // * If set to kOnTestThread, the PpdCache class will use the // task environment of the test fixture. // * If set to kInBackgroundThreads, the PpdCache class will // spawn its own background threads. // * Prefer only to run cache on the test thread if you need to // manipulate its sequencing independently of PpdProvider; // otherwise, allowing it spawn its own background threads // should be safe and good for exercising its codepaths. enum class PpdCacheRunLocation { kOnTestThread, kInBackgroundThreads, }; // * Determines whether the browser locale given to PpdProvider // should be propagated to the composed PpdMetadataManager as its // metadata locale as well. // * Useful to the caller depending on whether or not one is // interested in the codepaths that fetch and parse the locales // metadata. enum class PropagateLocaleToMetadataManager { kDoNotPropagate, kDoPropagate, }; // Options passed to CreateProvider(). struct CreateProviderOptions { std::string browser_locale; PpdCacheRunLocation where_ppd_cache_runs; PropagateLocaleToMetadataManager propagate_locale; }; PpdProviderTest() : task_environment_(base::test::TaskEnvironment::MainThreadType::IO, base::test::TaskEnvironment::TimeSource::MOCK_TIME) {} void SetUp() override { ASSERT_TRUE(ppd_cache_temp_dir_.CreateUniqueTempDir()); } // Creates and return a provider for a test that uses the given |options|. scoped_refptr<PpdProvider> CreateProvider( const CreateProviderOptions& options) { switch (options.where_ppd_cache_runs) { case PpdCacheRunLocation::kOnTestThread: ppd_cache_ = PpdCache::CreateForTesting( ppd_cache_temp_dir_.GetPath(), task_environment_.GetMainThreadTaskRunner()); break; case PpdCacheRunLocation::kInBackgroundThreads: default: ppd_cache_ = PpdCache::Create(ppd_cache_temp_dir_.GetPath()); break; } auto manager_config_cache = std::make_unique<FakePrinterConfigCache>(); provider_backdoor_.manager_config_cache = manager_config_cache.get(); auto manager = PpdMetadataManager::Create(options.browser_locale, &clock_, std::move(manager_config_cache)); provider_backdoor_.metadata_manager = manager.get(); switch (options.propagate_locale) { case PropagateLocaleToMetadataManager::kDoNotPropagate: // Nothing to do; the no-propagate case allows the // PpdMetadataManager to acquire the metadata locale (or fail to // do so) by natural means. break; case PropagateLocaleToMetadataManager::kDoPropagate: default: provider_backdoor_.metadata_manager->SetLocaleForTesting( options.browser_locale); break; } auto config_cache = std::make_unique<FakePrinterConfigCache>(); provider_backdoor_.config_cache = config_cache.get(); return PpdProvider::Create(base::Version("40.8.6753.09"), ppd_cache_, std::move(manager), std::move(config_cache)); } // Fills the fake Chrome OS Printing serving root with content. // Must be called after CreateProvider(). void StartFakePpdServer() { for (const auto& entry : server_contents()) { provider_backdoor_.config_cache->SetFetchResponseForTesting(entry.first, entry.second); provider_backdoor_.manager_config_cache->SetFetchResponseForTesting( entry.first, entry.second); } } // Interceptor posts a *task* during destruction that actually unregisters // things. So we have to run the message loop post-interceptor-destruction to // actually unregister the URLs, otherwise they won't *actually* be // unregistered until the next time we invoke the message loop. Which may be // in the middle of the next test. // // Note this is harmless to call if we haven't started a fake ppd server. void StopFakePpdServer() { for (const auto& entry : server_contents()) { provider_backdoor_.config_cache->Drop(entry.first); provider_backdoor_.manager_config_cache->Drop(entry.first); } task_environment_.RunUntilIdle(); } // Capture the result of a ResolveManufacturers() call. void CaptureResolveManufacturers(PpdProvider::CallbackResultCode code, const std::vector<std::string>& data) { captured_resolve_manufacturers_.push_back({code, data}); } // Capture the result of a ResolvePrinters() call. void CaptureResolvePrinters(PpdProvider::CallbackResultCode code, const PpdProvider::ResolvedPrintersList& data) { captured_resolve_printers_.push_back({code, data}); } // Capture the result of a ResolvePpd() call. void CaptureResolvePpd(PpdProvider::CallbackResultCode code, const std::string& ppd_contents) { CapturedResolvePpdResults results; results.code = code; results.ppd_contents = ppd_contents; captured_resolve_ppd_.push_back(results); } // Capture the result of a ResolveUsbIds() call. void CaptureResolvePpdReference(PpdProvider::CallbackResultCode code, const Printer::PpdReference& ref, const std::string& usb_manufacturer) { captured_resolve_ppd_references_.push_back({code, ref, usb_manufacturer}); } // Capture the result of a ResolvePpdLicense() call. void CaptureResolvePpdLicense(PpdProvider::CallbackResultCode code, const std::string& license) { captured_resolve_ppd_license_.push_back({code, license}); } void CaptureReverseLookup(PpdProvider::CallbackResultCode code, const std::string& manufacturer, const std::string& model) { captured_reverse_lookup_.push_back({code, manufacturer, model}); } // Discard the result of a ResolvePpd() call. void DiscardResolvePpd(PpdProvider::CallbackResultCode code, const std::string& contents) {} // Calls the ResolveManufacturer() method of the |provider| and // waits for its completion. Ignores the returned string values and // returns whether the result code was // PpdProvider::CallbackResultCode::SUCCESS. bool SuccessfullyResolveManufacturers(PpdProvider* provider) { base::RunLoop run_loop; PpdProvider::CallbackResultCode code; provider->ResolveManufacturers(base::BindLambdaForTesting( [&run_loop, &code]( PpdProvider::CallbackResultCode result_code, const std::vector<std::string>& unused_manufacturers) { code = result_code; run_loop.QuitClosure().Run(); })); run_loop.Run(); return code == PpdProvider::CallbackResultCode::SUCCESS; } protected: // List of relevant endpoint for this FakeServer std::vector<std::pair<std::string, std::string>> server_contents() const { // Use brace initialization to express the desired server contents as "url", // "contents" pairs. return {{"metadata_v3/locales.json", R"({ "locales": [ "de", "en", "es" ] })"}, {"metadata_v3/manufacturers-en.json", kDefaultManufacturersJson}, {"metadata_v3/manufacturer_a-en.json", R"({ "printers": [ { "name": "printer_a", "emm": "printer_a_ref" }, { "name": "printer_b", "emm": "printer_b_ref" } ] })"}, {"metadata_v3/manufacturer_b-en.json", R"({ "printers": [ { "name": "printer_c", "emm": "printer_c_ref" } ] })"}, {"metadata_v3/index-01.json", R"({ "ppdIndex": { "printer_a_ref": { "ppdMetadata": [ { "name": "printer_a.ppd", "license": "fake_license" } ] } } })"}, {"metadata_v3/index-02.json", R"({ "ppdIndex": { "printer_b_ref": { "ppdMetadata": [ { "name": "printer_b.ppd" } ] } } })"}, {"metadata_v3/index-03.json", R"({ "ppdIndex": { "printer_c_ref": { "ppdMetadata": [ { "name": "printer_c.ppd" } ] } } })"}, {"metadata_v3/index-04.json", R"({ "ppdIndex": { "printer_d_ref": { "ppdMetadata": [ { "name": "printer_d.ppd" } ] } } })"}, {"metadata_v3/index-05.json", R"({ "ppdIndex": { "printer_e_ref": { "ppdMetadata": [ { "name": "printer_e.ppd" } ] } } })"}, {"metadata_v3/index-08.json", R"({ "ppdIndex": { "Some canonical reference": { "ppdMetadata": [ { "name": "unused.ppd" } ] } } })"}, {"metadata_v3/index-10.json", R"({ "ppdIndex": { "Some other canonical reference": { "ppdMetadata": [ { "name": "unused.ppd" } ] } } })"}, {"metadata_v3/usb-031f.json", R"({ "usbIndex": { "1592": { "effectiveMakeAndModel": "Some canonical reference" }, "6535": { "effectiveMakeAndModel": "Some other canonical reference" } } })"}, {"metadata_v3/usb-03f0.json", ""}, {"metadata_v3/usb-1234.json", ""}, {"metadata_v3/usb_vendor_ids.json", R"({ "entries": [ { "vendorId": 799, "vendorName": "Seven Ninety Nine LLC" }, { "vendorId": 1008, "vendorName": "HP" } ] })"}, {"metadata_v3/reverse_index-en-01.json", R"({ "reverseIndex": { "printer_a_ref": { "manufacturer": "manufacturer_a_en", "model": "printer_a" } } })"}, {"metadata_v3/reverse_index-en-19.json", R"({ "reverseIndex": { "unused effective make and model": { "manufacturer": "unused manufacturer", "model": "unused model" } } })"}, {"ppds_for_metadata_v3/printer_a.ppd", kCupsFilterPpdContents}, {"ppds_for_metadata_v3/printer_b.ppd", kCupsFilter2PpdContents}, {"ppds_for_metadata_v3/printer_c.ppd", "c"}, {"ppds_for_metadata_v3/printer_d.ppd", "d"}, {"ppds_for_metadata_v3/printer_e.ppd", "e"}, {"user_supplied_ppd_directory/user_supplied.ppd", "u"}}; } // Environment for task schedulers. base::test::TaskEnvironment task_environment_; std::vector< std::pair<PpdProvider::CallbackResultCode, std::vector<std::string>>> captured_resolve_manufacturers_; std::vector<std::pair<PpdProvider::CallbackResultCode, PpdProvider::ResolvedPrintersList>> captured_resolve_printers_; struct CapturedResolvePpdResults { PpdProvider::CallbackResultCode code; std::string ppd_contents; }; std::vector<CapturedResolvePpdResults> captured_resolve_ppd_; struct CapturedResolvePpdReferenceResults { PpdProvider::CallbackResultCode code; Printer::PpdReference ref; std::string usb_manufacturer; }; std::vector<CapturedResolvePpdReferenceResults> captured_resolve_ppd_references_; struct CapturedReverseLookup { PpdProvider::CallbackResultCode code; std::string manufacturer; std::string model; }; std::vector<CapturedReverseLookup> captured_reverse_lookup_; struct CapturedResolvePpdLicense { PpdProvider::CallbackResultCode code; std::string license; }; std::vector<CapturedResolvePpdLicense> captured_resolve_ppd_license_; base::ScopedTempDir ppd_cache_temp_dir_; base::ScopedTempDir interceptor_temp_dir_; // Reference to the underlying ppd_cache_ so we can muck with it to test // cache-dependent behavior of ppd_provider_. scoped_refptr<PpdCache> ppd_cache_; PpdProviderComposedMembers provider_backdoor_; // Misc extra stuff needed for the test environment to function. base::SimpleTestClock clock_; }; // Tests that PpdProvider enqueues a bounded number of calls to // ResolveManufacturers() and fails the oldest call when the queue is // deemed full (implementation-specified detail). TEST_F(PpdProviderTest, FailsOldestQueuedResolveManufacturers) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoNotPropagate}); // Prevents the provider from ever getting a metadata locale. // We want it to stall out, forcing it to perpetually defer method // calls to ResolveManufacturers(). provider_backdoor_.manager_config_cache->DiscardFetchRequestFor( "metadata_v3/locales.json"); for (int i = kMethodDeferralLimitForTesting; i >= 0; i--) { provider->ResolveManufacturers(base::BindOnce( &PpdProviderTest::CaptureResolveManufacturers, base::Unretained(this))); } // The for loop above should have overflowed the deferral queue by // a factor of one: the oldest call to ResolveManufacturers() should // have been forced out and asked to fail, and we expect it to be // sitting on the sequence right now. ASSERT_EQ(1UL, task_environment_.GetPendingMainThreadTaskCount()); task_environment_.FastForwardUntilNoTasksRemain(); ASSERT_EQ(1UL, captured_resolve_manufacturers_.size()); EXPECT_EQ(PpdProvider::CallbackResultCode::SERVER_ERROR, captured_resolve_manufacturers_[0].first); } // Tests that PpdProvider enqueues a bounded number of calls to // ReverseLookup() and fails the oldest call when the queue is deemed // full (implementation-specified detail). TEST_F(PpdProviderTest, FailsOldestQueuedReverseLookup) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoNotPropagate}); // Prevents the provider from ever getting a metadata locale. // We want it to stall out, forcing it to perpetually defer method // calls to ReverseLookup(). provider_backdoor_.manager_config_cache->DiscardFetchRequestFor( "metadata_v3/locales.json"); for (int i = kMethodDeferralLimitForTesting; i >= 0; i--) { provider->ReverseLookup( "some effective-make-and-model string", base::BindOnce(&PpdProviderTest::CaptureReverseLookup, base::Unretained(this))); } // The for loop above should have overflowed the deferral queue by // a factor of one: the oldest call to ReverseLookup() should have // been forced out and asked to fail, and we expect it to be sitting // on the sequence right now. ASSERT_EQ(1UL, task_environment_.GetPendingMainThreadTaskCount()); task_environment_.FastForwardUntilNoTasksRemain(); ASSERT_EQ(1UL, captured_reverse_lookup_.size()); EXPECT_EQ(PpdProvider::CallbackResultCode::SERVER_ERROR, captured_reverse_lookup_[0].code); } // Test that we get back manufacturer maps as expected. TEST_F(PpdProviderTest, ManufacturersFetch) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); // Issue two requests at the same time, both should be resolved properly. provider->ResolveManufacturers(base::BindOnce( &PpdProviderTest::CaptureResolveManufacturers, base::Unretained(this))); provider->ResolveManufacturers(base::BindOnce( &PpdProviderTest::CaptureResolveManufacturers, base::Unretained(this))); task_environment_.FastForwardUntilNoTasksRemain(); ASSERT_EQ(2UL, captured_resolve_manufacturers_.size()); std::vector<std::string> expected_result( {"Manufacturer A", "Manufacturer B"}); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_manufacturers_[0].first); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_manufacturers_[1].first); EXPECT_TRUE(captured_resolve_manufacturers_[0].second == expected_result); EXPECT_TRUE(captured_resolve_manufacturers_[1].second == expected_result); } // Test that we get a reasonable error when we have no server to contact. Tis // is almost exactly the same as the above test, we just don't bring up the fake // server first. TEST_F(PpdProviderTest, ManufacturersFetchNoServer) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoNotPropagate}); // Issue two requests at the same time, both should resolve properly // (though they will fail). provider->ResolveManufacturers(base::BindOnce( &PpdProviderTest::CaptureResolveManufacturers, base::Unretained(this))); provider->ResolveManufacturers(base::BindOnce( &PpdProviderTest::CaptureResolveManufacturers, base::Unretained(this))); task_environment_.FastForwardUntilNoTasksRemain(); ASSERT_EQ(2UL, captured_resolve_manufacturers_.size()); EXPECT_EQ(PpdProvider::SERVER_ERROR, captured_resolve_manufacturers_[0].first); EXPECT_EQ(PpdProvider::SERVER_ERROR, captured_resolve_manufacturers_[1].first); EXPECT_TRUE(captured_resolve_manufacturers_[0].second.empty()); EXPECT_TRUE(captured_resolve_manufacturers_[1].second.empty()); } // Tests that mutiples requests for make-and-model resolution can be fulfilled // simultaneously. TEST_F(PpdProviderTest, RepeatedMakeModel) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); PrinterSearchData unrecognized_printer; unrecognized_printer.discovery_type = PrinterDiscoveryType::kManual; unrecognized_printer.make_and_model = {"Printer Printer"}; PrinterSearchData recognized_printer; recognized_printer.discovery_type = PrinterDiscoveryType::kManual; recognized_printer.make_and_model = {"printer_a_ref"}; PrinterSearchData mixed; mixed.discovery_type = PrinterDiscoveryType::kManual; mixed.make_and_model = {"printer_a_ref", "Printer Printer"}; // Resolve the same thing repeatedly. provider->ResolvePpdReference( unrecognized_printer, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); provider->ResolvePpdReference( mixed, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); provider->ResolvePpdReference( recognized_printer, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(static_cast<size_t>(3), captured_resolve_ppd_references_.size()); EXPECT_EQ(PpdProvider::NOT_FOUND, captured_resolve_ppd_references_[0].code); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_references_[1].code); EXPECT_EQ("printer_a_ref", captured_resolve_ppd_references_[1].ref.effective_make_and_model); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_references_[2].code); EXPECT_EQ("printer_a_ref", captured_resolve_ppd_references_[2].ref.effective_make_and_model); } // Test successful and unsuccessful usb resolutions. TEST_F(PpdProviderTest, UsbResolution) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); PrinterSearchData search_data; search_data.discovery_type = PrinterDiscoveryType::kUsb; // Should get back "Some canonical reference" search_data.usb_vendor_id = 0x031f; search_data.usb_product_id = 1592; provider->ResolvePpdReference( search_data, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); // Should get back "Some other canonical reference" search_data.usb_vendor_id = 0x031f; search_data.usb_product_id = 6535; provider->ResolvePpdReference( search_data, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); // Vendor id that exists, nonexistent device id, should get a NOT_FOUND. // In our fake serving root, the manufacturer with vendor ID 0x031f // (== 799) is named "Seven Ninety Nine LLC." search_data.usb_vendor_id = 0x031f; search_data.usb_product_id = 8162; provider->ResolvePpdReference( search_data, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); // Nonexistent vendor id, should get a NOT_FOUND in the real world, but // the URL interceptor we're using considers all nonexistent files to // be effectively CONNECTION REFUSED, so we just check for non-success // on this one. search_data.usb_vendor_id = 0x1234; search_data.usb_product_id = 1782; provider->ResolvePpdReference( search_data, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(captured_resolve_ppd_references_.size(), static_cast<size_t>(4)); // ResolvePpdReference() takes place in several asynchronous steps, so // order is not guaranteed. EXPECT_THAT( captured_resolve_ppd_references_, UnorderedElementsAre( AllOf(Field(&CapturedResolvePpdReferenceResults::code, Eq(PpdProvider::SUCCESS)), Field(&CapturedResolvePpdReferenceResults::ref, Field(&Printer::PpdReference::effective_make_and_model, StrEq("Some canonical reference")))), AllOf(Field(&CapturedResolvePpdReferenceResults::code, Eq(PpdProvider::SUCCESS)), Field(&CapturedResolvePpdReferenceResults::ref, Field(&Printer::PpdReference::effective_make_and_model, StrEq("Some other canonical reference")))), AllOf(Field(&CapturedResolvePpdReferenceResults::code, Eq(PpdProvider::NOT_FOUND)), Field(&CapturedResolvePpdReferenceResults::usb_manufacturer, StrEq("Seven Ninety Nine LLC"))), Field(&CapturedResolvePpdReferenceResults::code, Eq(PpdProvider::NOT_FOUND)))); } // Test basic ResolvePrinters() functionality. At the same time, make // sure we can get the PpdReference for each of the resolved printers. TEST_F(PpdProviderTest, ResolvePrinters) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); // Required setup calls to advance past PpdProvider's method deferral. ASSERT_TRUE(provider_backdoor_.metadata_manager->SetManufacturersForTesting( kDefaultManufacturersJson)); ASSERT_TRUE(SuccessfullyResolveManufacturers(provider.get())); provider->ResolvePrinters( "Manufacturer A", base::BindOnce(&PpdProviderTest::CaptureResolvePrinters, base::Unretained(this))); provider->ResolvePrinters( "Manufacturer B", base::BindOnce(&PpdProviderTest::CaptureResolvePrinters, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(2UL, captured_resolve_printers_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_printers_[0].first); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_printers_[1].first); EXPECT_EQ(2UL, captured_resolve_printers_[0].second.size()); // First capture should get back printer_a, and printer_b, with ppd // reference effective make and models of printer_a_ref and printer_b_ref. const auto& capture0 = captured_resolve_printers_[0].second; ASSERT_EQ(2UL, capture0.size()); EXPECT_EQ("printer_a", capture0[0].name); EXPECT_EQ("printer_a_ref", capture0[0].ppd_ref.effective_make_and_model); EXPECT_EQ("printer_b", capture0[1].name); EXPECT_EQ("printer_b_ref", capture0[1].ppd_ref.effective_make_and_model); // Second capture should get back printer_c with effective make and model of // printer_c_ref const auto& capture1 = captured_resolve_printers_[1].second; ASSERT_EQ(1UL, capture1.size()); EXPECT_EQ("printer_c", capture1[0].name); EXPECT_EQ("printer_c_ref", capture1[0].ppd_ref.effective_make_and_model); } // Test that if we give a bad reference to ResolvePrinters(), we get a // SERVER_ERROR. There's currently no feedback that indicates // specifically to the caller that they asked for the printers of // a manufacturer we didn't previously advertise. TEST_F(PpdProviderTest, ResolvePrintersBadReference) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); // Required setup calls to advance past PpdProvider's method deferral. ASSERT_TRUE(provider_backdoor_.metadata_manager->SetManufacturersForTesting( kDefaultManufacturersJson)); ASSERT_TRUE(SuccessfullyResolveManufacturers(provider.get())); provider->ResolvePrinters( "bogus_doesnt_exist", base::BindOnce(&PpdProviderTest::CaptureResolvePrinters, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, captured_resolve_printers_.size()); EXPECT_EQ(PpdProvider::SERVER_ERROR, captured_resolve_printers_[0].first); } // Test that if the server is unavailable, we get SERVER_ERRORs back out. TEST_F(PpdProviderTest, ResolvePrintersNoServer) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); // Required setup calls to advance past PpdProvider's method deferral. ASSERT_TRUE(provider_backdoor_.metadata_manager->SetManufacturersForTesting( kDefaultManufacturersJson)); ASSERT_TRUE(SuccessfullyResolveManufacturers(provider.get())); provider->ResolvePrinters( "Manufacturer A", base::BindOnce(&PpdProviderTest::CaptureResolvePrinters, base::Unretained(this))); provider->ResolvePrinters( "Manufacturer B", base::BindOnce(&PpdProviderTest::CaptureResolvePrinters, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(2UL, captured_resolve_printers_.size()); EXPECT_EQ(PpdProvider::SERVER_ERROR, captured_resolve_printers_[0].first); EXPECT_EQ(PpdProvider::SERVER_ERROR, captured_resolve_printers_[1].first); } // Test a successful ppd resolution from an effective_make_and_model reference. TEST_F(PpdProviderTest, ResolveServerKeyPpd) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); Printer::PpdReference ref; ref.effective_make_and_model = "printer_b_ref"; provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); ref.effective_make_and_model = "printer_c_ref"; provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(2UL, captured_resolve_ppd_.size()); // ResolvePpd() works in several asynchronous steps, so order of // return is not guaranteed. EXPECT_THAT( captured_resolve_ppd_, UnorderedElementsAre( AllOf(Field(&CapturedResolvePpdResults::code, PpdProvider::CallbackResultCode::SUCCESS), Field(&CapturedResolvePpdResults::ppd_contents, StrEq(kCupsFilter2PpdContents))), AllOf(Field(&CapturedResolvePpdResults::code, PpdProvider::CallbackResultCode::SUCCESS), Field(&CapturedResolvePpdResults::ppd_contents, StrEq("c"))))); } // Test that we *don't* resolve a ppd URL over non-file schemes. It's not clear // whether we'll want to do this in the long term, but for now this is // disallowed because we're not sure we completely understand the security // implications. TEST_F(PpdProviderTest, ResolveUserSuppliedUrlPpdFromNetworkFails) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); Printer::PpdReference ref; // PpdProvider::ResolvePpd() shall fail if a user-supplied PPD URL // does not begin with the "file://" scheme. ref.user_supplied_ppd_url = "nonfilescheme://unused"; provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, captured_resolve_ppd_.size()); EXPECT_EQ(PpdProvider::INTERNAL_ERROR, captured_resolve_ppd_[0].code); EXPECT_TRUE(captured_resolve_ppd_[0].ppd_contents.empty()); } // Test a successful ppd resolution from a user_supplied_url field when // reading from a file. Note we shouldn't need the server to be up // to do this successfully, as we should be able to do this offline. TEST_F(PpdProviderTest, ResolveUserSuppliedUrlPpdFromFile) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath filename = temp_dir.GetPath().Append("my_spiffy.ppd"); std::string user_ppd_contents = "Woohoo"; ASSERT_TRUE(base::WriteFile(filename, user_ppd_contents)); Printer::PpdReference ref; ref.user_supplied_ppd_url = base::StringPrintf("file://%s", filename.MaybeAsASCII().c_str()); provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, captured_resolve_ppd_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_[0].code); EXPECT_EQ(user_ppd_contents, captured_resolve_ppd_[0].ppd_contents); } // Test that we cache ppd resolutions when we fetch them and that we can resolve // from the cache without the server available. TEST_F(PpdProviderTest, ResolvedPpdsGetCached) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); std::string user_ppd_contents = "Woohoo"; Printer::PpdReference ref; { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath filename = temp_dir.GetPath().Append("my_spiffy.ppd"); ASSERT_TRUE(base::WriteFile(filename, user_ppd_contents)); ref.user_supplied_ppd_url = base::StringPrintf("file://%s", filename.MaybeAsASCII().c_str()); provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, captured_resolve_ppd_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_[0].code); EXPECT_EQ(user_ppd_contents, captured_resolve_ppd_[0].ppd_contents); } // ScopedTempDir goes out of scope, so the source file should now be // deleted. But if we resolve again, we should hit the cache and // still be successful. captured_resolve_ppd_.clear(); // Recreate the provider to make sure we don't have any memory caches which // would mask problems with disk persistence. provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); // Re-resolve. provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, captured_resolve_ppd_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_[0].code); EXPECT_EQ(user_ppd_contents, captured_resolve_ppd_[0].ppd_contents); } // Test that all entrypoints will correctly work with case-insensitve // effective-make-and-model strings. TEST_F(PpdProviderTest, CaseInsensitiveMakeAndModel) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); std::string ref = "pRiNteR_A_reF"; Printer::PpdReference ppd_ref; ppd_ref.effective_make_and_model = ref; provider->ResolvePpd(ppd_ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); provider->ReverseLookup(ref, base::BindOnce(&PpdProviderTest::CaptureReverseLookup, base::Unretained(this))); PrinterSearchData printer_info; printer_info.make_and_model = {ref}; provider->ResolvePpdReference( printer_info, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); task_environment_.RunUntilIdle(); // Check PpdProvider::ResolvePpd ASSERT_EQ(1UL, captured_resolve_ppd_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_[0].code); EXPECT_EQ(kCupsFilterPpdContents, captured_resolve_ppd_[0].ppd_contents); // Check PpdProvider::ReverseLookup ASSERT_EQ(1UL, captured_reverse_lookup_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_reverse_lookup_[0].code); EXPECT_EQ("manufacturer_a_en", captured_reverse_lookup_[0].manufacturer); EXPECT_EQ("printer_a", captured_reverse_lookup_[0].model); // Check PpdProvider::ResolvePpdReference ASSERT_EQ(1UL, captured_resolve_ppd_references_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_references_[0].code); EXPECT_EQ("printer_a_ref", captured_resolve_ppd_references_[0].ref.effective_make_and_model); } // Tests that ResolvePpdLicense is able to correctly source the index and // determine the name of the PPD license associated with the given effecive make // and model (if any). TEST_F(PpdProviderTest, ResolvePpdLicense) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); // For this effective_make_and_model, we expect that there is associated // license. const char kEmm1[] = "printer_a_ref"; provider->ResolvePpdLicense( kEmm1, base::BindOnce(&PpdProviderTest::CaptureResolvePpdLicense, base::Unretained(this))); // We do not expect there to be any license associated with this // effective_make_and_model, so the response should be empty. const char kEmm2[] = "printer_b_ref"; provider->ResolvePpdLicense( kEmm2, base::BindOnce(&PpdProviderTest::CaptureResolvePpdLicense, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(2UL, captured_resolve_ppd_license_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_license_[0].code); EXPECT_EQ("fake_license", captured_resolve_ppd_license_[0].license); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_license_[1].code); EXPECT_EQ("", captured_resolve_ppd_license_[1].license); } // Verifies that we can extract the Manufacturer and Model selection for a // given effective make and model. TEST_F(PpdProviderTest, ReverseLookup) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); std::string ref = "printer_a_ref"; provider->ReverseLookup(ref, base::BindOnce(&PpdProviderTest::CaptureReverseLookup, base::Unretained(this))); // TODO(skau): PpdProvider has a race condition that prevents running these // requests in parallel. task_environment_.RunUntilIdle(); std::string ref_fail = "printer_does_not_exist"; provider->ReverseLookup(ref_fail, base::BindOnce(&PpdProviderTest::CaptureReverseLookup, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(2U, captured_reverse_lookup_.size()); CapturedReverseLookup success_capture = captured_reverse_lookup_[0]; EXPECT_EQ(PpdProvider::SUCCESS, success_capture.code); EXPECT_EQ("manufacturer_a_en", success_capture.manufacturer); EXPECT_EQ("printer_a", success_capture.model); CapturedReverseLookup failed_capture = captured_reverse_lookup_[1]; EXPECT_EQ(PpdProvider::NOT_FOUND, failed_capture.code); } // Verifies that we never attempt to re-download a PPD that we // previously retrieved from the serving root. The Chrome OS Printing // Team plans to keep PPDs immutable inside the serving root, so // PpdProvider should always prefer to retrieve a PPD from the PpdCache // when it's possible to do so. TEST_F(PpdProviderTest, PreferToResolvePpdFromPpdCacheOverServingRoot) { // Explicitly *not* starting a fake server. std::string cached_ppd_contents = "These cached contents are different from what's being served"; auto provider = CreateProvider({"en", PpdCacheRunLocation::kOnTestThread, PropagateLocaleToMetadataManager::kDoPropagate}); Printer::PpdReference ref; ref.effective_make_and_model = "printer_a_ref"; std::string cache_key = PpdProvider::PpdReferenceToCacheKey(ref); // Cache exists, and is just created, so should be fresh. // // PPD basename is taken from value specified in forward index shard // defined in server_contents(). const std::string ppd_basename = "printer_a.ppd"; ppd_cache_->StoreForTesting(PpdProvider::PpdBasenameToCacheKey(ppd_basename), cached_ppd_contents, base::TimeDelta()); ppd_cache_->StoreForTesting(PpdProvider::PpdReferenceToCacheKey(ref), ppd_basename, base::TimeDelta()); task_environment_.RunUntilIdle(); provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, captured_resolve_ppd_.size()); // Should get the cached (not served) results back, and not have hit the // network. EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_[0].code); EXPECT_EQ(cached_ppd_contents, captured_resolve_ppd_[0].ppd_contents); } // For user-provided ppds, we should always use the latest version on // disk if it still exists there. TEST_F(PpdProviderTest, UserPpdAlwaysRefreshedIfAvailable) { base::ScopedTempDir temp_dir; std::string cached_ppd_contents = "Cached Ppd Contents"; std::string disk_ppd_contents = "Updated Ppd Contents"; auto provider = CreateProvider({"en", PpdCacheRunLocation::kOnTestThread, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath filename = temp_dir.GetPath().Append("my_spiffy.ppd"); Printer::PpdReference ref; ref.user_supplied_ppd_url = base::StringPrintf("file://%s", filename.MaybeAsASCII().c_str()); // Put cached_ppd_contents into the cache. ppd_cache_->StoreForTesting(PpdProvider::PpdReferenceToCacheKey(ref), cached_ppd_contents, base::TimeDelta()); task_environment_.RunUntilIdle(); // Write different contents to disk, so that the cached contents are // now stale. ASSERT_TRUE(base::WriteFile(filename, disk_ppd_contents)); provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, captured_resolve_ppd_.size()); EXPECT_EQ(PpdProvider::SUCCESS, captured_resolve_ppd_[0].code); EXPECT_EQ(disk_ppd_contents, captured_resolve_ppd_[0].ppd_contents); // Check that the cache was also updated with the new contents. PpdCache::FindResult captured_find_result; ppd_cache_->Find(PpdProvider::PpdReferenceToCacheKey(ref), base::BindOnce( [](PpdCache::FindResult* captured_find_result, const PpdCache::FindResult& find_result) { *captured_find_result = find_result; }, &captured_find_result)); task_environment_.RunUntilIdle(); EXPECT_EQ(captured_find_result.success, true); EXPECT_EQ(captured_find_result.contents, disk_ppd_contents); } // Test resolving usb manufacturer when failed to resolve PpdReference. TEST_F(PpdProviderTest, ResolveUsbManufacturer) { auto provider = CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, PropagateLocaleToMetadataManager::kDoPropagate}); StartFakePpdServer(); PrinterSearchData search_data; search_data.discovery_type = PrinterDiscoveryType::kUsb; // Vendor id that exists, nonexistent device id, should get a NOT_FOUND. // Although this is an unsupported printer model, we can still expect to get // the manufacturer name. search_data.usb_vendor_id = 0x03f0; search_data.usb_product_id = 9999; provider->ResolvePpdReference( search_data, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); // Nonexistent vendor id, should get a NOT_FOUND in the real world, but // the URL interceptor we're using considers all nonexistent files to // be effectively CONNECTION REFUSED, so we just check for non-success // on this one. We should also not be able to get a manufacturer name from a // nonexistent vendor id. search_data.usb_vendor_id = 0x1234; search_data.usb_product_id = 1782; provider->ResolvePpdReference( search_data, base::BindOnce(&PpdProviderTest::CaptureResolvePpdReference, base::Unretained(this))); task_environment_.RunUntilIdle(); ASSERT_EQ(static_cast<size_t>(2), captured_resolve_ppd_references_.size()); // Was able to find the printer manufactuer but unable to find the printer // model should result in a NOT_FOUND. EXPECT_EQ(PpdProvider::NOT_FOUND, captured_resolve_ppd_references_[0].code); // Failed to grab the PPD for a USB printer, but should still be able to grab // its manufacturer name. EXPECT_EQ("HP", captured_resolve_ppd_references_[0].usb_manufacturer); // Unable to find the PPD file should result in a failure. EXPECT_FALSE(captured_resolve_ppd_references_[1].code == PpdProvider::SUCCESS); // Unknown vendor id should result in an empty manufacturer string. EXPECT_TRUE(captured_resolve_ppd_references_[1].usb_manufacturer.empty()); } } // namespace } // namespace chromeos
42.146725
80
0.68484
[ "vector", "model" ]
7465f6c7cc8985cfb1fa5cd5d38f894936d61648
1,349
cpp
C++
thirdparty/ngraph/src/nnfusion/core/operators/util/tensor_op.cpp
xiezhq-hermann/nnfusion
1b2c23b0732bee295e37b990811719e0c4c6e993
[ "MIT" ]
1
2021-05-14T08:10:30.000Z
2021-05-14T08:10:30.000Z
thirdparty/ngraph/src/nnfusion/core/operators/util/tensor_op.cpp
xiezhq-hermann/nnfusion
1b2c23b0732bee295e37b990811719e0c4c6e993
[ "MIT" ]
null
null
null
thirdparty/ngraph/src/nnfusion/core/operators/util/tensor_op.cpp
xiezhq-hermann/nnfusion
1b2c23b0732bee295e37b990811719e0c4c6e993
[ "MIT" ]
1
2021-02-13T08:10:55.000Z
2021-02-13T08:10:55.000Z
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** // Microsoft (c) 2019, NNFusion Team #include "tensor_op.hpp" #include "nnfusion/core/graph/gnode.hpp" using namespace std; using namespace nnfusion::op; TensorOp::TensorOp(const std::string& node_type, const nnfusion::element::Type& element_type, const nnfusion::Shape& shape) : Op(node_type) , m_shape(shape) , m_element_type(element_type) { } void TensorOp::validate_and_infer_types(std::shared_ptr<graph::GNode> gnode) { Op::validate_and_infer_types(gnode); gnode->set_output_type_and_shape(0, m_element_type, m_shape); }
33.725
79
0.638251
[ "shape" ]
746951b7a2ecdd3b25980f95cf3de8c28520aea6
5,539
cc
C++
ortools/constraint_solver/samples/cp_is_fun_cp.cc
kharazian/or-tools-em
8df912821e013203523ba433ff2babbbc91c6a4b
[ "Apache-2.0" ]
null
null
null
ortools/constraint_solver/samples/cp_is_fun_cp.cc
kharazian/or-tools-em
8df912821e013203523ba433ff2babbbc91c6a4b
[ "Apache-2.0" ]
null
null
null
ortools/constraint_solver/samples/cp_is_fun_cp.cc
kharazian/or-tools-em
8df912821e013203523ba433ff2babbbc91c6a4b
[ "Apache-2.0" ]
null
null
null
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] // Cryptarithmetic puzzle // // First attempt to solve equation CP + IS + FUN = TRUE // where each letter represents a unique digit. // // This problem has 72 different solutions in base 10. // [START import] #include <cstdint> #include <vector> #include "absl/flags/flag.h" #include "ortools/base/init_google.h" #include "ortools/base/logging.h" #include "ortools/base/logging_flags.h" #include "ortools/constraint_solver/constraint_solver.h" // [END import] namespace operations_research { // Helper functions. IntVar* const MakeBaseLine2(Solver* s, IntVar* const v1, IntVar* const v2, const int64_t base) { return s->MakeSum(s->MakeProd(v1, base), v2)->Var(); } IntVar* const MakeBaseLine3(Solver* s, IntVar* const v1, IntVar* const v2, IntVar* const v3, const int64_t base) { std::vector<IntVar*> tmp_vars; std::vector<int64_t> coefficients; tmp_vars.push_back(v1); coefficients.push_back(base * base); tmp_vars.push_back(v2); coefficients.push_back(base); tmp_vars.push_back(v3); coefficients.push_back(1); return s->MakeScalProd(tmp_vars, coefficients)->Var(); } IntVar* const MakeBaseLine4(Solver* s, IntVar* const v1, IntVar* const v2, IntVar* const v3, IntVar* const v4, const int64_t base) { std::vector<IntVar*> tmp_vars; std::vector<int64_t> coefficients; tmp_vars.push_back(v1); coefficients.push_back(base * base * base); tmp_vars.push_back(v2); coefficients.push_back(base * base); tmp_vars.push_back(v3); coefficients.push_back(base); tmp_vars.push_back(v4); coefficients.push_back(1); return s->MakeScalProd(tmp_vars, coefficients)->Var(); } void CPIsFunCp() { // Instantiate the solver. // [START solver] Solver solver("CP is fun!"); // [END solver] // [START variables] const int64_t kBase = 10; // Define decision variables. IntVar* const c = solver.MakeIntVar(1, kBase - 1, "C"); IntVar* const p = solver.MakeIntVar(0, kBase - 1, "P"); IntVar* const i = solver.MakeIntVar(1, kBase - 1, "I"); IntVar* const s = solver.MakeIntVar(0, kBase - 1, "S"); IntVar* const f = solver.MakeIntVar(1, kBase - 1, "F"); IntVar* const u = solver.MakeIntVar(0, kBase - 1, "U"); IntVar* const n = solver.MakeIntVar(0, kBase - 1, "N"); IntVar* const t = solver.MakeIntVar(1, kBase - 1, "T"); IntVar* const r = solver.MakeIntVar(0, kBase - 1, "R"); IntVar* const e = solver.MakeIntVar(0, kBase - 1, "E"); // We need to group variables in a vector to be able to use // the global constraint AllDifferent std::vector<IntVar*> letters; letters.push_back(c); letters.push_back(p); letters.push_back(i); letters.push_back(s); letters.push_back(f); letters.push_back(u); letters.push_back(n); letters.push_back(t); letters.push_back(r); letters.push_back(e); // Check if we have enough digits CHECK_GE(kBase, letters.size()); // [END variables] // [START constraints] // Define constraints. solver.AddConstraint(solver.MakeAllDifferent(letters)); // CP + IS + FUN = TRUE IntVar* const term1 = MakeBaseLine2(&solver, c, p, kBase); IntVar* const term2 = MakeBaseLine2(&solver, i, s, kBase); IntVar* const term3 = MakeBaseLine3(&solver, f, u, n, kBase); IntVar* const sum_terms = solver.MakeSum(solver.MakeSum(term1, term2), term3)->Var(); IntVar* const sum = MakeBaseLine4(&solver, t, r, u, e, kBase); solver.AddConstraint(solver.MakeEquality(sum_terms, sum)); // [END constraints] // [START solve] int num_solutions = 0; // Create decision builder to search for solutions. DecisionBuilder* const db = solver.MakePhase( letters, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { LOG(INFO) << "C=" << c->Value() << " " << "P=" << p->Value() << " " << "I=" << i->Value() << " " << "S=" << s->Value() << " " << "F=" << f->Value() << " " << "U=" << u->Value() << " " << "N=" << n->Value() << " " << "T=" << t->Value() << " " << "R=" << r->Value() << " " << "E=" << e->Value(); // Is CP + IS + FUN = TRUE? CHECK_EQ(p->Value() + s->Value() + n->Value() + kBase * (c->Value() + i->Value() + u->Value()) + kBase * kBase * f->Value(), e->Value() + kBase * u->Value() + kBase * kBase * r->Value() + kBase * kBase * kBase * t->Value()); num_solutions++; } solver.EndSearch(); LOG(INFO) << "Number of solutions found: " << num_solutions; // [END solve] } } // namespace operations_research int main(int argc, char** argv) { InitGoogle(argv[0], &argc, &argv, true); absl::SetFlag(&FLAGS_logtostderr, true); operations_research::CPIsFunCp(); return EXIT_SUCCESS; } // [END program]
33.36747
75
0.630439
[ "vector" ]
746c8bcc2f9c6ac2bbd9b44edc9747706d6f02c8
941
cpp
C++
solutions/05XX/598/598B.cpp
AlexanderFadeev/codeforces
9e70a58e69fafe96604045e1e9ce1d3dab07e1e5
[ "MIT" ]
null
null
null
solutions/05XX/598/598B.cpp
AlexanderFadeev/codeforces
9e70a58e69fafe96604045e1e9ce1d3dab07e1e5
[ "MIT" ]
null
null
null
solutions/05XX/598/598B.cpp
AlexanderFadeev/codeforces
9e70a58e69fafe96604045e1e9ce1d3dab07e1e5
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <array> #include <unordered_map> #include <set> using namespace std; struct Query { int l; int r; int k; }; void run() { string s; cin >> s; int q; cin >> q; vector<Query> qq; qq.resize(q); for (int i = 0; i < q; i++) { cin >> qq[i].l >> qq[i].r >> qq[i].k; qq[i].l--; qq[i].r--; } string ans; ans.resize(s.length()); for (int i = 0; i < s.length(); i++) { int idx = i; for (int j = 0; j < q; j++) { if (qq[j].l > idx || idx > qq[j].r) { continue; } int d = qq[j].r - qq[j].l + 1; idx = qq[j].l + (idx - qq[j].l + qq[j].k) % d; } ans[idx] = s[i]; } cout << ans << endl; } int main() { int t; // cin >> t; t = 1; while (t--) { run(); } }
17.109091
58
0.405951
[ "vector" ]
746f2427b28114c9aefabaacc4f037be2df1bee9
12,758
cpp
C++
socks5.cpp
dnybz/asio_socks5
bacef2b082981be00e1588fe140729c2041ad5f9
[ "MIT" ]
null
null
null
socks5.cpp
dnybz/asio_socks5
bacef2b082981be00e1588fe140729c2041ad5f9
[ "MIT" ]
null
null
null
socks5.cpp
dnybz/asio_socks5
bacef2b082981be00e1588fe140729c2041ad5f9
[ "MIT" ]
null
null
null
/** * @file socks5.cpp * @brief Simple SOCKS5 proxy server realization using standalone asio library * @author philave (philave7@gmail.com), cnfreebsd@163.com */ #include <cstdlib> #include <iostream> #include <string> #include <memory> #include <utility> #include <asio.hpp> #include <fstream> #include "config_reader.hpp" using asio::ip::tcp; // Common log function inline void write_log(int prefix, short verbose, short verbose_level, int session_id, const std::string& what, const std::string& error_message = "") { if (verbose > verbose_level) return; std::string session = ""; if (session_id >= 0) { session += "session("; session += std::to_string(session_id); session += "): "; } if (prefix > 0) { std::cerr << (prefix == 1 ? "Error: " : "Warning: ") << session << what; if (error_message.size() > 0) std::cerr << ": " << error_message; std::cerr << std::endl; } else { std::cout << session << what; if (error_message.size() > 0) std::cout << ": " << error_message; std::cout << std::endl; } } class Session : public std::enable_shared_from_this<Session> { public: Session(tcp::socket in_socket, unsigned session_id, size_t buffer_size, short verbose) : in_socket_(std::move(in_socket)), out_socket_(in_socket.get_io_service()), resolver(in_socket.get_io_service()), in_buf_(buffer_size), out_buf_(buffer_size), session_id_(session_id), verbose_(verbose) { } void start() { read_socks5_handshake(); } private: void read_socks5_handshake() { auto self(shared_from_this()); in_socket_.async_receive(asio::buffer(in_buf_), [this, self](asio::error_code ec, std::size_t length) { if (!ec) { /* The client connects to the server, and sends a version identifier/method selection message: +----+----------+----------+ |VER | NMETHODS | METHODS | +----+----------+----------+ | 1 | 1 | 1 to 255 | +----+----------+----------+ The values currently defined for METHOD are: o X'00' NO AUTHENTICATION REQUIRED o X'01' GSSAPI o X'02' USERNAME/PASSWORD o X'03' to X'7F' IANA ASSIGNED o X'80' to X'FE' RESERVED FOR PRIVATE METHODS o X'FF' NO ACCEPTABLE METHODS */ if (length < 3 || in_buf_[0] != 0x05) { write_log(1, 0, verbose_, session_id_, "SOCKS5 handshake request is invalid. Closing session."); return; } uint8_t num_methods = in_buf_[1]; // Prepare request in_buf_[1] = 0xFF; // Only 0x00 - 'NO AUTHENTICATION REQUIRED' is now support_ed for (uint8_t method = 0; method < num_methods; ++method) if (in_buf_[2 + method] == 0x00) { in_buf_[1] = 0x00; break; } write_socks5_handshake(); } else write_log(1, 0, verbose_, session_id_, "SOCKS5 handshake request", ec.message()); }); } void write_socks5_handshake() { auto self(shared_from_this()); asio::async_write(in_socket_, asio::buffer(in_buf_, 2), // Always 2-byte according to RFC1928 [this, self](asio::error_code ec, std::size_t length) { if (!ec) { if (in_buf_[1] == 0xFF) return; // No appropriate auth method found. Close session. read_socks5_request(); } else write_log(1, 0, verbose_, session_id_, "SOCKS5 handshake response write", ec.message()); }); } void read_socks5_request() { auto self(shared_from_this()); in_socket_.async_receive(asio::buffer(in_buf_), [this, self](asio::error_code ec, std::size_t length) { if (!ec) { /* The SOCKS request is formed as follows: +----+-----+-------+------+----------+----------+ |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | +----+-----+-------+------+----------+----------+ | 1 | 1 | X'00' | 1 | Variable | 2 | +----+-----+-------+------+----------+----------+ Where: o VER protocol version: X'05' o CMD o CONNECT X'01' o BIND X'02' o UDP ASSOCIATE X'03' o RSV RESERVED o ATYP address type of following address o IP V4 address: X'01' o DOMAINNAME: X'03' o IP V6 address: X'04' o DST.ADDR desired destination address o DST.PORT desired destination port_ in network octet order The SOCKS server will typically evaluate the request based on source and destination addresses, and return one or more reply messages, as appropriate for the request type. */ if (length < 5 || in_buf_[0] != 0x05 || in_buf_[1] != 0x01) { write_log(1, 0, verbose_, session_id_, "SOCKS5 request is invalid. Closing session."); return; } uint8_t addr_type = in_buf_[3], host_length; switch (addr_type) { case 0x01: // IP V4 addres if (length != 10) { write_log(1, 0, verbose_, session_id_, "SOCKS5 request length is invalid. Closing session."); return; } remote_host_ = asio::ip::address_v4(ntohl(*((uint32_t*)&in_buf_[4]))).to_string(); remote_port_ = std::to_string(ntohs(*((uint16_t*)&in_buf_[8]))); break; case 0x03: // DOMAINNAME host_length = in_buf_[4]; if (length != (size_t)(5 + host_length + 2)) { write_log(1, 0, verbose_, session_id_, "SOCKS5 request length is invalid. Closing session."); return; } remote_host_ = std::string(&in_buf_[5], host_length); remote_port_ = std::to_string(ntohs(*((uint16_t*)&in_buf_[5 + host_length]))); break; default: write_log(1, 0, verbose_, session_id_, "unsupport_ed address type in SOCKS5 request. Closing session."); break; } do_resolve(); } else write_log(1, 0, verbose_, session_id_, "SOCKS5 request read", ec.message()); }); } void do_resolve() { auto self(shared_from_this()); resolver.async_resolve(tcp::resolver::query({ remote_host_, remote_port_ }), [this, self](const asio::error_code& ec, tcp::resolver::iterator it) { if (!ec) { do_connect(it); } else { std::ostringstream what; what << "failed to resolve " << remote_host_ << ":" << remote_port_; write_log(1, 0, verbose_, session_id_, what.str(), ec.message()); } }); } void do_connect(tcp::resolver::iterator& it) { auto self(shared_from_this()); out_socket_.async_connect(*it, [this, self](const asio::error_code& ec) { if (!ec) { std::ostringstream what; what << "connected to " << remote_host_ << ":" << remote_port_; write_log(0, 1, verbose_, session_id_, what.str()); write_socks5_response(); } else { std::ostringstream what; what << "failed to connect " << remote_host_ << ":" << remote_port_; write_log(1, 0, verbose_, session_id_, what.str(), ec.message()); } }); } void write_socks5_response() { auto self(shared_from_this()); /* The SOCKS request information is sent by the client as soon as it has established a connection to the SOCKS server, and completed the authentication negotiations. The server evaluates the request, and returns a reply formed as follows: +----+-----+-------+------+----------+----------+ |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | +----+-----+-------+------+----------+----------+ | 1 | 1 | X'00' | 1 | Variable | 2 | +----+-----+-------+------+----------+----------+ Where: o VER protocol version: X'05' o REP Reply field: o X'00' succeeded o X'01' general SOCKS server failure o X'02' connection not allowed by ruleset o X'03' Network unreachable o X'04' Host unreachable o X'05' Connection refused o X'06' TTL expired o X'07' Command not support_ed o X'08' Address type not support_ed o X'09' to X'FF' unassigned o RSV RESERVED o ATYP address type of following address o IP V4 address: X'01' o DOMAINNAME: X'03' o IP V6 address: X'04' o BND.ADDR server bound address o BND.PORT server bound port_ in network octet order Fields marked RESERVED (RSV) must be set to X'00'. */ in_buf_[0] = 0x05; in_buf_[1] = 0x00; in_buf_[2] = 0x00; in_buf_[3] = 0x01; uint32_t realRemoteIP = out_socket_.remote_endpoint().address().to_v4().to_ulong(); uint16_t realRemoteport = htons(out_socket_.remote_endpoint().port()); std::memcpy(&in_buf_[4], &realRemoteIP, 4); std::memcpy(&in_buf_[8], &realRemoteport, 2); asio::async_write(in_socket_, asio::buffer(in_buf_, 10), // Always 10-byte according to RFC1928 [this, self](asio::error_code ec, std::size_t length) { if (!ec) { do_read(3); // Read both sockets } else write_log(1, 0, verbose_, session_id_, "SOCKS5 response write", ec.message()); }); } void do_read(int direction) { auto self(shared_from_this()); // We must divide reads by direction to not permit second read call on the same socket. if (direction & 0x1) in_socket_.async_receive(asio::buffer(in_buf_), [this, self](asio::error_code ec, std::size_t length) { if (!ec) { std::ostringstream what; what << "--> " << std::to_string(length) << " bytes"; write_log(0, 2, verbose_, session_id_, what.str()); do_write(1, length); } else //if (ec != asio::error::eof) { write_log(2, 1, verbose_, session_id_, "closing session. Client socket read error", ec.message()); // Most probably client closed socket. Let's close both sockets and exit session. in_socket_.close(); out_socket_.close(); } }); if (direction & 0x2) out_socket_.async_receive(asio::buffer(out_buf_), [this, self](asio::error_code ec, std::size_t length) { if (!ec) { std::ostringstream what; what << "<-- " << std::to_string(length) << " bytes"; write_log(0, 2, verbose_, session_id_, what.str()); do_write(2, length); } else //if (ec != asio::error::eof) { write_log(2, 1, verbose_, session_id_, "closing session. Remote socket read error", ec.message()); // Most probably remote server closed socket. Let's close both sockets and exit session. in_socket_.close(); out_socket_.close(); } }); } void do_write(int direction, std::size_t Length) { auto self(shared_from_this()); switch (direction) { case 1: asio::async_write(out_socket_, asio::buffer(in_buf_, Length), [this, self, direction](asio::error_code ec, std::size_t length) { if (!ec) do_read(direction); else { write_log(2, 1, verbose_, session_id_, "closing session. Client socket write error", ec.message()); // Most probably client closed socket. Let's close both sockets and exit session. in_socket_.close(); out_socket_.close(); } }); break; case 2: asio::async_write(in_socket_, asio::buffer(out_buf_, Length), [this, self, direction](asio::error_code ec, std::size_t length) { if (!ec) do_read(direction); else { write_log(2, 1, verbose_, session_id_, "closing session. Remote socket write error", ec.message()); // Most probably remote server closed socket. Let's close both sockets and exit session. in_socket_.close(); out_socket_.close(); } }); break; } } tcp::socket in_socket_; tcp::socket out_socket_; tcp::resolver resolver; std::string remote_host_; std::string remote_port_; std::vector<char> in_buf_; std::vector<char> out_buf_; int session_id_; short verbose_; }; class Server { public: Server(asio::io_service& io_service, short port, unsigned buffer_size, short verbose) : acceptor_(io_service, tcp::endpoint(tcp::v4(), port)), in_socket_(io_service), buffer_size_(buffer_size), verbose_(verbose), session_id_(0) { do_accept(); } private: void do_accept() { acceptor_.async_accept(in_socket_, [this](asio::error_code ec) { if (!ec) { std::make_shared<Session>(std::move(in_socket_), session_id_++, buffer_size_, verbose_)->start(); } else write_log(1, 0, verbose_, session_id_, "socket accept error", ec.message()); do_accept(); }); } tcp::acceptor acceptor_; tcp::socket in_socket_; size_t buffer_size_; short verbose_; unsigned session_id_; }; int main(int argc, char* argv[]) { short verbose = 0; try { if (argc != 2) { std::cout << "Usage: boost_socks5 <config_file>" << std::endl; return 1; } ConfigReader conf; conf.parse(argv[1]); short port = conf.check_key("port") ? std::atoi(conf.get_key_value("port")) : 1080; // Default port_ size_t buffer_size = conf.check_key("buffer_size") ? std::atoi(conf.get_key_value("buffer_size")) : 8192; // Default buffer_size verbose = conf.check_key("verbose") ? std::atoi(conf.get_key_value("verbose")) : 0; // Default verbose_ asio::io_service io_service; Server server(io_service, port, buffer_size, verbose); io_service.run(); } catch (std::exception& e) { write_log(1, 0, verbose, -1, "", e.what()); } catch (...) { write_log(1, 0, verbose, -1, "", "exception..."); } return 0; }
27.377682
156
0.630428
[ "vector" ]
747fe737d65844a5755afa710e41a33b5ac8db3b
1,598
cpp
C++
ide/XSIDE/xsfilesavedialog.cpp
mixtile/gena-xskit
9d273840c60493c509c72b281463a376702539fb
[ "Apache-2.0" ]
15
2016-01-21T19:57:11.000Z
2021-04-08T08:59:01.000Z
ide/XSIDE/xsfilesavedialog.cpp
mixtile/gena-xskit
9d273840c60493c509c72b281463a376702539fb
[ "Apache-2.0" ]
5
2015-12-05T03:41:43.000Z
2016-10-17T16:25:35.000Z
ide/XSIDE/xsfilesavedialog.cpp
mixtile/gena-xskit
9d273840c60493c509c72b281463a376702539fb
[ "Apache-2.0" ]
10
2016-03-21T09:34:01.000Z
2020-07-21T18:34:07.000Z
#include "xsfilesavedialog.h" #include "ui_xsfilesavedialog.h" #include <QStandardItemModel> XSFileSaveDialog::XSFileSaveDialog(QWidget *parent) : QDialog(parent), ui(new Ui::XSFileSaveDialog) { ui->setupUi(this); } void XSFileSaveDialog::updateList(const QStringList &fileNames, const QStringList &filePaths) { QStandardItemModel *model = new QStandardItemModel; for(int i = 0; i < fileNames.size(); i++) { QString text = fileNames.at(i) + " [" + filePaths.at(i) + "]"; QStandardItem *item = new QStandardItem(text); item->setCheckable(true); item->setCheckState(Qt::Checked); model->setItem(i, item); } ui->listView->setModel(model); } const QVector<int> XSFileSaveDialog::getSaveFileIndexes() { return indexes; } XSFileSaveDialog::~XSFileSaveDialog() { delete ui; } void XSFileSaveDialog::on_btn_select_clicked() { for(int i = 0; i < ui->listView->model()->rowCount(); i++) { ((QStandardItemModel *)ui->listView->model())->item(i)->setCheckState(Qt::Checked); } } void XSFileSaveDialog::on_btn_unselect_clicked() { for(int i = 0; i < ui->listView->model()->rowCount(); i++) { ((QStandardItemModel *)ui->listView->model())->item(i)->setCheckState(Qt::Unchecked); } } void XSFileSaveDialog::on_buttonBox_confirm_accepted() { indexes.clear(); for(int i = 0; i < ui->listView->model()->rowCount(); i++) { if(((QStandardItemModel *)ui->listView->model())->item(i)->checkState() == Qt::Checked) { indexes.append(i); } } }
25.365079
95
0.635795
[ "model" ]
7483d80f7ad2d640ca57091f98e6c368cc1f3444
8,970
cpp
C++
src/scene/octree.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
1
2019-02-13T15:39:56.000Z
2019-02-13T15:39:56.000Z
src/scene/octree.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
null
null
null
src/scene/octree.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
2
2017-11-09T12:06:41.000Z
2019-02-13T15:40:02.000Z
#include "vixen.h" #include "scene/vxoctree.h" namespace Vixen { VX_IMPLEMENT_CLASSID(Octree, Shape, VX_Octree); Octree::Octree(const Box3* bound) : Shape() { if (bound) SetBound(bound); // SetHints(Model::STATIC); } /*! * @fn bool Octree::IsInside(const Mesh* mesh) const * @param mesh mesh to check * * Determines whether or not the given mesh is within the * bounds of this octree node. The result is computed by * comparing the bounding box of the mesh against the * bounds of this node. Individual triangles are not checked. * This routine assumes the local coordinate system of the * mesh vertices is world coordinates! * * @return true if mesh inside this node, else false * * @see Octree::MakeWorldCoords */ bool Octree::IsInside(const Geometry* mesh) const { Box3 b; Box3 bnd; if (mesh == NULL) return false; if (!mesh->IsClass(VX_Mesh)) return false; if (!GetBound(&bnd, NONE)) return false; if (!mesh->GetBound(&b)) // no bounding volume? return false; // ignore this one if (bnd.Contains(b.min) && bnd.Contains(b.max)) return true; // within input bounds return false; } /*! * @fn Octree* Octree::Find(const Vec3& loc) const * @param loc location to find within octree * * Finds the lowest level octree node which contains the * given location. The spatially sorted structure of the * octree makes this efficient, allowing for fast * collision detection and picking */ const Octree* Octree::Find(const Vec3& loc) const { Box3 bound; if (!GetBound(&bound, NONE) || !bound.Contains(loc)) return NULL; GroupIter<Octree> iter(this, Group::CHILDREN); const Octree* node; const Octree* found; while (node = iter.Next()) { if (node->IsClass(VX_Octree) && (found = node->Find(loc))) return found; } return this; } /*! * @fn bool Octree::BuildTree(ObjArray* surfaces, const Box3& bound) * @param surfaces array of surfaces to spatially sort * @param bound bounding volume for octree * * Spatially sorts the input array of surfaces by building an octree * that arranges the meshes according to 3D location in space. * The octree itself is a scene graph and can be added to the * hierarchy of a scene. It arranges the meshes at each level * based on which octant of 3D space they occupy. Only the surfaces * of leaf nodes have meshes in them. Upper level nodes subdivide * space but render nothing. This spatial organization optimizes * operations like picking and collision detection which try to * determine relationships between objects in space. * * The technique only works for a scene graph that does not * contain dynamic objects whose matrix changes over time * (like billboards or animated characters). The input surfaces * must be converted to world coordinates before they can be used * to make an octree. * * @returns true if octree construction successful, * false if octree was not made * */ bool Octree::BuildTree(ObjArray& surfaces, const Box3& bound) { Box3 limit; float limitvol; Matrix rootmtx; int nmeshes; ObjArray collected; SetBound(&bound); nmeshes = CollectMeshes(surfaces, collected, limit, false); if (nmeshes <= 0) return false; limitvol = limit.Width() * limit.Height() * limit.Depth(); Subdivide(collected, limitvol, 1); return true; } /* * @fn bool Octree::Subdivide(ObjArray& meshes, float limitvol, int level) * @param limitvol minimum volume for subdivision * @param level tree depth * * Subdivides this octree node, creating 8 children for each * octant of the original bounding volume. * * @return true if children created, false if subdivision below volume limit */ bool Octree::Subdivide(ObjArray& meshes, float limitvol, int level) { Octree* node; Box3 minvol; Box3 bound; if (meshes.GetSize() == 0) return false; // no meshes and no children? if (!GetBound(&bound, NONE)) return false; // empty bounds? float newvol = bound.Width() * bound.Height() * bound.Depth(); Vec3 center = bound.Center(); Box3 b; TCHAR namebuf[VX_MaxName]; const TCHAR* name = GetName(); TCHAR* p; newvol /= 8; if (newvol < limitvol) // smaller than limit volume? return false; // don't subdivide ++level; VX_ASSERT(name); // isolate first part of name STRCPY(namebuf, name); p = STRCHR(namebuf, '-'); if (p) *p = 0; b.Set(Vec3(bound.min.x, bound.min.y, bound.min.z), center); node = MakeNode(meshes, &b, level, namebuf, limitvol, 1); b.Set(Vec3(bound.max.x, bound.min.y, bound.min.z), center); node = MakeNode(meshes, &b, level, namebuf, limitvol, 2); b.Set(Vec3(bound.min.x, bound.max.y, bound.min.z), center); node = MakeNode(meshes, &b, level, namebuf, limitvol, 3); b.Set(Vec3(bound.max.x, bound.max.y, bound.min.z), center); node = MakeNode(meshes, &b, level, namebuf, limitvol, 4); b.Set(Vec3(bound.min.x, bound.min.y, bound.max.z), center); node = MakeNode(meshes, &b, level, namebuf, limitvol, 5); b.Set(Vec3(bound.max.x, bound.min.y, bound.max.z), center); node = MakeNode(meshes, &b, level, namebuf, limitvol, 6); b.Set(Vec3(bound.min.x, bound.max.y, bound.max.z), center); node = MakeNode(meshes, &b, level, namebuf, limitvol, 7); b.Set(Vec3(bound.max.x, bound.max.y, bound.max.z), center); node = MakeNode(meshes, &b, level, namebuf, limitvol, 8); return true; } Octree* Octree::MakeNode(ObjArray& inputmeshes, const Box3* bound, int level, const TCHAR* nameprefix, float limitvol, int count) { TCHAR namebuf[VX_MaxName]; TCHAR* p; Box3 minvol; int nmeshes; Octree* node = new Octree(bound); ObjArray outputmeshes; VX_ASSERT(nameprefix); nmeshes = node->CollectMeshes(inputmeshes, outputmeshes, minvol, true); if (nmeshes == 0) { node->Delete(); return NULL; } STRCPY(namebuf, nameprefix); p = namebuf + STRLEN(namebuf); SPRINTF(p, TEXT("-%d.%d"), level, count); node->SetName(namebuf); node->Subdivide(outputmeshes, limitvol, level); Append(node); if (nmeshes == 1) // only one mesh? node->SetGeometry((Geometry*) (SharedObj*) outputmeshes[0]); else // multiple meshes { ObjArray::Iter iter(outputmeshes); Geometry* geo; Shape* shape; while (geo = (Geometry*) iter.Next()) // add each mesh as a child shape { shape = new Shape(); shape->SetGeometry(geo); node->Append(shape); } } return node; } /*! * @fn int Octree::CollectMeshes(const ObjArray& input, ObjArray& output, Box3& minvol) * @param input input array of meshes * @param output output array of meshes * @param minvol gets bounding volume of smallest mesh * @param remove true to remove the collected meshes from the input array, false to leave them * * Collects all of the meshes from the input array of surfaces that fit within * the bounds of this node and returns them in the output array. * This routine assumes all of the surfaces in the hierarchy have been * converted to world coordinates. * * @return number of meshes collected */ int Octree::CollectMeshes(const ObjArray& input, ObjArray& output, Box3& minvol, bool remove) { ObjArray::Iter iter(input); const Geometry* surf; int nmeshes = 0; minvol.Empty(); while (surf = (const Geometry*) iter.Next()) // for each mesh in the array { if (CalcMinVol(surf, minvol)) // is it in the box? { output.Append(surf); if (remove) iter.Remove(); nmeshes++; } } return nmeshes; } /*! * @fn bool Octree::CalcMinVol(const Geometry* mesh, Box3& minbox) * @param mesh input mesh to check * @param minbox gets bounding volume of mesh * * Collects all of the meshes from the input hierarchy that fit within * the input bound and adds them to the surface of this shape. * * @return true if mesh is inside box, else false */ bool Octree::CalcMinVol(const Geometry* mesh, Box3& minbox) { float minvol = minbox.Width() * minbox.Height() * minbox.Depth(); Box3 b; float vol; if (!IsInside(mesh)) return false; if (!GetBound(&b, NONE)) return false; vol = b.Width() * b.Height() * b.Depth(); if ((minvol == 0) || (minvol > vol)) { minbox = b; // new minimum volume box minvol = vol; } return true; } bool Octree::Hit(Ray& ray, float& distance) const { Box3 bound; if (GetBound(&bound, NONE)) return bound.Hit(ray, distance, NULL); return false; } intptr Octree::Cull(const Matrix* trans, Scene* scene) { Box3 box; if (m_NoBounds) return DISPLAY_NONE; if (m_NoCull || !DoCulling) // do not cull this one return DISPLAY_ALL; if (Parent() == NULL) // never cull the root return DISPLAY_ALL; if (GetBound(&box, NONE) && scene->GetCamera()->IsVisible(box)) { Geometry* geo = GetGeometry(); if ((geo == NULL) || !geo->Cull(trans, scene)) return DISPLAY_ALL; // shape is visible } SceneStats* g = scene->GetStats(); Core::InterlockAdd(&(g->CulledVerts), (int) m_Verts); Core::InterlockAdd(&(g->TotalVerts), (int) m_Verts); Core::InterlockInc(&(g->CulledModels)); return DISPLAY_NONE; // model culled } } // end Vixen
28.566879
129
0.689298
[ "mesh", "geometry", "render", "shape", "model", "3d" ]
7486e832c570f520f323d47b38cb301fe3278b7f
7,260
cpp
C++
src/file-watcher/FileWatcher_win32.cpp
jheruty/hotswap-cpp
74175b028bf5dd0aa0dc8450f5251e6dfdf0e380
[ "MIT" ]
7
2021-05-25T11:31:00.000Z
2022-03-16T08:39:03.000Z
src/file-watcher/FileWatcher_win32.cpp
jheruty/hotswap-cpp
74175b028bf5dd0aa0dc8450f5251e6dfdf0e380
[ "MIT" ]
1
2021-06-07T20:01:41.000Z
2021-06-16T13:43:23.000Z
src/file-watcher/FileWatcher_win32.cpp
jheruty/hotswap-cpp
74175b028bf5dd0aa0dc8450f5251e6dfdf0e380
[ "MIT" ]
3
2021-07-08T07:33:03.000Z
2021-08-21T06:50:31.000Z
#include <algorithm> #include <assert.h> #include "hscpp/file-watcher/FileWatcher_win32.h" #include "hscpp/Log.h" #include "hscpp/Util.h" namespace hscpp { const static std::chrono::milliseconds DEBOUNCE_TIME = std::chrono::milliseconds(20); FileWatcher::FileWatcher(FileWatcherConfig *pConfig) : m_pConfig(pConfig) {} FileWatcher::~FileWatcher() { ClearAllWatches(); } bool FileWatcher::AddWatch(const fs::path& directoryPath) { auto pWatch = std::unique_ptr<DirectoryWatch>(new DirectoryWatch()); // FILE_FLAG_BACKUP_SEMANTICS is necessary to open a directory. HANDLE hDirectory = CreateFileW( directoryPath.wstring().c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (hDirectory == INVALID_HANDLE_VALUE) { log::Error() << HSCPP_LOG_PREFIX << "Failed to add directory " << directoryPath << " to watch. " << log::LastOsError() << log::End(); return false; } pWatch->directoryPath = directoryPath; pWatch->hDirectory = hDirectory; pWatch->pFileWatcher = this; if (!ReadDirectoryChangesAsync(pWatch.get())) { log::Error() << HSCPP_LOG_PREFIX << "Failed initial call to ReadDirectoryChangesW. " << log::LastOsError() << log::End(); CloseHandle(hDirectory); return false; } m_DirectoryHandles.push_back(hDirectory); m_Watchers.push_back(std::move(pWatch)); return true; } bool FileWatcher::RemoveWatch(const fs::path& directoryPath) { auto watchIt = std::find_if(m_Watchers.begin(), m_Watchers.end(), [directoryPath](const std::unique_ptr<DirectoryWatch>& pWatch) { return pWatch->directoryPath == directoryPath; }); if (watchIt == m_Watchers.end()) { log::Error() << HSCPP_LOG_PREFIX << "Directory " << directoryPath << "could not be found." << log::End(); return false; } DirectoryWatch* pWatch = watchIt->get(); EraseDirectoryHandle(pWatch->hDirectory); CloseWatch(pWatch); m_Watchers.erase(watchIt); return true; } void FileWatcher::ClearAllWatches() { for (const auto& pWatch : m_Watchers) { EraseDirectoryHandle(pWatch->hDirectory); CloseWatch(pWatch.get()); } m_Watchers.clear(); } void FileWatcher::PollChanges(std::vector<Event>& events) { events.clear(); // Trigger WatchCallback if a file change was detected. WaitForMultipleObjectsEx(static_cast<DWORD>(m_DirectoryHandles.size()), m_DirectoryHandles.data(), false, 0, true); // We will gather the events that occur over the next m_PollFrequency ms. This makes it // easier to deal with temporary files that occur during saving, as one can be reasonably // confident that these files have been created and removed within a sufficiently long // m_PollFrequency period. if (!m_bGatheringEvents && m_PendingEvents.size() > 0) { // Begin gathering events. m_bGatheringEvents = true; m_LastPollTime = std::chrono::steady_clock::now(); return; } else { // Currently gathering events. Return if not enough time has passed yet. auto now = std::chrono::steady_clock::now(); auto dt = now - m_LastPollTime; if (dt < m_pConfig->latency) { return; } } // Done gathering events. m_bGatheringEvents = false; events = m_PendingEvents; m_PendingEvents.clear(); } void FileWatcher::PushPendingEvent(const Event& event) { m_PendingEvents.push_back(event); } void WINAPI FileWatcher::WatchCallback(DWORD error, DWORD nBytesTransferred, LPOVERLAPPED overlapped) { UNREFERENCED_PARAMETER(nBytesTransferred); if (error != ERROR_SUCCESS) { log::Error() << HSCPP_LOG_PREFIX << "ReadDirectoryChangesW failed. " << log::OsError(error) << log::End(); return; } FILE_NOTIFY_INFORMATION* pNotify = nullptr; DirectoryWatch* pWatch = reinterpret_cast<DirectoryWatch*>(overlapped); size_t offset = 0; do { pNotify = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(&pWatch->buffer[offset]); offset += pNotify->NextEntryOffset; std::wstring fileName(pNotify->FileName, pNotify->FileNameLength / sizeof(WCHAR)); Event event; event.filePath = pWatch->directoryPath / fileName; pWatch->pFileWatcher->PushPendingEvent(event); } while (pNotify->NextEntryOffset != 0); if (!ReadDirectoryChangesAsync(pWatch)) { log::Error() << HSCPP_LOG_PREFIX << "Failed refresh call to ReadDirectoryChangesW. " << log::LastOsError() << log::End(); return; } } bool FileWatcher::ReadDirectoryChangesAsync(DirectoryWatch* pWatch) { // OVERLAPPED struct must be zero-initialized before calling ReadDirectoryChangesW. pWatch->overlapped = {}; return ReadDirectoryChangesW( pWatch->hDirectory, pWatch->buffer, sizeof(pWatch->buffer), false, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SIZE, NULL, &pWatch->overlapped, WatchCallback) != 0; } void FileWatcher::CloseWatch(DirectoryWatch* pWatch) { bool bResult = (CancelIoEx(pWatch->hDirectory, &pWatch->overlapped) != 0); if (!bResult) { log::Error() << HSCPP_LOG_PREFIX << "Failed to cancel IO. " << log::LastOsError() << log::End(); return; } // Wait for IO to be canceled. DWORD nBytesTransferred = 0; bResult = (GetOverlappedResult(pWatch->hDirectory, &pWatch->overlapped, &nBytesTransferred, true) != 0); // If we were in the middle of an IO operation (like ReadDirectoryChangesW) and call CancelIoEx, // GetOverlappedResult returns false, with ERROR_OPERATON_ABORTED. if (!bResult && GetLastError() != ERROR_OPERATION_ABORTED) { log::Error() << HSCPP_LOG_PREFIX << "Failed to wait on overlapped result. " << log::LastOsError() << log::End(); return; } CloseHandle(pWatch->hDirectory); } void FileWatcher::EraseDirectoryHandle(HANDLE hDirectory) { auto directoryIt = std::find_if(m_DirectoryHandles.begin(), m_DirectoryHandles.end(), [hDirectory](HANDLE h) { return hDirectory == h; }); m_DirectoryHandles.erase(directoryIt); } }
32.123894
129
0.594353
[ "vector" ]
7488c6cf525e315cec6bb7d6d215e328ea19bdcd
16,823
hpp
C++
Middlewares/ST/touchgfx_backup/framework/include/touchgfx/widgets/canvas/AbstractShape.hpp
koson/car-dash
7be8f02a243d43b4fd9fd33b0a160faa5901f747
[ "MIT" ]
12
2020-06-25T13:10:17.000Z
2022-01-27T01:48:26.000Z
Middlewares/ST/touchgfx_backup/framework/include/touchgfx/widgets/canvas/AbstractShape.hpp
koson/car-dash
7be8f02a243d43b4fd9fd33b0a160faa5901f747
[ "MIT" ]
2
2021-05-23T05:02:48.000Z
2021-05-24T11:15:56.000Z
Middlewares/ST/touchgfx_backup/framework/include/touchgfx/widgets/canvas/AbstractShape.hpp
koson/car-dash
7be8f02a243d43b4fd9fd33b0a160faa5901f747
[ "MIT" ]
7
2020-08-27T08:23:49.000Z
2021-09-19T12:54:30.000Z
/** ****************************************************************************** * This file is part of the TouchGFX 4.13.0 distribution. * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifndef ABSTRACTSHAPE_HPP #define ABSTRACTSHAPE_HPP #include <touchgfx/hal/Types.hpp> #include <touchgfx/widgets/Widget.hpp> #include <touchgfx/widgets/canvas/CanvasWidget.hpp> namespace touchgfx { /** * @class AbstractShape AbstractShape.hpp touchgfx/widgets/canvas/AbstractShape.hpp * * @brief Simple widget capable of drawing a abstractShape. * * Simple widget capable of drawing a abstractShape. The abstractShape can be scaled and * rotated around 0,0. Note that the y axis goes down, so a abstractShape that goes up * must be given negative coordinates. * * @see CanvasWidget * * ### tparam T The type of the points used for the abstractShape. Must be int or float. */ class AbstractShape : public CanvasWidget { public: /** * @struct ShapePoint AbstractShape.hpp touchgfx/widgets/canvas/AbstractShape.hpp * * @brief Defines an alias representing the array of points making up the abstract shape. * * Defines an alias representing the array of points making up the abstract shape. * This will help setting up the abstractShape very easily using setAbstractShape(). * * @tparam T Generic type parameter, either int or float. * * @see setAbstractShape() */ template <typename T> struct ShapePoint { T x; ///< The x coordinate of the points. T y; ///< The y coordinate of the points. }; /** * @fn AbstractShape::AbstractShape(); * * @brief Constructs a new AbstractShape. * * Constructs a new AbstractShape. */ AbstractShape(); /** * @fn virtual AbstractShape::~AbstractShape(); * * @brief Virtual Destructor. * * Virtual Destructor. */ virtual ~AbstractShape(); /** * @fn virtual int AbstractShape::getNumPoints() const = 0; * * @brief Gets number points used to make up the shape. * * Gets number points used to make up the shape. * * @return The number points. */ virtual int getNumPoints() const = 0; /** * @fn virtual void AbstractShape::setCorner(int i, CWRUtil::Q5 x, CWRUtil::Q5 y) = 0; * * @brief Sets a corner of the shape. * * Sets a corner of the shape in Q5 format. * * @param i Zero-based index of the corner. * @param x The x coordinate in Q5 format. * @param y The y coordinate in Q5 format. * * @note Remember to call updateAbstractShapeCache() to make sure that the cached outline of * the shape is correct. * @see updateAbstractShapeCache */ virtual void setCorner(int i, CWRUtil::Q5 x, CWRUtil::Q5 y) = 0; /** * @fn virtual CWRUtil::Q5 AbstractShape::getCornerX(int i) const = 0; * * @brief Gets the x coordinate of a corner. * * Gets the x coordinate of a corner. * * @param i Zero-based index of the corner. * * @return The corner x coordinate. */ virtual CWRUtil::Q5 getCornerX(int i) const = 0; /** * @fn virtual CWRUtil::Q5 AbstractShape::getCornerY(int i) const = 0; * * @brief Gets the y coordinate of a corner. * * Gets the y coordinate of a corner. * * @param i Zero-based index of the corner. * * @return The corner y coordinate. */ virtual CWRUtil::Q5 getCornerY(int i) const = 0; /** * @fn template <typename T> void AbstractShape::setShape(ShapePoint<T>* points) * * @brief Sets a shape the struct Points. * * Sets a shape the struct Points. The cached outline of the shape is automatically * updated. * * @tparam T Generic type parameter, either int or float. * @param [in] points The points that make up the shape. * * @note The area containing the shape is not invalidated. */ template <typename T> void setShape(ShapePoint<T>* points) { int numPoints = getNumPoints(); for (int i = 0; i < numPoints; i++) { setCorner(i, CWRUtil::toQ5<T>(points[i].x), CWRUtil::toQ5<T>(points[i].y)); } updateAbstractShapeCache(); } /** * @fn template <typename T> void AbstractShape::setShape(const ShapePoint<T>* points) * * @brief Sets a shape the struct Points. * * Sets a shape the struct Points. The cached outline of the shape is automatically * updated. * * @tparam T Generic type parameter, either int or float. * @param [in] points The points that make up the shape. * * @note The area containing the shape is not invalidated. */ template <typename T> void setShape(const ShapePoint<T>* points) { int numPoints = getNumPoints(); for (int i = 0; i < numPoints; i++) { setCorner(i, CWRUtil::toQ5<T>(points[i].x), CWRUtil::toQ5<T>(points[i].y)); } updateAbstractShapeCache(); } /** * @fn template <typename T> void AbstractShape::setOrigin(T x, T y) * * @brief Sets the position of (0,0). * * Sets the position of (0,0) used when the abstractShape was created. This means * that all coordinates initially used when created the shape are moved relative to * these given offsets. Calling setOrigin() again, will not add to the previous * settings of setOrigin() but will replace the old values for origin. * * @tparam T Generic type parameter, either int or float. * @param x The x coordinate of the shapes position (0,0). * @param y The y coordinate of the shapes position (0,0). * * @note The area containing the AbstractShape is not invalidated. * * @see moveOrigin() */ template <typename T> void setOrigin(T x, T y) { CWRUtil::Q5 dxNew = CWRUtil::toQ5<T>(x); CWRUtil::Q5 dyNew = CWRUtil::toQ5<T>(y); if (dx == dxNew && dy == dyNew) { return; } dx = dxNew; dy = dyNew; updateAbstractShapeCache(); } /** * @fn template <typename T> void AbstractShape::moveOrigin(T x, T y) * * @brief Moves the start point for this AbstractShape. * * Moves the start point for this AbstractShape. The rectangle that surrounds the * old and new area covered by the shape will be invalidated. * * * @tparam T Generic type parameter, either int or float. * @param x The x coordinate of the shapes position (0,0). * @param y The y coordinate of the shapes position (0,0). * * @note The area containing the AbstractShape is invalidated before and after the change. * * @see setOrigin() */ template <typename T> void moveOrigin(T x, T y) { CWRUtil::Q5 xNew = CWRUtil::toQ5<T>(x); CWRUtil::Q5 yNew = CWRUtil::toQ5<T>(y); if (dx == xNew && dy == yNew) { return; } Rect rect = getMinimalRect(); dx = xNew; dy = yNew; updateAbstractShapeCache(); rect.expandToFit(getMinimalRect()); invalidateRect(rect); } /** * @fn template <typename T> void AbstractShape::getOrigin(T& dx, T& dy) const * * @brief Gets the start coordinates for the line. * * Gets the start coordinates for the line. * * @tparam T Generic type parameter, either int or float. * @param [out] dx The x coordinate. * @param [out] dy The y coordinate. */ template <typename T> void getOrigin(T& dx, T& dy) const { dx = this->dx.to<T>(); dy = this->dy.to<T>(); } /** * @fn template <typename T> void AbstractShape::setAngle(T angle) * * @brief Sets the angle to turn the abstractShape. * * Sets the angle to turn the abstractShape. 0 degrees is straight up and 90 degrees * is 3 o'clock. * * @tparam T Generic type parameter. * @param angle The angle to turn the abstractShape to relative to 0 (straight up), not relative * to the previous angle. * * @note The area containing the AbstractShape is not invalidated. * * @see updateAngle() */ template <typename T> void setAngle(T angle) { CWRUtil::Q5 angleQ5 = CWRUtil::toQ5<T>(angle); if (shapeAngle != angleQ5) { shapeAngle = angleQ5; updateAbstractShapeCache(); } } /** * @fn template <typename T> void AbstractShape::getAngle(T& angle) * * @brief Gets the abstractShape's angle. * * Gets the abstractShape's angle. * * @tparam T Generic type parameter. * @param [out] angle The current abstractShape angle relative to 0. */ template <typename T> void getAngle(T& angle) { angle = this->shapeAngle.to<T>(); } /** * @fn template <typename T> void AbstractShape::updateAngle(T angle) * * @brief Sets the angle to turn the abstractShape. * * Sets the angle to turn the abstractShape. 0 degrees is straight up and 90 degrees * is 3 o'clock. * * @tparam T Generic type parameter. * @param angle The angle to turn the abstractShape. * * @note The area containing the AbstractShape is invalidated before and after the change. * * @see setAngle() */ template <typename T> void updateAngle(T angle) { CWRUtil::Q5 angleQ5 = CWRUtil::toQ5<T>(angle); if (shapeAngle != angleQ5) { Rect rectBefore = getMinimalRect(); shapeAngle = angleQ5; updateAbstractShapeCache(); Rect rectAfter = getMinimalRect(); rectBefore.expandToFit(rectAfter); invalidateRect(rectBefore); } } /** * @fn template <typename T> T AbstractShape::getAngle() const * * @brief Gets the current angle of the abstractShape. * * Gets the current angle of the abstractShape. * * @return The angle of the AbstractShape. */ int getAngle() const { return shapeAngle.to<int>(); } /** * @fn template <typename T> void AbstractShape::setScale(T newXScale, T newYScale) * * @brief Scale the AbstractShape. * * Scale the AbstractShape the given amounts in the x direction and the y direction. * * @tparam T Generic type parameter, either int or float. * @param newXScale The new scale in the x direction. * @param newYScale The new scale in the y direction. * * @note The area containing the AbstractShape is not invalidated. * * @see getScale, updateScale */ template <typename T> void setScale(T newXScale, T newYScale) { xScale = CWRUtil::toQ10<T>(newXScale); yScale = CWRUtil::toQ10<T>(newYScale); updateAbstractShapeCache(); } /** * @fn template <typename T> void AbstractShape::setScale(T scale) * * @brief Scale the AbstractShape. * * Scale the AbstractShape the given amount in the x direction and the y direction. * * @tparam T Generic type parameter, either int or float. * @param scale The scale in the x direction. * * @note The area containing the AbstractShape is not invalidated. * * @see getScale */ template <typename T> void setScale(T scale) { setScale(scale, scale); } /** * @fn template <typename T> void AbstractShape::updateScale(T newXScale, T newYScale) * * @brief Scale the AbstractShape. * * Scale the AbstractShape the given amounts in the x direction and the y direction. * * @tparam T Generic type parameter, either int or float. * @param newXScale The new scale in the x direction. * @param newYScale The new scale in the y direction. * * @note The area containing the AbstractShape is invalidated before and after the change. * * @see setScale() */ template <typename T> void updateScale(T newXScale, T newYScale) { CWRUtil::Q10 xScaleQ10 = CWRUtil::toQ10<T>(newXScale); CWRUtil::Q10 yScaleQ10 = CWRUtil::toQ10<T>(newYScale); if (xScale != xScaleQ10 || yScale != yScaleQ10) { Rect rectBefore = getMinimalRect(); xScale = xScaleQ10; yScale = yScaleQ10; updateAbstractShapeCache(); Rect rectAfter = getMinimalRect(); rectBefore.expandToFit(rectAfter); invalidateRect(rectBefore); } } /** * @fn template <typename T> void AbstractShape::getScale(T& x, T& y) const * * @brief Gets the x scale and y scale. * * Gets the x scale and y scale of the shape as previously set using setScale. Default * is 1 for both x scale and y scale. * * @tparam T Generic type parameter, either int or float. * @param [out] x Scaling of x coordinates. * @param [out] y Scaling of y coordinates. * * @see setScale */ template <typename T> void getScale(T& x, T& y) const { x = xScale.to<T>(); y = yScale.to<T>(); } /** * @fn virtual bool AbstractShape::drawCanvasWidget(const Rect& invalidatedArea) const; * * @brief Draws the AbstractShape. * * Draws the AbstractShape. This class supports partial drawing, so only the area * described by the rectangle will be drawn. * * @param invalidatedArea The rectangle to draw, with coordinates relative to this drawable. * * @return true if it succeeds, false if it fails. */ virtual bool drawCanvasWidget(const Rect& invalidatedArea) const; /** * @fn void AbstractShape::updateAbstractShapeCache(); * * @brief Updates the abstractShape cache. * * Updates the abstractShape cache. The cache is used to be able to quickly redraw * the AbstractShape without calculating the points that make up the abstractShape * (with regards to scaling and rotation). */ void updateAbstractShapeCache(); protected: /** * @fn virtual void AbstractShape::setCache(int i, CWRUtil::Q5 x, CWRUtil::Q5 y) = 0; * * @brief Sets the cached coordinates of a given corner. * * Sets the cached coordinates of a given corner. The coordinates in the cache are * the coordinates from the corners after rotating and scaling the coordinate. * * @param i Zero-based index of the corner. * @param x The x coordinate. * @param y The y coordinate. */ virtual void setCache(int i, CWRUtil::Q5 x, CWRUtil::Q5 y) = 0; /** * @fn virtual CWRUtil::Q5 AbstractShape::getCacheX(int i) const = 0; * * @brief Gets cached x coordinate of a corner. * * Gets cached x coordinate of a corner. * * @param i Zero-based index of the corner. * * @return The cached x coordinate. */ virtual CWRUtil::Q5 getCacheX(int i) const = 0; /** * @fn virtual CWRUtil::Q5 AbstractShape::getCacheY(int i) const = 0; * * @brief Gets cached y coordinate of a corner. * * Gets cached y coordinate of a corner. * * @param i Zero-based index of the corner. * * @return The cached y coordinate. */ virtual CWRUtil::Q5 getCacheY(int i) const = 0; /** * @fn virtual Rect AbstractShape::getMinimalRect() const; * * @brief Gets minimal rectangle containing the abstractShape. * * Gets minimal rectangle containing the abstractShape. Used for invalidating only * the required part of the screen. * * @return The minimal rectangle. */ virtual Rect getMinimalRect() const; private: CWRUtil::Q5 dx, dy; CWRUtil::Q5 shapeAngle; CWRUtil::Q10 xScale, yScale; Rect minimalRect; }; } // namespace touchgfx #endif // ABSTRACTSHAPE_HPP
30.698905
100
0.594484
[ "shape" ]
74894fb9e8d06e697dfa4fb71f384dddac342f85
2,054
cpp
C++
Dev/asd_cpp/core/IO/asd.Decryptor.cpp
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
37
2015-07-12T14:21:03.000Z
2020-10-17T03:08:17.000Z
Dev/asd_cpp/core/IO/asd.Decryptor.cpp
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
91
2015-06-14T10:47:22.000Z
2020-06-29T18:05:21.000Z
Dev/asd_cpp/core/IO/asd.Decryptor.cpp
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
14
2015-07-13T04:15:20.000Z
2021-09-30T01:34:51.000Z
#include <vector> #include "asd.Decryptor.h" namespace asd { Decryptor::Decryptor(const astring& key) { if (key != astring()) { // 古いバージョン { std::vector<int8_t> key_temp; std::vector<uint8_t> key_; Utf16ToUtf8(key_temp, (const int16_t*) key.c_str()); key_.resize(key_temp.size()); memcpy(key_.data(), key_temp.data(), key_temp.size()); key_.pop_back(); for (int loop = 0; loop < 40; loop++) { for (size_t i = 0; i < key_.size(); i++) { int k = (int) key_[i]; k = (k + (loop + i)) % 255; keys[0].push_back((uint8_t) k); } } } // 新しいバージョン { // 線形合同法 int32_t seed_ = 1; auto rand_ = [&]() -> int32_t { seed_ = seed_ * 214013 + 2531011; return(int) (seed_ >> 16) & 32767; }; auto srand_ = [&](int32_t seed) -> void { seed_ = seed; if (seed == 0) rand_(); }; std::vector<int8_t> str_temp; std::vector<uint8_t> str_; Utf16ToUtf8(str_temp, (const int16_t*) key.c_str()); str_.resize(str_temp.size()); memcpy(str_.data(), str_temp.data(), str_temp.size()); str_.pop_back(); uint32_t r = 0xFFFFFF; for (size_t i = 0; i < str_.size(); i++) { r ^= (uint32_t) (str_[i] ^ 0x17); for (int32_t b = 0; b < 8; b++) { if ((b & 1) != 0) { r = (r >> 1) ^ 0x13579A; } else { r = r>> 1; } } } srand_((int32_t)r); for (int32_t i = 0; i < 2048; i++) { keys[1].push_back((uint8_t) rand_()); } } } } void Decryptor::ChangeVersion(int32_t version) { if (this->version > 0) { assert(0); } this->version = version; } bool Decryptor::IsValid() { return keys[version].size() > 0; } void Decryptor::Decrypt(uint8_t* bytes, int64_t start, int64_t count, int64_t globalPos) { auto& keys_ = keys[version]; if (keys_.size() > 0) { for (auto i = start; i < start+count; ++i) { bytes[i] = (bytes[i] ^ keys_[(i + globalPos) % keys_.size()]); } } } }
18.339286
89
0.516553
[ "vector" ]
74915290c85fd6a62a57e3ba8d3f3b1c31af6db5
12,299
cpp
C++
modules/camera_tracking_and_mapping/src/TSFilterCloudsXYZRGB.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
17
2015-11-16T14:21:10.000Z
2020-11-09T02:57:33.000Z
modules/camera_tracking_and_mapping/src/TSFilterCloudsXYZRGB.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
35
2015-07-27T15:04:43.000Z
2019-08-22T10:52:35.000Z
modules/camera_tracking_and_mapping/src/TSFilterCloudsXYZRGB.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
18
2015-08-06T09:26:27.000Z
2020-09-03T01:31:00.000Z
/** * $Id$ * * @author Johann Prankl * */ #include <v4r/camera_tracking_and_mapping/TSFilterCloudsXYZRGB.h> #include <v4r/keypoints/impl/invPose.hpp> #include <v4r/common/convertImage.h> #include <pcl/common/transforms.h> #include <v4r/reconstruction/impl/projectPointToImage.hpp> #include <pcl/common/time.h> namespace v4r { using namespace std; std::vector<cv::Vec4i> TSFilterCloudsXYZRGB::npat = std::vector<cv::Vec4i>(); /************************************************************************************ * Constructor/Destructor */ TSFilterCloudsXYZRGB::TSFilterCloudsXYZRGB(const Parameter &p) : width(0), height(0), sf_timestamp(0), sf_pose(Eigen::Matrix4f::Identity()), run(false), have_thread(false) { setParameter(p); } TSFilterCloudsXYZRGB::~TSFilterCloudsXYZRGB() { if (have_thread) stop(); } /** * operate */ void TSFilterCloudsXYZRGB::operate() { bool have_todo; Eigen::Matrix4f inv_pose; v4r::DataMatrix2D<Surfel> sf_cloud_local; std::list< v4r::triple< pcl::PointCloud<pcl::PointXYZRGB>::Ptr, Eigen::Matrix4f, double > > frames_local; std::list< v4r::triple< pcl::PointCloud<pcl::PointXYZRGB>::Ptr, Eigen::Matrix4f, double > >::iterator it0, itm, itp; while(run) { have_todo = false; mtx_shm.lock(); if (frames.size()==(unsigned)param.batch_size_clouds) { frames_local = frames; frames.clear(); have_todo = true; } mtx_shm.unlock(); if (have_todo) { if ( tgt_intrinsic.empty()) throw std::runtime_error("[TSFilterCloudsXYZRGB::addCloud] Camera parameter not available"); it0 = std::next(frames_local.begin(), frames_local.size()/2); initKeyframe(*it0->first); itp=itm=it0; itp++; for (; itm!=frames_local.begin() && itp!=frames_local.end(); itm--, itp++) { if (itm!=frames_local.begin()) { invPose(itm->second, inv_pose); //integrateData(*itm->first, it0->second*inv_pose); integrateDataRGB(*itm->first, it0->second*inv_pose); } if (itp!=frames_local.end()) { invPose(itp->second, inv_pose); //integrateData(*itp->first, it0->second*inv_pose); integrateDataRGB(*itp->first, it0->second*inv_pose); } } project3D(sf_cloud_local, 0.5); computeNormals(sf_cloud_local,2); mtx_shm.lock(); sf_timestamp = it0->third; sf_pose = it0->second; sf_cloud = sf_cloud_local; mtx_shm.unlock(); have_todo = false; } if (!have_todo) usleep(10000); } } /** * @brief TSFilterCloudsXYZRGB::initKeyframe */ void TSFilterCloudsXYZRGB::initKeyframe(const pcl::PointCloud<pcl::PointXYZRGB> &cloud0) { depth = cv::Mat_<float>::zeros(height, width); depth_weight = cv::Mat_<float>::zeros(height, width); im_bgr = cv::Mat_<cv::Vec3f>::zeros(height, width); if (cloud0.isOrganized()) { float scale_x = ((float)width)/(float)cloud0.width; float scale_y = ((float)height)/(float)cloud0.height; for (unsigned v=0; v<cloud0.height; v++) { for (unsigned u=0; u<cloud0.width; u++) { cv::Vec3f &c = im_bgr(scale_y*v, scale_x*u); const pcl::PointXYZRGB &pt = cloud0(u,v); c[0] = pt.b; c[1] = pt.g; c[2] = pt.r; } } } } /** * @brief TSFilterCloudsXYZRGB::integrateData * @param cloud in camera coordinates * @param pose to transform the cloud from global coordinates to camera coordinates */ void TSFilterCloudsXYZRGB::integrateData(const pcl::PointCloud<pcl::PointXYZRGB> &cloud, const Eigen::Matrix4f &pose) { int x,y; cv::Point2f im_pt; pcl::transformPointCloud(cloud,tmp_cloud,pose); // tranform filt cloud to current frame and update for (unsigned i=0; i<tmp_cloud.points.size(); i++) { const pcl::PointXYZRGB &pt3 = tmp_cloud.points[i]; if (isnan(pt3.x) || isnan(pt3.y) || isnan(pt3.z)) continue; projectPointToImage(&pt3.x, &tgt_intrinsic(0,0), &im_pt.x); x = (int)(im_pt.x); y = (int)(im_pt.y); if (x<0 || y<0 || x>=width || y>=height) continue; float &d = depth(y,x); float &w = depth_weight(y,x); if (w>0) { if (fabs(1./d - 1./pt3.z) < param.inv_depth_cut_off) { d = (w*d + pt3.z); w += 1.; d /= w; } else { w -= 1.; } } else { d = pt3.z; w=1.; } } } /** * @brief TSFilterCloudsXYZRGB::integrateDataRGB * @param cloud * @param pose */ void TSFilterCloudsXYZRGB::integrateDataRGB(const pcl::PointCloud<pcl::PointXYZRGB> &cloud, const Eigen::Matrix4f &pose) { int x,y; cv::Point2f im_pt; pcl::transformPointCloud(cloud,tmp_cloud,pose); // tranform filt cloud to current frame and update for (unsigned i=0; i<tmp_cloud.points.size(); i++) { const pcl::PointXYZRGB &pt3 = tmp_cloud.points[i]; if (isnan(pt3.x) || isnan(pt3.y) || isnan(pt3.z)) continue; projectPointToImage(&pt3.x, &tgt_intrinsic(0,0), &im_pt.x); x = (int)(im_pt.x); y = (int)(im_pt.y); if (x<0 || y<0 || x>=width || y>=height) continue; float &d = depth(y,x); cv::Vec3f &col = im_bgr(y,x); float &w = depth_weight(y,x); if (w>0) { if (fabs(1./d - 1./pt3.z) < param.inv_depth_cut_off) { d = (w*d + pt3.z); col[0] = (w*col[0]+pt3.b); col[1] = (w*col[1]+pt3.g); col[2] = (w*col[2]+pt3.r); w += 1.; d /= w; col[0] /= w; col[1] /= w; col[2] /= w; } else { w -= 1.; } } else { d = pt3.z; col[0] = pt3.b; col[1] = pt3.g; col[2] = pt3.r; w=1.; } } } void TSFilterCloudsXYZRGB::project3D(v4r::DataMatrix2D<Surfel> &_sf_cloud, const float &px_offs) { double *C = &tgt_intrinsic(0,0); double invC0 = 1./C[0]; double invC4 = 1./C[4]; _sf_cloud.resize(depth.rows, depth.cols); for (int v=0; v<depth.rows; v++) { for (int u=0; u<depth.cols; u++) { Surfel &sf = _sf_cloud(v,u); sf.weight = depth_weight(v,u); if (sf.weight>std::numeric_limits<float>::epsilon()) { sf.pt[2] = depth(v,u); sf.pt[0] = sf.pt[2] * (( ((float)u)+px_offs-C[2]) * invC0); sf.pt[1] = sf.pt[2] * (( ((float)v)+px_offs-C[5]) * invC4); } else sf = Surfel(); const cv::Vec3b &c = im_bgr(v,u); sf.r = c[2]; sf.g = c[1]; sf.b = c[0]; } } } /** * @brief TSFilterCloudsXYZRGB::selectintegrateDataFrame * @param pose0 * @param pose1 * @return */ bool TSFilterCloudsXYZRGB::selectFrame(const Eigen::Matrix4f &pose0, const Eigen::Matrix4f &pose1) { Eigen::Matrix4f inv_pose0, inv_pose1; invPose(pose0, inv_pose0); invPose(pose1, inv_pose1); if ( (inv_pose0.block<3,1>(0,2).dot(inv_pose1.block<3,1>(0,2)) > cos_delta_angle_select_frame) && (inv_pose0.block<3,1>(0,3)-inv_pose1.block<3,1>(0,3)).squaredNorm() < sqr_cam_distance_select_frame ) return false; return true; } /***************************************************************************************/ /** * start */ void TSFilterCloudsXYZRGB::start() { if (tgt_intrinsic.empty()) throw std::runtime_error("[TSFilterCloudsXYZRGB::start] No camera parameter available!"); if (have_thread) stop(); run = true; th_obectmanagement = boost::thread(&TSFilterCloudsXYZRGB::operate, this); have_thread = true; } /** * stop */ void TSFilterCloudsXYZRGB::stop() { run = false; th_obectmanagement.join(); have_thread = false; } /** * reset */ void TSFilterCloudsXYZRGB::reset() { stop(); frames.clear(); sf_cloud.clear(); sf_timestamp = 0; sf_pose.setIdentity(); } /** * @brief TSFilterCloudsXYZRGB::addCloud * @param cloud * @param pose * @param have_track */ void TSFilterCloudsXYZRGB::addCloud(const pcl::PointCloud<pcl::PointXYZRGB> &cloud, const Eigen::Matrix4f &pose, const double &_timestamp, bool have_track) { if (!isStarted()) start(); mtx_shm.lock(); if (!have_track) frames.clear(); if ( selectFrame(pose, frames.back().second) ) { if (frames.size()==(unsigned)param.batch_size_clouds) frames.pop_front(); frames.push_back( v4r::triple< pcl::PointCloud<pcl::PointXYZRGB>::Ptr, Eigen::Matrix4f, double >( pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>()), pose, _timestamp) ); pcl::copyPointCloud(cloud, *frames.back().first); } mtx_shm.unlock(); } /** * @brief TSFilterCloudsXYZRGB::computeRadius * @param sf_cloud */ void TSFilterCloudsXYZRGB::computeRadius(v4r::DataMatrix2D<Surfel> &sf_cloud, const cv::Mat_<double> &intrinsic) { const float norm = 1./sqrt(2)*(2./(intrinsic(0,0)+intrinsic(1,1))); for (int v=0; v<sf_cloud.rows; v++) { for (int u=0; u<sf_cloud.cols; u++) { Surfel &s = sf_cloud(v,u); if (std::isnan(s.pt[0]) || std::isnan(s.pt[1]) || std::isnan(s.pt[2])) { s.radius = 0.; continue; } s.radius = norm*s.pt[2]; } } } /** * @brief TSFilterCloudsXYZRGB::computeNormals * @param sf_cloud */ void TSFilterCloudsXYZRGB::computeNormals(v4r::DataMatrix2D<Surfel> &sf_cloud, int nb_dist) { { npat.resize(4); npat[0] = cv::Vec4i(nb_dist,0,0,nb_dist); npat[1] = cv::Vec4i(0,nb_dist,-nb_dist,0); npat[2] = cv::Vec4i(-nb_dist,0,0,-nb_dist); npat[3] = cv::Vec4i(0,-nb_dist,0,nb_dist); } Surfel *s1, *s2, *s3; Eigen::Vector3f l1, l2; int z; for (int v=0; v<sf_cloud.rows; v++) { for (int u=0; u<sf_cloud.cols; u++) { s2=s3=0; s1 = &sf_cloud(v,u); if (std::isnan(s1->pt[0]) || std::isnan(s1->pt[1]) || std::isnan(s1->pt[2])) continue; for (z=0; z<4; z++) { const cv::Vec4i &p = npat[z]; if (u+p[0]>=0 && u+p[0]<sf_cloud.cols && v+p[1]>=0 && v+p[1]<sf_cloud.rows && u+p[2]>=0 && u+p[2]<sf_cloud.cols && v+p[3]>=0 && v+p[3]<sf_cloud.rows) { s2 = &sf_cloud(v+p[1],u+p[0]); if (std::isnan(s2->pt[0]) || std::isnan(s2->pt[1]) || std::isnan(s2->pt[2])) continue; s3 = &sf_cloud(v+p[3],u+p[2]); if (std::isnan(s3->pt[0]) || std::isnan(s3->pt[1]) || std::isnan(s3->pt[2])) continue; break; } } if (z<4) { l1 = s2->pt-s1->pt; l2 = s3->pt-s1->pt; s1->n = l1.cross(l2).normalized(); if (s1->n.dot(s1->pt) > 0) s1->n *= -1; } else s1->n = Eigen::Vector3f(std::numeric_limits<float>::quiet_NaN(),std::numeric_limits<float>::quiet_NaN(),std::numeric_limits<float>::quiet_NaN()); } } } void TSFilterCloudsXYZRGB::getFilteredCloudNormals(pcl::PointCloud<pcl::PointXYZRGBNormal> &cloud, Eigen::Matrix4f &pose, double &timestamp) { mtx_shm.lock(); cloud.resize(sf_cloud.data.size()); cloud.width = sf_cloud.cols; cloud.height = sf_cloud.rows; cloud.is_dense = false; for (unsigned i=0; i<sf_cloud.data.size(); i++) { const Surfel &s = sf_cloud.data[i]; pcl::PointXYZRGBNormal &o = cloud.points[i]; o.getVector3fMap() = s.pt; o.r = s.r; o.g = s.g; o.b = s.b; o.getNormalVector3fMap() = s.n; } timestamp = sf_timestamp; pose = sf_pose; mtx_shm.unlock(); } void TSFilterCloudsXYZRGB::getSurfelCloud(v4r::DataMatrix2D<Surfel> &cloud, Eigen::Matrix4f &pose, double &timestamp) { mtx_shm.lock(); cloud = sf_cloud; timestamp = sf_timestamp; pose = sf_pose; mtx_shm.unlock(); } /** * setCameraParameter */ void TSFilterCloudsXYZRGB::setCameraParameterTSF(const cv::Mat &_intrinsic, int _width, int _height) { width = _width; height = _height; if (_intrinsic.type() != CV_64F) _intrinsic.convertTo(tgt_intrinsic, CV_64F); else tgt_intrinsic = _intrinsic; reset(); } /** * @brief TSFilterCloudsXYZRGB::setParameter * @param p */ void TSFilterCloudsXYZRGB::setParameter(const Parameter &p) { param = p; sqr_cam_distance_select_frame = param.cam_distance_select_frame*param.cam_distance_select_frame; cos_delta_angle_select_frame = cos(param.angle_select_frame*M_PI/180.); if (param.batch_size_clouds<3) throw std::runtime_error("[TSFilterCloudsXYZRGB::setParameter] batch_size_clouds need to be > 2"); } }
23.561303
203
0.594195
[ "vector", "transform" ]
7492fd08ec8f866b5221ab58868e2b0fb1f0c7e2
34,083
cxx
C++
PWGLF/NUCLEX/Nuclei/Nucleipp/AliAnalysisTaskB2.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
1
2021-06-11T20:36:16.000Z
2021-06-11T20:36:16.000Z
PWGLF/NUCLEX/Nuclei/Nucleipp/AliAnalysisTaskB2.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
1
2017-03-14T15:11:43.000Z
2017-03-14T15:53:09.000Z
PWGLF/NUCLEX/Nuclei/Nucleipp/AliAnalysisTaskB2.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
1
2018-09-22T01:09:25.000Z
2018-09-22T01:09:25.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // Analysis task for B2 // author: Eulogio Serradilla <eulogio.serradilla@cern.ch> #include <Riostream.h> #include <TTree.h> #include <TChain.h> #include <TString.h> #include <AliLog.h> #include <AliAnalysisTask.h> #include <AliAnalysisManager.h> #include <AliESD.h> #include <AliESDEvent.h> #include <AliESDInputHandler.h> #include <AliESDtrackCuts.h> #include <AliExternalTrackParam.h> #include <AliMCEvent.h> #include <AliMCEventHandler.h> #include <AliMCVertex.h> #include <AliStack.h> #include <TParticle.h> #include <TParticlePDG.h> #include <TMCProcess.h> #include <AliTriggerAnalysis.h> // for offline signals #include <AliCentrality.h> #include <AliESDUtils.h> #include <AliESDpid.h> #include <TH1D.h> #include <TH2D.h> #include <TList.h> #include <TProfile.h> #include <TFile.h> #include "AliLnID.h" #include "AliLnHistoMap.h" #include "AliAnalysisTaskB2.h" ClassImp(AliAnalysisTaskB2) AliAnalysisTaskB2::AliAnalysisTaskB2() : AliAnalysisTask() , fSpecies("Proton") , fPartCode(AliPID::kProton) , fHeavyIons(0) , fSimulation(0) , fMultTriggerFired(0) , fCentTriggerFired(0) , fTriggerFired(0) , fGoodVertex(0) , fPileUpEvent(0) , fV0AND(0) , fNoFastOnly(0) , fNtrkMultTrigger(0) , fMinKNOmult(-10) , fMaxKNOmult(100000) , fMinCentrality(0) , fMaxCentrality(100) , fNch(0) , fNtrk(0) , fMeanNtrk(1) , fKNOmult(1) , fMinVx(-1) , fMaxVx(1) , fMinVy(-1) , fMaxVy(1) , fMinVz(-10) , fMaxVz(10) , fMinDCAxy(-1) , fMaxDCAxy(1) , fMinDCAz(-2) , fMaxDCAz(2) , fMaxNSigma(3) , fMinEta(-0.8) , fMaxEta(0.8) , fMinY(-0.5) , fMaxY(0.5) , fMCevent(0) , fESDevent(0) , fOutputContainer(0) , fHistoMap(0) , fTrackCuts(0) , fLnID(0) , fMaxNSigmaITS(3) , fMaxNSigmaTPC(3) , fMaxNSigmaTOF(3) , fTrigAna(0) , fESDpid(0) , fIsPidOwner(0) , fTimeZeroType(AliESDpid::kTOF_T0) , fTOFmatch(0) , fMinM2(2.) , fMaxM2(6.) , fMomentumCorrection(0) , fMoCpfx(0) { // // Default constructor // AliLog::SetGlobalLogLevel(AliLog::kFatal); fTrigAna = new AliTriggerAnalysis(); } AliAnalysisTaskB2::AliAnalysisTaskB2(const char* name) : AliAnalysisTask(name,"") , fSpecies("Proton") , fPartCode(AliPID::kProton) , fHeavyIons(0) , fSimulation(0) , fMultTriggerFired(0) , fCentTriggerFired(0) , fTriggerFired(0) , fGoodVertex(0) , fPileUpEvent(0) , fV0AND(0) , fNoFastOnly(0) , fNtrkMultTrigger(0) , fMinKNOmult(-10) , fMaxKNOmult(100000) , fMinCentrality(-1) , fMaxCentrality(100) , fNch(0) , fNtrk(0) , fMeanNtrk(1) , fKNOmult(1) , fMinVx(-1) , fMaxVx(1) , fMinVy(-1) , fMaxVy(1) , fMinVz(-10) , fMaxVz(10) , fMinDCAxy(-1) , fMaxDCAxy(1) , fMinDCAz(-2) , fMaxDCAz(2) , fMaxNSigma(3) , fMinEta(-0.8) , fMaxEta(0.8) , fMinY(-0.5) , fMaxY(0.5) , fMCevent(0) , fESDevent(0) , fOutputContainer(0) , fHistoMap(0) , fTrackCuts(0) , fLnID(0) , fMaxNSigmaITS(3) , fMaxNSigmaTPC(3) , fMaxNSigmaTOF(3) , fTrigAna(0) , fESDpid(0) , fIsPidOwner(0) , fTimeZeroType(AliESDpid::kTOF_T0) , fTOFmatch(0) , fMinM2(2.) , fMaxM2(6.) , fMomentumCorrection(0) , fMoCpfx(0) { // // Constructor // DefineInput(0, TChain::Class()); DefineOutput(0, TTree::Class()); DefineOutput(1, TList::Class()); //kFatal, kError, kWarning, kInfo, kDebug, kMaxType AliLog::SetGlobalLogLevel(AliLog::kFatal); fTrigAna = new AliTriggerAnalysis(); } void AliAnalysisTaskB2::ConnectInputData(Option_t *) { // // Connect input data // TTree* tree = dynamic_cast<TTree*> (GetInputData(0)); if(!tree) { this->Error("ConnectInputData", "could not read chain from input slot 0"); return; } // Get the pointer to the existing analysis manager via the static access method. AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { this->Error("ConnectInputData", "could not get analysis manager"); return; } // cast type AliVEventHandler AliESDInputHandler* esdH = dynamic_cast<AliESDInputHandler*>(mgr->GetInputEventHandler()); if (!esdH) { this->Error("ConnectInputData", "could not get ESDInputHandler"); return; } // Get pointer to esd event from input handler fESDevent = (AliESDEvent*)esdH->GetEvent(); // PID object for TOF fESDpid = esdH->GetESDpid(); if(!fESDpid) { //in case of no Tender attached fESDpid = new AliESDpid(); fIsPidOwner = kTRUE; } } void AliAnalysisTaskB2::CreateOutputObjects() { // // Create output objects // if(fHistoMap == 0) AliFatal("no histogram map"); // should be created somewhere else fOutputContainer = new TList(); fOutputContainer->SetOwner(kTRUE); TObjString* key; TIter iter(fHistoMap->GetMap()); while((key = dynamic_cast<TObjString*>(iter.Next()))) fOutputContainer->Add((TH1*)fHistoMap->Get(key)); PostData(1, fOutputContainer); } AliAnalysisTaskB2::~AliAnalysisTaskB2() { // // Default destructor // delete fHistoMap; delete fOutputContainer; delete fTrackCuts; delete fLnID; delete fTrigAna; if(fIsPidOwner) delete fESDpid; delete fMoCpfx; } void AliAnalysisTaskB2::SetParticleSpecies(const TString& species) { // // set the particle species and the AliPID code // fSpecies = species; fPartCode = this->GetPidCode(species); } void AliAnalysisTaskB2::Exec(Option_t* ) { // // Execute analysis for the current event // if(fESDevent == 0) { this->Error("Exec", "AliESDEvent not available"); return; } if(fTrackCuts == 0) AliFatal("track cuts not set"); if(fLnID == 0) AliFatal("PID not set"); if(fSimulation) { AliMCEventHandler* mcH = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); if(mcH == 0) return; fMCevent = mcH->MCEvent(); if(fMCevent == 0) return; } // multiplicity and centrality fNtrk = AliESDtrackCuts::GetReferenceMultiplicity(fESDevent, AliESDtrackCuts::kTrackletsITSTPC, fMaxEta); if(fSimulation) fNch = this->GetChargedMultiplicity(fMaxEta); fKNOmult = fNtrk/fMeanNtrk; ((TH1D*)fHistoMap->Get(fSpecies + "_Event_Ntrk"))->Fill(fNtrk); ((TH1D*)fHistoMap->Get(fSpecies + "_Event_Zmult"))->Fill(fKNOmult); fMultTriggerFired = (fNtrk > 0) && (fKNOmult >= fMinKNOmult) && (fKNOmult < fMaxKNOmult); if(fHeavyIons) { AliCentrality* esdCent = fESDevent->GetCentrality(); Float_t centrality = esdCent->GetCentralityPercentile("V0M"); fCentTriggerFired = (centrality >= fMinCentrality) && (centrality < fMaxCentrality); Float_t v0ScaMult; Float_t v0Mult = AliESDUtils::GetCorrV0(fESDevent,v0ScaMult); ((TH1D*)fHistoMap->Get(fSpecies + "_V0_Mult"))->Fill(v0Mult); ((TH1D*)fHistoMap->Get(fSpecies + "_V0_Scaled_Mult"))->Fill(v0ScaMult); } // trigger AliInputEventHandler* eventH = dynamic_cast<AliInputEventHandler*>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if(eventH == 0) { this->Error("Exec", "could not get AliInputEventHandler"); return; } UInt_t triggerBits = eventH->IsEventSelected(); if(fHeavyIons) { fTriggerFired = ( this->IsMB(triggerBits) && fCentTriggerFired ); } else { fTriggerFired = this->IsMB(triggerBits); if(fNoFastOnly) fTriggerFired = ( fTriggerFired && !this->IsFastOnly(triggerBits) ); if(fV0AND) fTriggerFired = ( fTriggerFired && this->IsV0AND() ); if(fNtrkMultTrigger) fTriggerFired = ( fTriggerFired && fMultTriggerFired ); } // vertex fGoodVertex = kFALSE; const AliESDVertex* vtx = fESDevent->GetPrimaryVertex(); // best primary vertex if(vtx->GetStatus()) { fGoodVertex=kTRUE; ((TH2D*)fHistoMap->Get(fSpecies + "_Vertex_YX"))->Fill(vtx->GetX(), vtx->GetY()); ((TH2D*)fHistoMap->Get(fSpecies + "_Vertex_YZ"))->Fill(vtx->GetZ(), vtx->GetY()); ((TH2D*)fHistoMap->Get(fSpecies + "_Vertex_XZ"))->Fill(vtx->GetZ(), vtx->GetX()); } if(fESDevent->GetPrimaryVertex()->IsFromVertexerZ()) { if(fESDevent->GetPrimaryVertex()->GetDispersion() > 0.02) fGoodVertex=kFALSE; if(fESDevent->GetPrimaryVertex()->GetZRes() > 0.25 ) fGoodVertex=kFALSE; } if( (vtx->GetX() <= fMinVx) || (vtx->GetX() >= fMaxVx) ) fGoodVertex=kFALSE; if( (vtx->GetY() <= fMinVy) || (vtx->GetY() >= fMaxVy) ) fGoodVertex=kFALSE; if( (vtx->GetZ() <= fMinVz) || (vtx->GetZ() >= fMaxVz) ) fGoodVertex=kFALSE; // pile up fPileUpEvent = fESDevent->IsPileupFromSPDInMultBins(); // event stats ((TH1D*)fHistoMap->Get(fSpecies + "_Stats"))->Fill(0); // number of events if(fTriggerFired) { ((TH1D*)fHistoMap->Get(fSpecies + "_Stats"))->Fill(1); // triggering events if(vtx->GetStatus()) { ((TH1D*)fHistoMap->Get(fSpecies + "_Stats"))->Fill(3); // valid vertex within a triggering event if((vtx->GetZ() > fMinVz) && (vtx->GetZ() < fMaxVz)) { ((TH1D*)fHistoMap->Get(fSpecies + "_Stats"))->Fill(4); // Vz if( (vtx->GetX() > fMinVx) && (vtx->GetX() < fMaxVx) && (vtx->GetY() > fMinVy) && (vtx->GetY() < fMaxVy)) { ((TH1D*)fHistoMap->Get(fSpecies + "_Stats"))->Fill(5); // Vx, Vy if(fGoodVertex) { ((TH1D*)fHistoMap->Get(fSpecies + "_Stats"))->Fill(6); // VertexerZ if(!fPileUpEvent) { ((TH1D*)fHistoMap->Get(fSpecies + "_Stats"))->Fill(7); // no pile-up } } } } } } // Particles and tracks for this event if(fSimulation) this->GetParticles(); this->GetTracks(); // Post the data (input/output slots #0 already used by the base class) PostData(1, fOutputContainer); } Int_t AliAnalysisTaskB2::GetParticles() { // // Get particles from current event // Int_t nParticles = 0; AliStack* stack = fMCevent->Stack(); if (!stack) { AliDebug(AliLog::kWarning, "stack not available"); return 0; } for (Int_t i = 0; i < fMCevent->GetNumberOfTracks(); ++i) { TParticle* iParticle = stack->Particle(i); if(!iParticle) continue; Int_t pid = fLnID->GetPID(iParticle); if(pid != fPartCode) continue; // physical primaries if(!stack->IsPhysicalPrimary(i)) continue; TString particle = fSpecies; if(iParticle->GetPDG()->Charge() < 0) particle.Prepend("Anti"); Double_t genP = iParticle->P(); Double_t genPt = iParticle->Pt(); Double_t genY = iParticle->Y(); Double_t genPhi = iParticle->Phi(); Double_t genEta = iParticle->Eta(); // multiplicity and centrality if( fHeavyIons && !fCentTriggerFired) continue; if( fNtrkMultTrigger && !fMultTriggerFired) continue; ((TH1D*)fHistoMap->Get(particle + "_Gen_Prim_P"))->Fill(genP); ((TH1D*)fHistoMap->Get(particle + "_Gen_Prim_Pt"))->Fill(genPt); ((TH1D*)fHistoMap->Get(particle + "_Gen_Prim_Y"))->Fill(genY); ((TH1D*)fHistoMap->Get(particle + "_Gen_Prim_Phi"))->Fill(genPhi); ((TH1D*)fHistoMap->Get(particle + "_Gen_Prim_Eta"))->Fill(genEta); ((TH2D*)fHistoMap->Get(particle + "_Gen_Prim_PtY"))->Fill(genY, genPt); ((TH2D*)fHistoMap->Get(particle + "_Gen_Prim_EtaY"))->Fill(genY, genEta); // is within phase space? if(TMath::Abs(genY) >= fMaxY) continue; ((TH1D*)fHistoMap->Get(particle + "_Gen_PhS_Prim_P"))->Fill(genP); ((TH1D*)fHistoMap->Get(particle + "_Gen_PhS_Prim_Pt"))->Fill(genPt); // is from a triggering event? (same as rec.) if(!fTriggerFired) { ((TH1D*)fHistoMap->Get(particle + "_Gen_NoTrig_Prim_Pt"))->Fill(genPt); continue; } ((TH1D*)fHistoMap->Get(particle + "_Gen_Trig_Prim_Pt"))->Fill(genPt); // is from a triggering event with good vertex? if(!fESDevent->GetPrimaryVertex()->GetStatus()) { ((TH1D*)fHistoMap->Get(particle + "_Gen_NoVtx_Prim_Pt"))->Fill(genPt); } if(!fGoodVertex) continue; if(fPileUpEvent) continue; ((TH1D*)fHistoMap->Get(particle + "_Gen_Nch"))->Fill(fNch); ((TH1D*)fHistoMap->Get(particle + "_Gen_Vtx_Prim_Pt"))->Fill(genPt); // is within the geometrical acceptance? if(TMath::Abs(genEta) >= fMaxEta) continue; ((TH2D*)fHistoMap->Get(particle + "_Gen_Acc_Prim_PtY"))->Fill(genY,genPt); ((TH1D*)fHistoMap->Get(particle + "_Gen_Acc_Prim_P"))->Fill(genP); ((TH1D*)fHistoMap->Get(particle + "_Gen_Acc_Prim_Pt"))->Fill(genPt); ((TH1D*)fHistoMap->Get(particle + "_Gen_Acc_Prim_Phi"))->Fill(genPhi); ((TH1D*)fHistoMap->Get(particle + "_Gen_Acc_Prim_Y"))->Fill(genY); } return nParticles; } Int_t AliAnalysisTaskB2::GetTracks() { // // Get tracks from current event // using namespace std; Int_t nTracks = 0; // trigger, vertex and pile-up if(!fTriggerFired) return 0; if(!fGoodVertex) return 0; if(fPileUpEvent) return 0; // this is a 'good' event ((TH1D*)fHistoMap->Get(fSpecies + "_Stats"))->Fill(2); // analyzed events ((TH1D*)fHistoMap->Get(fSpecies + "_Ana_Event_Ntrk"))->Fill(fNtrk); ((TH1D*)fHistoMap->Get(fSpecies + "_Ana_Event_Zmult"))->Fill(fKNOmult); if(fSimulation) { ((TH2D*)fHistoMap->Get(fSpecies + "_Ana_Event_Nch_Ntrk"))->Fill(fNtrk, fNch); } const AliESDVertex* vtx = fESDevent->GetPrimaryVertex(); ((TH2D*)fHistoMap->Get(fSpecies + "_Ana_Vertex_YX"))->Fill(vtx->GetX(), vtx->GetY()); ((TH2D*)fHistoMap->Get(fSpecies + "_Ana_Vertex_YZ"))->Fill(vtx->GetZ(), vtx->GetY()); ((TH2D*)fHistoMap->Get(fSpecies + "_Ana_Vertex_XZ"))->Fill(vtx->GetZ(), vtx->GetX()); if(fHeavyIons) { Float_t v0ScaMult; Float_t v0Mult = AliESDUtils::GetCorrV0(fESDevent,v0ScaMult); ((TH1D*)fHistoMap->Get(fSpecies + "_Ana_V0_Mult"))->Fill(v0Mult); ((TH1D*)fHistoMap->Get(fSpecies + "_Ana_V0_Scaled_Mult"))->Fill(v0ScaMult); } // track loop for(Int_t i = 0; i < fESDevent->GetNumberOfTracks(); ++i) { AliESDtrack* iTrack = fESDevent->GetTrack(i); if(!iTrack) continue; TString particle = fSpecies; if(iTrack->GetSign() < 0) particle.Prepend("Anti"); // impact parameters Float_t dcaxy, dcaz; iTrack->GetImpactParameters(dcaxy, dcaz); if(iTrack->GetSign() < 0) // in case of asymmetry { dcaxy = -dcaxy; dcaz = -dcaz; } Double_t nSigmaVtx = fTrackCuts->GetSigmaToVertex(iTrack); // momentum at DCA Double_t p = iTrack->GetP(); Double_t pt = iTrack->Pt(); Double_t pz = iTrack->Pz(); // track cuts Double_t eta = iTrack->Eta(); Double_t phi = this->GetPhi(iTrack); ((TH2D*)fHistoMap->Get(particle + "_Before_Phi_Eta"))->Fill(eta,phi); if(!fTrackCuts->AcceptTrack(iTrack)) continue; // with next track if(fTOFmatch && !this->AcceptTOFtrack(iTrack)) continue; // with next track // end track cuts ++nTracks; ((TH2D*)fHistoMap->Get(particle + "_After_Phi_Eta"))->Fill(eta, phi); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_DCAxy"))->Fill(dcaxy); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_DCAz"))->Fill(dcaz); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_NSigma"))->Fill(nSigmaVtx); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_ITSchi2PerCls"))->Fill(this->GetITSchi2PerCluster(iTrack)); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_TPCncls"))->Fill(iTrack->GetTPCNcls()); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_TPCxRowsOverF"))->Fill(static_cast<Double_t>(iTrack->GetTPCCrossedRows())/static_cast<Double_t>(iTrack->GetTPCNclsF())); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_TPCxRows"))->Fill(iTrack->GetTPCCrossedRows()); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_TPCchi2PerCls"))->Fill(iTrack->GetTPCchi2()/iTrack->GetTPCNcls()); ((TH1D*)fHistoMap->Get(particle + "_TrackCuts_TPCchi2Global"))->Fill(iTrack->GetChi2TPCConstrainedVsGlobal(fESDevent->GetPrimaryVertex())); // detector signals Double_t pITS = this->GetITSmomentum(iTrack); Double_t pTPC = iTrack->GetTPCmomentum(); Double_t pTOF = this->GetTOFmomentum(iTrack); Double_t dEdxITS = iTrack->GetITSsignal(); Double_t dEdxTPC = iTrack->GetTPCsignal(); Int_t nPointsITS = this->GetITSnPointsPID(iTrack); Int_t nPointsTPC = iTrack->GetTPCsignalN(); Double_t beta = 0; Double_t mass = 0; Double_t m2 = 0; ((TH2D*)fHistoMap->Get(particle + "_ITS_dEdx_P"))->Fill(pITS, dEdxITS); ((TH2D*)fHistoMap->Get(particle + "_TPC_dEdx_P"))->Fill(pTPC, dEdxTPC); if(fTOFmatch) { beta = this->GetBeta(iTrack); m2 = this->GetMassSquared(p, beta); mass = TMath::Sqrt(TMath::Abs(m2)); ((TH2D*)fHistoMap->Get(particle + "_TOF_Beta_P"))->Fill(pTOF, beta); ((TH2D*)fHistoMap->Get(particle + "_TOF_Mass_P"))->Fill(pTOF, mass); } // get the pid Int_t pid = fLnID->GetPID( fPartCode, pITS, dEdxITS, nPointsITS, pTPC, dEdxTPC, nPointsTPC, pTOF, beta, fMaxNSigmaITS, fMaxNSigmaTPC, fMaxNSigmaTOF); Int_t offset = AliPID::kDeuteron - 5; // for bayes iteration if(pid != -1) { Int_t iBin = (pid > AliPID::kProton) ? pid - offset : pid; ((TH1D*)fHistoMap->Get(fSpecies + "_Stats_PID"))->Fill(iBin); } // fix momentum if(fPartCode > AliPID::kTriton) { p *= 2.; pt *= 2.; pz *= 2.; } if(fMomentumCorrection) { pt += this->GetMomentumCorrection(pt); p = TMath::Sqrt(pt*pt + pz*pz); if(fTOFmatch) { m2 = this->GetMassSquared(p, beta); mass = TMath::Sqrt(TMath::Abs(m2)); } } // for pid and efficiency Double_t simPt = 0; Double_t simPhi = 0; Double_t simY = 0; Int_t simpid = -1; TParticle* iParticle = 0; if(fSimulation) { iParticle = this->GetParticle(iTrack); if(iParticle == 0) continue; simPt = iParticle->Pt(); simPhi = iParticle->Phi(); simY = iParticle->Y(); simpid = fLnID->GetPID(iParticle); if(simpid == fPartCode) { TString simparticle = fSpecies; if(this->GetSign(iParticle)<0) simparticle.Prepend("Anti"); ((TH2D*)fHistoMap->Get(simparticle + "_Sim_PtY"))->Fill(simY, simPt); if(TMath::Abs(simY) < fMaxY) { ((TH2D*)fHistoMap->Get(simparticle + "_Response_Matrix"))->Fill(pt, simPt); if(this->IsPhysicalPrimary(iParticle)) { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Ntrk"))->Fill(fNtrk); } // for pid if(!this->IsFakeTrack(iTrack)) { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Pt"))->Fill(simPt); if(this->IsPhysicalPrimary(iParticle)) // the efficiency is calculated on the primaries { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Prim_Pt"))->Fill(simPt); ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Prim_Y"))->Fill(simY); ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Prim_Phi"))->Fill(simPhi); ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Prim_Rec_Pt"))->Fill(pt); ((TH2D*)fHistoMap->Get(simparticle + "_Sim_Prim_DCAxy_Pt"))->Fill(simPt,dcaxy); ((TH2D*)fHistoMap->Get(simparticle + "_Prim_Response_Matrix"))->Fill(pt, simPt); ((TH2D*)fHistoMap->Get(simparticle + "_Prim_DiffPt_RecPt"))->Fill(pt,simPt-pt); if(fTOFmatch) { ((TH2D*)fHistoMap->Get(simparticle + "_Sim_Prim_M2_P"))->Fill(pTOF, m2); ((TH2D*)fHistoMap->Get(simparticle + "_Sim_Prim_M2_Pt"))->Fill(pt, m2); } } else if(this->IsFromWeakDecay(iParticle)) { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Fdwn_Pt"))->Fill(simPt); ((TH2D*)fHistoMap->Get(simparticle + "_Sim_Fdwn_DCAxy_Pt"))->Fill(simPt,dcaxy); } else { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Mat_Pt"))->Fill(simPt); ((TH2D*)fHistoMap->Get(simparticle + "_Sim_Mat_DCAxy_Pt"))->Fill(simPt,dcaxy); } } else // fake tracks { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Fake_Pt"))->Fill(simPt); if(this->IsPhysicalPrimary(iParticle)) { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Fake_Prim_Pt"))->Fill(simPt); } else if(this->IsFromWeakDecay(iParticle)) { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Fake_Fdwn_Pt"))->Fill(simPt); } else { ((TH1D*)fHistoMap->Get(simparticle + "_Sim_Fake_Mat_Pt"))->Fill(simPt); } } } } // pid table for prior probabilities (only Bayes) Int_t sim = (simpid > AliPID::kProton) ? simpid - offset : simpid; Int_t rec = (pid > AliPID::kProton) ? pid - offset : pid; if((sim > -1) && (rec > -1)) // pid performance { ((TH2D*)fHistoMap->Get(fSpecies + "_Stats_PID_Table"))->Fill(sim, rec); ((TH2D*)fHistoMap->Get(fSpecies + "_Stats_PID_Table"))->Fill(9, rec); } if(sim > -1) { ((TH2D*)fHistoMap->Get(fSpecies + "_Stats_PID_Table"))->Fill(sim, 9); } } // candidate tracks if(pid != fPartCode) continue; Bool_t goodPid = 0; if(fSimulation) { goodPid = ( simpid == pid ); } ((TH2D*)fHistoMap->Get(particle + "_PID_Ntrk_pTPC"))->Fill(pTPC,fNtrk); ((TH2D*)fHistoMap->Get(particle + "_PID_Zmult_pTPC"))->Fill(pTPC,fKNOmult); // pid performance ((TH2D*)fHistoMap->Get(particle + "_PID_ITSdEdx_P"))->Fill(pITS, dEdxITS); ((TH2D*)fHistoMap->Get(particle + "_PID_TPCdEdx_P"))->Fill(pTPC, dEdxTPC); if(fTOFmatch) { ((TH2D*)fHistoMap->Get(particle + "_PID_Beta_P"))->Fill(pTOF, beta); ((TH2D*)fHistoMap->Get(particle + "_PID_Mass_P"))->Fill(pTOF, mass); if(fSimulation && goodPid) { ((TH1D*)fHistoMap->Get(particle + "_Sim_PID_Mass"))->Fill(mass); } } Double_t y = this->GetRapidity(p, pz, AliPID::ParticleMass(fPartCode)); ((TH1D*)fHistoMap->Get(particle + "_PID_Y"))->Fill(y); ((TH2D*)fHistoMap->Get(particle + "_PID_Pt_Y"))->Fill(y, pt); // results in |y| < fMaxY if(TMath::Abs(y) >= fMaxY) continue; ((TH1D*)fHistoMap->Get(particle + "_PID_Pt"))->Fill(pt); ((TH1D*)fHistoMap->Get(particle + "_PID_Phi"))->Fill(phi); if(iTrack->IsOn(AliESDtrack::kTRDin)) { ((TH1D*)fHistoMap->Get(particle + "_PID_TRDin_Pt"))->Fill(pt); if(iTrack->IsOn(AliESDtrack::kTRDout)) ((TH1D*)fHistoMap->Get(particle + "_PID_TRDin_TRDout_Pt"))->Fill(pt); if(iTrack->IsOn(AliESDtrack::kTOFout)) ((TH1D*)fHistoMap->Get(particle + "_PID_TRDin_TOFout_Pt"))->Fill(pt); } if(iTrack->IsOn(AliESDtrack::kTOFin)) { ((TH1D*)fHistoMap->Get(particle + "_PID_TOFin_Pt"))->Fill(pt); if(iTrack->IsOn(AliESDtrack::kTOFout)) ((TH1D*)fHistoMap->Get(particle + "_PID_TOFin_TOFout_Pt"))->Fill(pt); } if(fTOFmatch) { Double_t dm2 = this->GetM2Difference(beta, pTOF, AliPID::ParticleMass(fPartCode)); Double_t t = this->GetTimeOfFlight(iTrack)*1.e-3; // ns Double_t dt = t - this->GetExpectedTime(iTrack, AliPID::ParticleMass(fPartCode))*1.e-3; ((TH2D*)fHistoMap->Get(particle + "_PID_M2_Pt"))->Fill(pt, m2); ((TH2D*)fHistoMap->Get(particle + "_PID_DM2_Pt"))->Fill(pt, dm2); ((TH2D*)fHistoMap->Get(particle + "_PID_Time_Pt"))->Fill(pt, t); ((TH2D*)fHistoMap->Get(particle + "_PID_DTime_Pt"))->Fill(pt, dt); ((TH1D*)fHistoMap->Get(particle + "_PID_TOFmatch_Pt"))->Fill(pt); } // secondaries Bool_t m2match = kTRUE; if( fTOFmatch && (fLnID->GetPidProcedure() > AliLnID::kMaxLikelihood)) { if ((m2 < fMinM2) || (m2 >= fMaxM2)) m2match = kFALSE; } if(m2match) { ((TH2D*)fHistoMap->Get(particle + "_PID_DCAxy_Pt"))->Fill(pt, dcaxy); ((TH2D*)fHistoMap->Get(particle + "_PID_DCAz_Pt"))->Fill(pt, dcaz); ((TH2D*)fHistoMap->Get(particle + "_PID_NSigma_Pt"))->Fill(pt, nSigmaVtx); } if(fSimulation && goodPid) { // for unfolding and pid contamination if(!this->IsFakeTrack(iTrack)) { ((TH1D*)fHistoMap->Get(particle + "_Sim_PID_Pt"))->Fill(simPt); if(fTOFmatch) { ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_M2_Pt"))->Fill(pt, m2); } if(this->IsPhysicalPrimary(iParticle)) { ((TH1D*)fHistoMap->Get(particle + "_Sim_PID_Prim_Pt"))->Fill(simPt); } if(m2match) { if(this->IsPhysicalPrimary(iParticle)) { ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Prim_DCAxy_Pt"))->Fill(pt, dcaxy); ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Prim_DCAz_Pt"))->Fill(pt, dcaz); ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Prim_NSigma_Pt"))->Fill(pt, nSigmaVtx); } else if(this->IsFromWeakDecay(iParticle)) { ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Fdwn_DCAxy_Pt"))->Fill(pt, dcaxy); ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Fdwn_DCAz_Pt"))->Fill(pt, dcaz); ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Fdwn_NSigma_Pt"))->Fill(pt, nSigmaVtx); } else // from materials { ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Mat_DCAxy_Pt"))->Fill(pt, dcaxy); ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Mat_DCAz_Pt"))->Fill(pt, dcaz); ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Mat_NSigma_Pt"))->Fill(pt, nSigmaVtx); } } } else // fake tracks { ((TH1D*)fHistoMap->Get(particle + "_Sim_PID_Fake_Pt"))->Fill(simPt); if(m2match) { if(this->IsPhysicalPrimary(iParticle)) { ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Fake_Prim_DCAxy_Pt"))->Fill(pt, dcaxy); } else if(this->IsFromWeakDecay(iParticle)) { ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Fake_Fdwn_DCAxy_Pt"))->Fill(pt, dcaxy); } else // from materials { ((TH2D*)fHistoMap->Get(particle + "_Sim_PID_Fake_Mat_DCAxy_Pt"))->Fill(pt, dcaxy); } } } } } return nTracks; } void AliAnalysisTaskB2::Terminate(Option_t* ) { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. } Bool_t AliAnalysisTaskB2::IsV0AND() const { // // signals in both V0A and V0C // return ( fTrigAna->IsOfflineTriggerFired(fESDevent, AliTriggerAnalysis::kV0A) && fTrigAna->IsOfflineTriggerFired(fESDevent, AliTriggerAnalysis::kV0C) ); } Bool_t AliAnalysisTaskB2::IsFastOnly(UInt_t triggerBits) const { // // kFastOnly trigger // return ( (triggerBits&AliVEvent::kFastOnly) == AliVEvent::kFastOnly ); } Bool_t AliAnalysisTaskB2::IsMB(UInt_t triggerBits) const { // // MB event // return ( (triggerBits&AliVEvent::kMB) == AliVEvent::kMB ); } Bool_t AliAnalysisTaskB2::AcceptTOFtrack(const AliESDtrack* trk) const { // // Additional checks for TOF match signal // if( !fTOFmatch ) return kFALSE; if( trk->GetIntegratedLength() < 350) return kFALSE; if( trk->GetTOFsignal() < 1e-6) return kFALSE; return kTRUE; } TParticle* AliAnalysisTaskB2::GetParticle(const AliESDtrack* trk) const { // // Particle that left the track // AliStack* stack = fMCevent->Stack(); Int_t label = TMath::Abs(trk->GetLabel()); // if negative then it shares points from other tracks if( label >= fMCevent->GetNumberOfTracks() ) return 0; return stack->Particle(label); } Bool_t AliAnalysisTaskB2::IsFakeTrack(const AliESDtrack* trk) const { // // Check if the track shares some clusters with different particles // (definition changed to label=0? ) // return ( trk->GetLabel() < 0 ); } Bool_t AliAnalysisTaskB2::IsPhysicalPrimary(const TParticle* prt) const { // // Check if the particle is physical primary // AliStack* stack = fMCevent->Stack(); Int_t index = stack->Particles()->IndexOf(prt); return stack->IsPhysicalPrimary(index); } Bool_t AliAnalysisTaskB2::IsFromMaterial(const TParticle* prt) const { // // Check if the particle is originated at the materials // AliStack* stack = fMCevent->Stack(); Int_t index = stack->Particles()->IndexOf(prt); return stack->IsSecondaryFromMaterial(index); } Bool_t AliAnalysisTaskB2::IsFromWeakDecay(const TParticle* prt) const { // // Check if the particle comes from a weak decay // AliStack* stack = fMCevent->Stack(); Int_t index = stack->Particles()->IndexOf(prt); return stack->IsSecondaryFromWeakDecay(index); } Double_t AliAnalysisTaskB2::GetSign(TParticle* prt) const { // // Sign of the particle // TParticlePDG* pdg = prt->GetPDG(); if(pdg != 0) return pdg->Charge(); return 0; } Double_t AliAnalysisTaskB2::GetPhi(const AliESDtrack* trk) const { // // Azimuthal angle [0,2pi) using the pt at the DCA point // Double_t px = trk->Px(); Double_t py = trk->Py(); return TMath::Pi()+TMath::ATan2(-py, -px); } Double_t AliAnalysisTaskB2::GetTheta(const AliESDtrack* trk) const { // // Polar angle using the pt at the DCA point // Double_t p = trk->GetP(); Double_t pz = trk->Pz(); return (pz == 0) ? TMath::PiOver2() : TMath::ACos(pz/p); } Double_t AliAnalysisTaskB2::GetITSmomentum(const AliESDtrack* trk) const { // // Momentum for ITS pid // Double_t pDCA = trk->GetP(); Double_t pTPC = trk->GetTPCmomentum(); return (pDCA+pTPC)/2.; } Double_t AliAnalysisTaskB2::GetTOFmomentum(const AliESDtrack* trk) const { // // Momentum for TOF pid // Double_t pIn = trk->GetTPCmomentum(); const AliExternalTrackParam* param = trk->GetOuterParam(); Double_t pOut = param ? param->GetP() : trk->GetP(); return (pIn+pOut)/2.; } Double_t AliAnalysisTaskB2::GetBeta(const AliESDtrack* trk) const { // // Velocity // Double_t t = this->GetTimeOfFlight(trk); // ps Double_t l = trk->GetIntegratedLength(); // cm if(t <= 0) return 1.e6; // 1M times the speed of light ;) return (l/t)/2.99792458e-2; } Double_t AliAnalysisTaskB2::GetExpectedTime(const AliESDtrack* trk, Double_t m) const { // // Expected time (ps) for the given mass hypothesis // Double_t p = (fPartCode>AliPID::kTriton) ? 2.*this->GetTOFmomentum(trk) : this->GetTOFmomentum(trk); Double_t beta = p/TMath::Sqrt(p*p + m*m); Double_t l = trk->GetIntegratedLength(); return l/beta/2.99792458e-2; } Double_t AliAnalysisTaskB2::GetMassSquared(Double_t p, Double_t beta) const { // // Mass squared // return p*p*(1./(beta*beta) - 1.); } Double_t AliAnalysisTaskB2::GetM2Difference(Double_t beta, Double_t p, Double_t m) const { // // Mass squared difference // Double_t expBeta2 = p*p/(p*p+m*m); return p*p*(1./(beta*beta)-1./expBeta2); } Int_t AliAnalysisTaskB2::GetChargedMultiplicity(Double_t etaMax) const { // // Charged particle multiplicity using ALICE physical primary definition // AliStack* stack = fMCevent->Stack(); Int_t nch = 0; //for (Int_t i=0; i < stack->GetNprimary(); ++i) for (Int_t i=0; i < stack->GetNtrack(); ++i) { if(!stack->IsPhysicalPrimary(i)) continue; TParticle* iParticle = stack->Particle(i); if(TMath::Abs(iParticle->Eta()) >= etaMax) continue; //if (iParticle->Pt() < -1) continue; TParticlePDG* iPDG = iParticle->GetPDG(); // There are some particles with no PDG if (iPDG && iPDG->Charge() == 0) continue; ++nch; } return nch; } Double_t AliAnalysisTaskB2::GetTimeOfFlight(const AliESDtrack* trk) const { // // Time of flight associated to the track. // Adapted from ANALYSIS/AliAnalysisTaskESDfilter.cxx // if(!fESDevent->GetTOFHeader()) { //protection in case the pass2 LHC10b,c,d have been processed without tender. Float_t t0spread[10]; Float_t intrinsicTOFres=100; //ps ok for LHC10b,c,d pass2!! for (Int_t j=0; j<10; j++) t0spread[j] = (TMath::Sqrt(fESDevent->GetSigma2DiamondZ()))/0.03; //0.03 to convert from cm to ps fESDpid->GetTOFResponse().SetT0resolution(t0spread); fESDpid->GetTOFResponse().SetTimeResolution(intrinsicTOFres); fESDpid->SetTOFResponse(fESDevent, (AliESDpid::EStartTimeType_t)fTimeZeroType); } if(fESDevent->GetTOFHeader() && fIsPidOwner) fESDpid->SetTOFResponse(fESDevent, (AliESDpid::EStartTimeType_t)fTimeZeroType); //in case of AOD production strating form LHC10e without Tender. Double_t timeZero = fESDpid->GetTOFResponse().GetStartTime(trk->P()); return trk->GetTOFsignal()-timeZero; } Int_t AliAnalysisTaskB2::GetITSnClusters(const AliESDtrack* trk) const { // // ITS number of clusters // UChar_t map = trk->GetITSClusterMap(); Int_t npoints=0; for(Int_t j=0; j<6; j++) { if(map&(1<<j)) ++npoints; } return npoints; } Double_t AliAnalysisTaskB2::GetITSchi2PerCluster(const AliESDtrack* trk) const { // // ITS chi2 per number of clusters // Double_t chi2 = trk->GetITSchi2(); Int_t ncls = this->GetITSnClusters(trk); Double_t chi2ncls = (ncls==0) ? 1.e10 : chi2/ncls; return chi2ncls; } Int_t AliAnalysisTaskB2::GetITSnPointsPID(const AliESDtrack* trk) const { // // ITS number of points for PID // UChar_t map = trk->GetITSClusterMap(); Int_t npoints = 0; for(Int_t j=2; j<6; j++) { if(map&(1<<j)) ++npoints; } return npoints; } Int_t AliAnalysisTaskB2::GetPidCode(const TString& species) const { // // Return AliPID code of the given species // TString name = species; name.ToLower(); if(name == "electron") return AliPID::kElectron; if(name == "muon") return AliPID::kMuon; if(name == "pion") return AliPID::kPion; if(name == "kaon") return AliPID::kKaon; if(name == "proton") return AliPID::kProton; if(name == "deuteron") return AliPID::kDeuteron; if(name == "triton") return AliPID::kTriton; if(name == "he3") return AliPID::kHe3; if(name == "alpha") return AliPID::kAlpha; return -1; } Double_t AliAnalysisTaskB2::GetMomentumCorrection(Double_t ptrec) const { // // momentum correction for low pt // if(fMoCpfx == 0) return 0; return fMoCpfx->Interpolate(ptrec); } Double_t AliAnalysisTaskB2::GetRapidity(Double_t p, Double_t pz, Double_t m) const { // // Rapidity // Double_t e = TMath::Sqrt(p*p + m*m); if(e <= pz) return 1.e+16; return 0.5*TMath::Log( (e+pz)/(e-pz) ); }
26.689898
191
0.657923
[ "object" ]
7497c6d31feeed1b484031889feb95f5fa4f3a38
1,980
cpp
C++
main.cpp
MariiaGerasimenko/CPP-Project
8ea99553ffbbb783d627f4695e665cfb4b69222b
[ "MIT" ]
null
null
null
main.cpp
MariiaGerasimenko/CPP-Project
8ea99553ffbbb783d627f4695e665cfb4b69222b
[ "MIT" ]
null
null
null
main.cpp
MariiaGerasimenko/CPP-Project
8ea99553ffbbb783d627f4695e665cfb4b69222b
[ "MIT" ]
null
null
null
#include "src/Bank.h" #include <iostream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; /* testing unprofitability of bank working scheme */ int test1() { vector<struct bank_info> a; Bank mybank; a = mybank.get_report_per_n_years(5); int res; if((a[4].money - a[0].money) <= 0) res = 1; else res = 0; return res; } int test2() { vector<struct bank_info> a; Bank mybank; a = mybank.get_report_per_n_years(10); int res; if((a[9].money - a[0].money) <= 0) res = 1; else res = 0; return res; } int test3() { vector<struct bank_info> a; Bank mybank; a = mybank.get_report_per_n_years(15); int res; if((a[14].money - a[0].money) <= 0) res = 1; else res = 0; return res; } int test4() { vector<struct bank_info> a; Bank mybank; a = mybank.get_report_per_n_years(20); int res; if((a[19].money - a[0].money) <= 0) res = 1; else res = 0; return res; } int main() { cout << "testing..." << endl; if(test1()) cout << "test 1 passed" << endl; // because of random test are working a long while if(test2()) cout << "test 2 passed" << endl; if(test3()) cout << "test 3 passed" << endl; if(test4()) cout << "test 4 passed" << endl; int n; cout << "Input years of bank working (optimal values due to speed of program are in range 10-20): "; cin >> n; cout << "Wait please, imitating banks work..." << endl; vector<struct bank_info> a; Bank mybank; a = mybank.get_report_per_n_years(n); cout << "Bank have been working for " << n << " years. Input 2 numbers from 0 to " << n; cout << " included " << endl << "to get financial report of bank's work on this period" << endl; int k, m; cin >> k >> m; get_delta(a, k, m); return 0; }
17.522124
104
0.550505
[ "vector" ]
749ae1badc9951ee18ddd06b2b7454f58707d8b1
4,810
cxx
C++
hpm_counters.cxx
davidbiancolin/riscv-hpmcounters
540a4fd4d85f90db2b24ed23aa90c2bd3598705b
[ "Apache-2.0" ]
9
2017-05-09T22:09:56.000Z
2021-05-26T06:21:12.000Z
hpm_counters.cxx
davidbiancolin/riscv-hpmcounters
540a4fd4d85f90db2b24ed23aa90c2bd3598705b
[ "Apache-2.0" ]
null
null
null
hpm_counters.cxx
davidbiancolin/riscv-hpmcounters
540a4fd4d85f90db2b24ed23aa90c2bd3598705b
[ "Apache-2.0" ]
11
2018-11-06T20:34:03.000Z
2021-12-18T04:05:40.000Z
// Copyright 2017 University of California, Berkeley. See LICENSE. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <vector> #include <array> // In setStats, we might trap reading uarch-specific counters. // The trap handler will skip over the instruction and write 0, // but only if a0 is the destination register. #define read_csr_safe(reg) ({ register long __tmp asm("a0"); \ asm volatile ("csrr %0, " #reg : "=r"(__tmp)); \ __tmp; }) // 100e6 cycles #define SLEEP_TIME_US (100000) // How many counters do we support? (change for your micro-architecture). #define NUM_COUNTERS (8) //#define NUM_COUNTERS (32) maximum amount of HPMs is 32 typedef std::array<long, NUM_COUNTERS> snapshot_t; static char const* counter_names[NUM_COUNTERS]; static snapshot_t init_counters; static std::vector <snapshot_t> counters; // use sprintf to attempt to lesson load on debug interface #define CHAR_PER_LINE (40) #define MAX_BUFFER_SZ (CHAR_PER_LINE * NUM_COUNTERS) enum StatState { INIT, // initialize the counters WAKEUP, // print the running diff from last snapshot FINISH, // print the total CPI MAX }; int bytes_added(int result) { if (result > 0) { return result; } else { printf ("Error in sprintf. Res: %d\n", result); return 0; } } #if 1 static int handle_stats(int enable) { long tsc_start = read_csr_safe(cycle); long irt_start = read_csr_safe(instret); sigset_t sig_set; sigemptyset(&sig_set); sigaddset(&sig_set, SIGTERM); if (sigprocmask(SIG_BLOCK, &sig_set, NULL) < 0) { perror ("sigprocmask failed"); return 1; } static size_t step = 0; // increment every time handle_stats is called int i = 0; snapshot_t snapshot; #define READ_CTR(name) do { \ if (i < NUM_COUNTERS) { \ long csr = read_csr_safe(name); \ if (enable == INIT) { init_counters[i] = csr; snapshot[i] = 0; counter_names[i] = #name; } \ if (enable == WAKEUP) { snapshot[i] = csr - init_counters[i]; } \ if (enable == FINISH) { snapshot[i] = csr - init_counters[i]; } \ i++; \ } \ } while (0) // Since most processors will not support all 32 HPMs, comment out which hpm counters you don't want to track. READ_CTR(cycle); READ_CTR(instret); READ_CTR(time); READ_CTR(hpmcounter3); READ_CTR(hpmcounter4); READ_CTR(hpmcounter5); READ_CTR(hpmcounter6); READ_CTR(hpmcounter7); READ_CTR(hpmcounter8); READ_CTR(hpmcounter9); READ_CTR(hpmcounter10); READ_CTR(hpmcounter11); READ_CTR(hpmcounter12); READ_CTR(hpmcounter13); READ_CTR(hpmcounter14); READ_CTR(hpmcounter15); READ_CTR(hpmcounter16); READ_CTR(hpmcounter17); READ_CTR(hpmcounter18); READ_CTR(hpmcounter19); READ_CTR(hpmcounter20); READ_CTR(hpmcounter21); READ_CTR(hpmcounter22); READ_CTR(hpmcounter23); READ_CTR(hpmcounter24); READ_CTR(hpmcounter25); READ_CTR(hpmcounter26); READ_CTR(hpmcounter27); READ_CTR(hpmcounter28); READ_CTR(hpmcounter29); READ_CTR(hpmcounter30); READ_CTR(hpmcounter31); counters.push_back(snapshot); //printf("Snapshot Time in cycles : %ld\n", read_csr_safe(cycle) - tsc_start); //printf("Snapshot Time in instret: %ld\n", read_csr_safe(instret) - irt_start); //if (step % 10 == 0) printf("heartbeat: %d\n", step); step++; #undef READ_CTR if (enable == FINISH || step % 30 == 0) { for (auto & element : counters) { for (int i = 0; i < NUM_COUNTERS; i++) { long c = element[i]; if (c) { printf("## %s = %ld\n", counter_names[i], c); } } } if (enable != FINISH) counters.clear(); //printf("Print Time in cycles : %ld\n", read_csr_safe(cycle) - tsc_start); //printf("Print Time in instret: %ld\n", read_csr_safe(instret) - irt_start); } if (sigprocmask(SIG_UNBLOCK, &sig_set, NULL) < 0) { perror ("sigprocmask unblock failed"); return 1; } return 0; } #else static int handle_stats(int enable) { return 0; } #endif void sig_handler(int signum) { handle_stats(FINISH); //printf("HPM Counters exiting, received handler: %d\n", signum); exit(0); } int main(int argc, char** argv) { signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); if (argc > 1) { // only print the final cycle and instret counts. //printf ("Pausing, argc=%d\n", argc); handle_stats(INIT); pause(); } else { //printf("Starting: counter array size: %d\n", sizeof(counters)); handle_stats(INIT); while (1) { usleep(SLEEP_TIME_US); handle_stats(WAKEUP); } //printf("Exiting\n"); } return 0; }
26.428571
113
0.638877
[ "vector" ]
749dcff0522a7816e6d971a26dfc8ba2d636770d
2,646
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/MediaSyncEvent.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/MediaSyncEvent.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/MediaSyncEvent.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "elastos/droid/ext/frameworkext.h" #include "elastos/droid/media/MediaSyncEvent.h" #include "elastos/droid/media/CMediaSyncEvent.h" #include <elastos/utility/logging/Slogger.h> using Elastos::Utility::Logging::Slogger; namespace Elastos { namespace Droid { namespace Media { MediaSyncEvent::MediaSyncEvent() : mType(0) , mAudioSession(0) {} MediaSyncEvent::~MediaSyncEvent() {} CAR_INTERFACE_IMPL(MediaSyncEvent, Object, IMediaSyncEvent) ECode MediaSyncEvent::constructor( /* [in] */ Int32 eventType) { mType = eventType; return NOERROR; } ECode MediaSyncEvent::CreateEvent( /* [in] */ Int32 eventType, /* [out] */ IMediaSyncEvent** result) { VALIDATE_NOT_NULL(result); *result = NULL; if (!IsValidType(eventType)) { Slogger::E("MediaSyncEvent", "%d is not a valid MediaSyncEvent type.", eventType); return E_ILLEGAL_ARGUMENT_EXCEPTION; } return CMediaSyncEvent::New(eventType, result); } ECode MediaSyncEvent::SetAudioSessionId( /* [in] */ Int32 audioSessionId) { if (audioSessionId > 0) { mAudioSession = audioSessionId; } else { Slogger::E("MediaSyncEvent", "%d is not a valid session ID.", audioSessionId); return E_ILLEGAL_ARGUMENT_EXCEPTION; } return NOERROR; } ECode MediaSyncEvent::GetType( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mType; return NOERROR; } ECode MediaSyncEvent::GetAudioSessionId( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mAudioSession; return NOERROR; } Boolean MediaSyncEvent::IsValidType( /* [in] */ Int32 type) { switch (type) { case SYNC_EVENT_NONE: case SYNC_EVENT_PRESENTATION_COMPLETE: return TRUE; default: return FALSE; } } } // namespace Media } // namepsace Droid } // namespace Elastos
25.68932
90
0.652305
[ "object" ]
749fa358b1877409b8de709842eab7ec2ebbfc30
960
cpp
C++
WinProj/CAnimation.cpp
godekd3133/MyAquarium
1162522b11f6ff222b138dff9e9dd0fe9e36353f
[ "Apache-2.0" ]
null
null
null
WinProj/CAnimation.cpp
godekd3133/MyAquarium
1162522b11f6ff222b138dff9e9dd0fe9e36353f
[ "Apache-2.0" ]
null
null
null
WinProj/CAnimation.cpp
godekd3133/MyAquarium
1162522b11f6ff222b138dff9e9dd0fe9e36353f
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "CAnimation.h" CAnimation::CAnimation(CTexture * _pTexture, FLOAT _fDelay, INT _iMaxframe, INT _iLine, INT _iFrameline) : m_pTexture(_pTexture),m_fDelay(_fDelay),m_iMaxFrame(_iMaxframe) { m_iCurrentTime = timeGetTime(); m_iOldTime = timeGetTime(); m_iFrameWidth = _pTexture->GetWidth() / _iMaxframe; m_iFrameHeight = _pTexture->GetHeight() / _iLine; m_vFramePos = { 0.f,(FLOAT)((_iFrameline - 1) * m_iFrameHeight) }; } CAnimation::~CAnimation() { } void CAnimation::Update() { m_iCurrentTime = timeGetTime(); if (m_iCurrentTime - m_iOldTime > m_fDelay * 1000) { m_iOldTime = m_iCurrentTime; m_iCurrentFrame++; m_vFramePos.x += m_iFrameWidth; if (m_iCurrentFrame == m_iMaxFrame) { m_vFramePos.x = 0; m_iCurrentFrame = 0; } } } void CAnimation::Render(const Vector2 & _vPos, COLORREF _ColorKey) { m_pTexture->CropRender( _vPos, m_vFramePos, m_iFrameWidth, m_iFrameHeight, _ColorKey ); }
20.869565
104
0.71875
[ "render" ]
74a532922f6302bd7995fbedfbcc36f7a50c94d9
2,413
cpp
C++
plugins/dds/rti/src/PluginFactory.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
1
2021-08-20T12:14:11.000Z
2021-08-20T12:14:11.000Z
plugins/dds/rti/src/PluginFactory.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
3
2021-06-16T19:25:23.000Z
2021-09-02T14:39:10.000Z
plugins/dds/rti/src/PluginFactory.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
null
null
null
// SPDX-FileCopyrightText: 2021 Open Energy Solutions Inc // // SPDX-License-Identifier: Apache-2.0 #include "rti/PluginFactory.h" #include <adapter-util/ConfigStrings.h> #include <adapter-util/config/generated/Profile.h> #include <schema-util/Builder.h> #include "ConfigKeys.h" #include "DDSPlugin.h" namespace adapter { namespace dds { namespace rti { using namespace api; schema::Object PluginFactory::get_plugin_schema() const { return schema::Object({ schema::numeric_property<int64_t>( keys::domain_id, schema::Required::yes, "how many messages to buffer before discarding the oldest", 100, schema::Bound<int64_t>::from(0), schema::Bound<int64_t>::from(232) ), schema::array_property( util::keys::publish, schema::Required::yes, "profile to send to the DDS broker", schema::Object({ schema::enum_property<util::Profile>( schema::Required::yes, "name of the profile to send", util::Profile::Value::SwitchReadingProfile ), schema::string_property( keys::subject, schema::Required::yes, "mRID of the profile to send to, or * for all", "*", schema::StringFormat::Subject ) }) ), schema::array_property( util::keys::subscribe, schema::Required::yes, "profile to receive from the DDS broker", schema::Object({ schema::enum_property<util::Profile>( schema::Required::yes, "name of the profile to subscribe to", util::Profile::Value::SwitchDiscreteControlProfile ), schema::string_property( keys::subject, schema::Required::yes, "mRID of the profile to subscribe to, or * for all", "*", schema::StringFormat::Subject ) }) ) }); } std::unique_ptr<IPlugin> PluginFactory::create(const YAML::Node& node, const Logger& logger, message_bus_t bus) { return std::make_unique<DDSPlugin>(logger, node, bus); } } } }
30.1625
111
0.528388
[ "object" ]
74a6e9f98b8d0996778a1d171764cb806321690d
1,358
hpp
C++
game/code/common/game/bowlergame/bowlerinput.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/game/bowlergame/bowlerinput.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/game/bowlergame/bowlerinput.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
2
2019-03-08T03:02:45.000Z
2019-05-14T08:41:26.000Z
#ifndef BOWLER_INPUT_HPP #define BOWLER_INPUT_HPP ////////////////////////////////////////////////////// // INCLUDES ////////////////////////////////////////////////////// #include <vector> ////////////////////////////////////////////////////// // FORWARD DECLARATIONS ////////////////////////////////////////////////////// class InputManager; ////////////////////////////////////////////////////// // CONSTANTS ////////////////////////////////////////////////////// enum BowlerInputType { BOWLER_INPUT_TYPE_DOWN, BOWLER_INPUT_TYPE_UP, BOWLER_INPUT_TYPE_JUMP_DOWN, BOWLER_INPUT_TYPE_JUMP_UP, }; ////////////////////////////////////////////////////// // STRUCTURES ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // CLASSES ////////////////////////////////////////////////////// class BowlerInput { public: enum KeyState { KEY_DOWN, KEY_UP }; BowlerInput(); ~BowlerInput(); bool GetToggleKey( unsigned char key ); bool GetKey( unsigned char key ); bool GetInput( BowlerInputType intputType ); std::vector<int> GetTouchInput( BowlerInputType intputType ); float GetX( int ID ); float GetY( int ID ); float GetDeltaX( int ID ); float GetDeltaY( int ID ); private: float mCurrentDeltaX; float mCurrentDeltaY; KeyState mKeyState[256]; }; #endif
20.268657
65
0.433726
[ "vector" ]
74aea75ae0e78c0d84c199922afabf02acf3fd85
15,865
cxx
C++
src/nghttp2/Client.cxx
CM4all/beng-proxy
ce5a81f7969bc5cb6c5985cdc98f61ef8b5c6159
[ "BSD-2-Clause" ]
35
2017-08-16T06:52:26.000Z
2022-03-27T21:49:01.000Z
src/nghttp2/Client.cxx
CM4all/beng-proxy
ce5a81f7969bc5cb6c5985cdc98f61ef8b5c6159
[ "BSD-2-Clause" ]
2
2017-12-22T15:34:23.000Z
2022-03-08T04:15:23.000Z
src/nghttp2/Client.cxx
CM4all/beng-proxy
ce5a81f7969bc5cb6c5985cdc98f61ef8b5c6159
[ "BSD-2-Clause" ]
8
2017-12-22T15:11:47.000Z
2022-03-15T22:54:04.000Z
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Client.hxx" #include "Util.hxx" #include "Error.hxx" #include "SocketUtil.hxx" #include "IstreamDataSource.hxx" #include "Option.hxx" #include "Callbacks.hxx" #include "pool/pool.hxx" #include "istream/LengthIstream.hxx" #include "istream/MultiFifoBufferIstream.hxx" #include "istream/New.hxx" #include "fs/FilteredSocket.hxx" #include "util/Cancellable.hxx" #include "util/RuntimeError.hxx" #include "util/StaticArray.hxx" #include "util/StringView.hxx" #include "http/ResponseHandler.hxx" #include "stopwatch.hxx" #include "strmap.hxx" #include "AllocatorPtr.hxx" #include <nghttp2/nghttp2.h> #include <assert.h> namespace NgHttp2 { static constexpr Event::Duration write_timeout = std::chrono::seconds(30); class ClientConnection::Request final : Cancellable, MultiFifoBufferIstreamHandler, IstreamDataSourceHandler, public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { struct pool &pool; enum class State { INITIAL, /** * Receiving response headers. */ HEADERS, /** * Receiving the response body. The * #HttpResponseHandler has been invoked already. */ BODY, } state = State::INITIAL; const StopwatchPtr stopwatch; ClientConnection &connection; HttpResponseHandler &handler; int32_t id = -1; http_status_t status = HTTP_STATUS_OK; StringMap response_headers; MultiFifoBufferIstream *response_body_control; std::unique_ptr<IstreamDataSource> request_body; public: explicit Request(struct pool &_pool, StopwatchPtr &&_stopwatch, ClientConnection &_connection, HttpResponseHandler &_handler, CancellablePointer &cancel_ptr) noexcept :pool(_pool), stopwatch(std::move(_stopwatch)), connection(_connection), handler(_handler) { cancel_ptr = *this; } ~Request() noexcept { if (id >= 0) { if (response_body_control) Consume(response_body_control->GetAvailable()); /* clear stream_user_data to ignore future callbacks on this stream */ nghttp2_session_set_stream_user_data(connection.session.get(), id, nullptr); } connection.RemoveRequest(*this); } void Destroy() noexcept { this->~Request(); } void DestroyEof() noexcept { auto *rbc = response_body_control; Destroy(); rbc->SetEof(); } void AbortError(std::exception_ptr e) noexcept; void DeferWrite() noexcept { connection.DeferWrite(); } void SendRequest(http_method_t method, const char *uri, StringMap &&headers, UnusedIstreamPtr body) noexcept; int SubmitResponse(bool has_response_body) noexcept; int OnEndDataFrame() noexcept; int OnStreamCloseCallback(uint32_t error_code) noexcept; static int OnStreamCloseCallback(nghttp2_session *session, int32_t stream_id, uint32_t error_code, void *) noexcept { auto *request = (Request *) nghttp2_session_get_stream_user_data(session, stream_id); if (request == nullptr) return 0; return request->OnStreamCloseCallback(error_code); } int OnHeaderCallback(StringView name, StringView value) noexcept; static int OnHeaderCallback(nghttp2_session *session, const nghttp2_frame *frame, const uint8_t *name, size_t namelen, const uint8_t *value, size_t valuelen, uint8_t, void *) noexcept { if (frame->hd.type != NGHTTP2_HEADERS || frame->headers.cat != NGHTTP2_HCAT_RESPONSE) return 0; auto *request = (Request *) nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); if (request == nullptr) return 0; return request->OnHeaderCallback({(const char *)name, namelen}, {(const char *)value, valuelen}); } int OnDataChunkReceivedCallback(ConstBuffer<uint8_t> data) noexcept; static int OnDataChunkReceivedCallback(nghttp2_session *session, [[maybe_unused]] uint8_t flags, int32_t stream_id, const uint8_t *data, size_t len, [[maybe_unused]] void *user_data) noexcept { auto &c = *(ClientConnection *)user_data; #ifndef NDEBUG c.unconsumed += len; #endif auto *request = (Request *) nghttp2_session_get_stream_user_data(session, stream_id); if (request == nullptr) { #ifndef NDEBUG c.unconsumed -= len; #endif nghttp2_session_consume(session, stream_id, len); c.DeferWrite(); return 0; } return request->OnDataChunkReceivedCallback({data, len}); } private: void Consume(size_t nbytes) noexcept { #ifndef NDEBUG assert(connection.unconsumed >= nbytes); connection.unconsumed -= nbytes; #endif nghttp2_session_consume(connection.session.get(), id, nbytes); DeferWrite(); } void AbortResponseHeaders(std::exception_ptr e) noexcept { auto &_handler = handler; Destroy(); _handler.InvokeError(std::move(e)); } void AbortResponseBody(std::exception_ptr e) noexcept { Consume(response_body_control->GetAvailable()); response_body_control->DestroyError(std::move(e)); response_body_control = nullptr; Destroy(); } nghttp2_data_provider MakeRequestDataProvider(UnusedIstreamPtr &&istream) noexcept { assert(!request_body); assert(istream); IstreamDataSourceHandler &h = *this; request_body = std::make_unique<IstreamDataSource>(std::move(istream), h); return request_body->MakeDataProvider(); } /* virtual methods from class Cancellable */ void Cancel() noexcept override; /* virtual methods from class MultiFifoBufferIstreamHandler */ void OnFifoBufferIstreamConsumed(size_t nbytes) noexcept override { Consume(nbytes); } void OnFifoBufferIstreamClosed() noexcept override { nghttp2_submit_rst_stream(connection.session.get(), NGHTTP2_FLAG_NONE, id, NGHTTP2_CANCEL); DeferWrite(); Destroy(); } /* virtual methods from class IstreamDataSourceHandler */ void OnIstreamDataSourceReady() noexcept override { assert(request_body); assert(connection.socket); nghttp2_session_resume_data(connection.session.get(), id); DeferWrite(); } }; void ClientConnection::Request::AbortError(std::exception_ptr e) noexcept { switch (state) { case State::INITIAL: Destroy(); break; case State::HEADERS: AbortResponseHeaders(std::move(e)); break; case State::BODY: AbortResponseBody(std::move(e)); break; } } inline void ClientConnection::Request::SendRequest(http_method_t method, const char *uri, StringMap &&headers, UnusedIstreamPtr body) noexcept { assert(state == State::INITIAL); StaticArray<nghttp2_nv, 256> hdrs; hdrs.push_back(MakeNv(":method", http_method_to_string(method))); hdrs.push_back(MakeNv(":scheme", "http")); // TODO const char *host = headers.Remove("host"); if (host != nullptr) hdrs.push_back(MakeNv(":authority", host)); hdrs.push_back(MakeNv(":path", uri)); char content_length_string[32]; if (body) { const auto content_length = body.GetAvailable(false); if (content_length >= 0) { snprintf(content_length_string, sizeof(content_length_string), "%lu", (unsigned long)content_length); hdrs.push_back(MakeNv("content-length", content_length_string)); } } for (const auto &i : headers) hdrs.push_back(MakeNv(i.key, i.value)); nghttp2_data_provider dp, *dpp = nullptr; if (body) { dp = MakeRequestDataProvider(std::move(body)); dpp = &dp; } id = nghttp2_submit_request(connection.session.get(), nullptr, hdrs.data(), hdrs.size(), dpp, this); if (id < 0) { AbortResponseHeaders(std::make_exception_ptr(FormatRuntimeError("nghttp2_submit_request() failed: %s", nghttp2_strerror(id)))); return; } state = State::HEADERS; DeferWrite(); } void ClientConnection::Request::Cancel() noexcept { nghttp2_submit_rst_stream(connection.session.get(), NGHTTP2_FLAG_NONE, id, NGHTTP2_CANCEL); DeferWrite(); Destroy(); } inline int ClientConnection::Request::OnHeaderCallback(StringView name, StringView value) noexcept { AllocatorPtr alloc(pool); if (name.Equals(":status")) { char buffer[4]; if (value.size != 3) return 0; memcpy(buffer, value.data, value.size); buffer[value.size] = 0; char *endptr; auto _status = (http_status_t)strtoul(buffer, &endptr, 10); if (endptr != buffer + value.size || !http_status_is_valid(_status)) return 0; status = _status; } if (name.size >= 2 && name.front() != ':') response_headers.Add(alloc, alloc.DupZ(name), alloc.DupZ(value)); return 0; } inline int ClientConnection::Request::OnDataChunkReceivedCallback(ConstBuffer<uint8_t> data) noexcept { // TODO: limit the MultiFifoBuffer size if (!response_body_control) { Consume(data.size); return 0; } response_body_control->Push(data.ToVoid()); response_body_control->SubmitBuffer(); return 0; } int ClientConnection::Request::SubmitResponse(bool has_response_body) noexcept { UnusedIstreamPtr body; if (has_response_body) { MultiFifoBufferIstreamHandler &fbi_handler = *this; response_body_control = NewFromPool<MultiFifoBufferIstream>(pool, pool, fbi_handler); body = UnusedIstreamPtr(response_body_control); const char *content_length = response_headers.Remove("content-length"); if (content_length != nullptr) { char *endptr; auto length = strtoul(content_length, &endptr, 10); if (endptr > content_length) body = NewIstreamPtr<LengthIstream>(pool, std::move(body), length); } } state = State::BODY; handler.InvokeResponse(status, std::move(response_headers), std::move(body)); if (!has_response_body) Destroy(); return 0; } int ClientConnection::Request::OnEndDataFrame() noexcept { if (!response_body_control) return 0; DestroyEof(); return 0; } int ClientConnection::Request::OnStreamCloseCallback(uint32_t error_code) noexcept { auto error = FormatRuntimeError("Stream closed: %s", nghttp2_http2_strerror(error_code)); AbortError(std::make_exception_ptr(std::move(error))); return 0; } ClientConnection::ClientConnection(std::unique_ptr<FilteredSocket> _socket, ConnectionHandler &_handler) :socket(std::move(_socket)), handler(_handler), defer_invoke_idle(socket->GetEventLoop(), BIND_THIS_METHOD(InvokeIdle)) { socket->Reinit(Event::Duration(-1), write_timeout, *this); NgHttp2::Option option; nghttp2_option_set_no_auto_window_update(option.get(), true); NgHttp2::SessionCallbacks callbacks; nghttp2_session_callbacks_set_send_callback(callbacks.get(), SendCallback); nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks.get(), OnFrameRecvCallback); nghttp2_session_callbacks_set_on_stream_close_callback(callbacks.get(), Request::OnStreamCloseCallback); nghttp2_session_callbacks_set_on_header_callback(callbacks.get(), Request::OnHeaderCallback); nghttp2_session_callbacks_set_on_data_chunk_recv_callback(callbacks.get(), Request::OnDataChunkReceivedCallback); session = NgHttp2::Session::NewClient(callbacks.get(), this, option.get()); static constexpr nghttp2_settings_entry iv[] = { {NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, MAX_CONCURRENT_STREAMS}, {NGHTTP2_SETTINGS_ENABLE_PUSH, false}, }; const auto rv = nghttp2_submit_settings(session.get(), NGHTTP2_FLAG_NONE, iv, std::size(iv)); if (rv != 0) throw MakeError(rv, "nghttp2_submit_settings() failed"); DeferWrite(); socket->ScheduleReadNoTimeout(false); } ClientConnection::~ClientConnection() noexcept { /* all requests must be finished/canceled before this object gets destructed */ assert(requests.empty()); assert(unconsumed == 0); } void ClientConnection::SendRequest(struct pool &request_pool, StopwatchPtr stopwatch, http_method_t method, const char *uri, StringMap &&headers, UnusedIstreamPtr body, HttpResponseHandler &_handler, CancellablePointer &cancel_ptr) noexcept { auto *request = NewFromPool<Request>(request_pool, request_pool, std::move(stopwatch), *this, _handler, cancel_ptr); requests.push_front(*request); defer_invoke_idle.Cancel(); request->SendRequest(method, uri, std::move(headers), std::move(body)); } void ClientConnection::DeferWrite() noexcept { socket->DeferWrite(); } void ClientConnection::RemoveRequest(Request &request) noexcept { requests.erase(requests.iterator_to(request)); if (requests.empty()) { assert(unconsumed == 0); defer_invoke_idle.ScheduleIdle(); } } void ClientConnection::AbortAllRequests(std::exception_ptr e) noexcept { while (!requests.empty()) requests.front().AbortError(e); } ssize_t ClientConnection::SendCallback(const void *data, size_t length) noexcept { return SendToBuffer(*socket, data, length); } int ClientConnection::OnFrameRecvCallback(const nghttp2_frame *frame) noexcept { switch (frame->hd.type) { case NGHTTP2_HEADERS: if (frame->hd.flags & NGHTTP2_FLAG_END_HEADERS) { void *stream_data = nghttp2_session_get_stream_user_data(session.get(), frame->hd.stream_id); if (stream_data == nullptr) return 0; auto &request = *(Request *)stream_data; return request.SubmitResponse((frame->hd.flags & NGHTTP2_FLAG_END_STREAM) == 0); } break; case NGHTTP2_DATA: if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) { void *stream_data = nghttp2_session_get_stream_user_data(session.get(), frame->hd.stream_id); if (stream_data == nullptr) return 0; auto &request = *(Request *)stream_data; return request.OnEndDataFrame(); } break; case NGHTTP2_SETTINGS: for (size_t i = 0; i < frame->settings.niv; ++i) if (frame->settings.iv[i].settings_id == NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS) max_concurrent_streams = std::min<size_t>(frame->settings.iv[i].value, MAX_CONCURRENT_STREAMS); break; case NGHTTP2_GOAWAY: handler.OnNgHttp2ConnectionGoAway(); break; default: break; } return 0; } BufferedResult ClientConnection::OnBufferedData() { return ReceiveFromSocketBuffer(session.get(), *socket); } bool ClientConnection::OnBufferedClosed() noexcept { AbortAllRequests(std::make_exception_ptr(std::runtime_error("Peer closed the socket prematurely"))); handler.OnNgHttp2ConnectionClosed(); return false; } bool ClientConnection::OnBufferedWrite() { return OnSocketWrite(session.get(), *socket); } void ClientConnection::OnBufferedError(std::exception_ptr e) noexcept { AbortAllRequests(e); handler.OnNgHttp2ConnectionError(std::move(e)); } } // namespace NgHttp2
25.547504
104
0.727829
[ "object" ]
74b00b5c0e43ebcea956bef7466b0f59a3e96fd7
4,091
cpp
C++
Tests/TestHamEvol.cpp
chaeyeunpark/Yavque
eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d
[ "Apache-2.0" ]
null
null
null
Tests/TestHamEvol.cpp
chaeyeunpark/Yavque
eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d
[ "Apache-2.0" ]
null
null
null
Tests/TestHamEvol.cpp
chaeyeunpark/Yavque
eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d
[ "Apache-2.0" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <Eigen/Dense> #include <catch.hpp> #include <random> #include "EDP/ConstructSparseMat.hpp" #include "EDP/LocalHamiltonian.hpp" #include "yavque/Operators/HamEvol.hpp" #include "yavque/utils.hpp" #include "common.hpp" template<typename RandomEngine> void test_single_qubit(const uint32_t N, const Eigen::SparseMatrix<double>& m, RandomEngine& re) { using namespace Eigen; using std::cos; using std::exp; using std::sin; using std::sqrt; constexpr yavque::cx_double I(0., 1.); std::normal_distribution<> nd; edp::LocalHamiltonian<double> ham_ct(N, 2); for(uint32_t i = 0; i < N; i++) { ham_ct.addOneSiteTerm(i, m); } auto ham = yavque::Hamiltonian(edp::constructSparseMat<yavque::cx_double>(1 << N, ham_ct)); auto hamEvol = yavque::HamEvol(ham); auto var = hamEvol.get_variable(); for(int i = 0; i < 100; i++) { VectorXcd ini = VectorXcd::Random(1 << N); ini.normalize(); double t = nd(re); var = t; VectorXcd out_test = hamEvol * ini; MatrixXcd mevol = (cos(t) * MatrixXcd::Identity(2, 2) - I * sin(t) * m); VectorXcd out = apply_kronecker(N, mevol, ini); REQUIRE((out - out_test).norm() < 1e-6); } hamEvol.dagger_in_place(); for(int i = 0; i < 100; i++) { VectorXcd ini = VectorXcd::Random(1 << N); ini.normalize(); double t = nd(re); var = t; VectorXcd out_test = hamEvol * ini; MatrixXcd mevol = (cos(t) * MatrixXcd::Identity(2, 2) + I * sin(t) * m); VectorXcd out = apply_kronecker(N, mevol, ini); REQUIRE((out - out_test).norm() < 1e-6); } } TEST_CASE("test single qubit Hamiltonian", "[one-site]") { constexpr uint32_t N = 8; // number of qubits // ini is |+>^N std::random_device rd; std::default_random_engine re{rd()}; SECTION("test using pauli X") { test_single_qubit(N, yavque::pauli_x(), re); } SECTION("test using pauli Z") { test_single_qubit(N, yavque::pauli_z(), re); } } TEST_CASE("Test basic operations", "[basic]") { using namespace Eigen; using namespace yavque; using std::cos; using std::exp; using std::sin; using std::sqrt; constexpr uint32_t N = 8; // number of qubits // ini is |+>^N VectorXcd ini = VectorXcd::Ones(1 << N); ini /= sqrt(1 << N); std::random_device rd; std::default_random_engine re{rd()}; std::normal_distribution<> nd; constexpr yavque::cx_double I(0., 1.); edp::LocalHamiltonian<double> ham_ct(N, 2); for(uint32_t i = 0; i < N; i++) { ham_ct.addOneSiteTerm(i, yavque::pauli_x()); } auto ham = yavque::Hamiltonian(edp::constructSparseMat<yavque::cx_double>(1 << N, ham_ct)); auto hamEvol = HamEvol(ham); auto copied = hamEvol.clone(); REQUIRE(hamEvol.get_variable() != dynamic_cast<HamEvol*>(copied.get())->get_variable()); REQUIRE(hamEvol.hamiltonian().is_same_ham( dynamic_cast<HamEvol*>(copied.get())->hamiltonian())); } TEST_CASE("Test gradient", "[log-deriv]") { using namespace Eigen; using namespace yavque; using std::cos; using std::exp; using std::sin; using std::sqrt; constexpr uint32_t N = 8; // number of qubits std::random_device rd; std::default_random_engine re{rd()}; std::vector<Eigen::SparseMatrix<double>> pauli_ops = {yavque::pauli_xx(), yavque::pauli_yy(), yavque::pauli_zz()}; std::uniform_int_distribution<> uid(0, 2); std::normal_distribution<> nd; for(uint32_t k = 0; k < 100; ++k) // instances { // ini is random VectorXcd ini = VectorXcd::Random(1 << N); ini.normalize(); edp::LocalHamiltonian<double> ham_ct(N, 2); ham_ct.addTwoSiteTerm(random_connection(N, re), pauli_ops[uid(re)]); auto ham = yavque::Hamiltonian( edp::constructSparseMat<yavque::cx_double>(1 << N, ham_ct)); auto hamEvol = HamEvol(ham); double val = nd(re); hamEvol.set_variable_value(val); Eigen::VectorXcd grad1 = hamEvol.log_deriv()->apply_right(hamEvol.apply_right(ini)); hamEvol.get_variable() += M_PI / 2; Eigen::VectorXcd grad2 = hamEvol.apply_right(ini); hamEvol.get_variable() = val - M_PI / 2; grad2 -= hamEvol.apply_right(ini); grad2 /= 2.0; REQUIRE((grad1 - grad2).norm() < 1e-6); } }
24.35119
84
0.668541
[ "vector" ]
74b69d3f29587ad5e8ae0906506ad816e41e2965
15,427
cpp
C++
Modules/DiffusionImaging/FiberTracking/Fiberfox/itkKspaceImageFilter.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
1
2021-11-20T08:19:27.000Z
2021-11-20T08:19:27.000Z
Modules/DiffusionImaging/FiberTracking/Fiberfox/itkKspaceImageFilter.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
null
null
null
Modules/DiffusionImaging/FiberTracking/Fiberfox/itkKspaceImageFilter.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
null
null
null
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __itkKspaceImageFilter_txx #define __itkKspaceImageFilter_txx #include <ctime> #include <cstdio> #include <cstdlib> #include "itkKspaceImageFilter.h" #include <itkImageRegionConstIterator.h> #include <itkImageRegionConstIteratorWithIndex.h> #include <itkImageRegionIterator.h> #include <mitkSingleShotEpi.h> #include <mitkCartesianReadout.h> #include <mitkDiffusionFunctionCollection.h> namespace itk { template< class ScalarType > KspaceImageFilter< ScalarType >::KspaceImageFilter() : m_Z(0) , m_UseConstantRandSeed(false) , m_SpikesPerSlice(0) , m_IsBaseline(true) { m_DiffusionGradientDirection.Fill(0.0); m_CoilPosition.Fill(0.0); m_FmapInterpolator = itk::LinearInterpolateImageFunction< itk::Image< float, 3 >, float >::New(); } template< class ScalarType > void KspaceImageFilter< ScalarType > ::BeforeThreadedGenerateData() { m_Spike = vcl_complex<ScalarType>(0,0); m_SpikeLog = ""; typename OutputImageType::Pointer outputImage = OutputImageType::New(); itk::ImageRegion<2> region; region.SetSize(0, m_Parameters->m_SignalGen.m_CroppedRegion.GetSize(0)); region.SetSize(1, m_Parameters->m_SignalGen.m_CroppedRegion.GetSize(1)); outputImage->SetLargestPossibleRegion( region ); outputImage->SetBufferedRegion( region ); outputImage->SetRequestedRegion( region ); outputImage->Allocate(); outputImage->FillBuffer(m_Spike); m_KSpaceImage = InputImageType::New(); m_KSpaceImage->SetLargestPossibleRegion( region ); m_KSpaceImage->SetBufferedRegion( region ); m_KSpaceImage->SetRequestedRegion( region ); m_KSpaceImage->Allocate(); m_KSpaceImage->FillBuffer(0.0); m_Gamma = 42576000; // Gyromagnetic ratio in Hz/T (1.5T) if ( m_Parameters->m_SignalGen.m_EddyStrength>0 && m_DiffusionGradientDirection.GetNorm()>0.001) { m_DiffusionGradientDirection.Normalize(); m_DiffusionGradientDirection = m_DiffusionGradientDirection * m_Parameters->m_SignalGen.m_EddyStrength/1000 * m_Gamma; m_IsBaseline = false; } this->SetNthOutput(0, outputImage); for (int i=0; i<3; i++) for (int j=0; j<3; j++) m_Transform[i][j] = m_Parameters->m_SignalGen.m_ImageDirection[i][j] * m_Parameters->m_SignalGen.m_ImageSpacing[j]; float a = m_Parameters->m_SignalGen.m_ImageRegion.GetSize(0)*m_Parameters->m_SignalGen.m_ImageSpacing[0]; float b = m_Parameters->m_SignalGen.m_ImageRegion.GetSize(1)*m_Parameters->m_SignalGen.m_ImageSpacing[1]; float diagonal = sqrt(a*a+b*b)/1000; // image diagonal in m switch (m_Parameters->m_SignalGen.m_CoilSensitivityProfile) { case SignalGenerationParameters::COIL_CONSTANT: { m_CoilSensitivityFactor = 1; // same signal everywhere break; } case SignalGenerationParameters::COIL_LINEAR: { m_CoilSensitivityFactor = -1/diagonal; // about 50% of the signal in the image center remaining break; } case SignalGenerationParameters::COIL_EXPONENTIAL: { m_CoilSensitivityFactor = -log(0.1)/diagonal; // about 32% of the signal in the image center remaining break; } } switch (m_Parameters->m_SignalGen.m_AcquisitionType) { case SignalGenerationParameters::SingleShotEpi: m_ReadoutScheme = new mitk::SingleShotEpi(m_Parameters); break; case SignalGenerationParameters::SpinEcho: m_ReadoutScheme = new mitk::CartesianReadout(m_Parameters); break; default: m_ReadoutScheme = new mitk::SingleShotEpi(m_Parameters); } m_ReadoutScheme->AdjustEchoTime(); m_FmapInterpolator->SetInputImage(m_Parameters->m_SignalGen.m_FrequencyMap); } template< class ScalarType > float KspaceImageFilter< ScalarType >::CoilSensitivity(VectorType& pos) { // ************************************************************************* // Coil ring is moving with excited slice (FIX THIS SOMETIME) m_CoilPosition[2] = pos[2]; // ************************************************************************* switch (m_Parameters->m_SignalGen.m_CoilSensitivityProfile) { case SignalGenerationParameters::COIL_CONSTANT: return 1; case SignalGenerationParameters::COIL_LINEAR: { VectorType diff = pos-m_CoilPosition; float sens = diff.GetNorm()*m_CoilSensitivityFactor + 1; if (sens<0) sens = 0; return sens; } case SignalGenerationParameters::COIL_EXPONENTIAL: { VectorType diff = pos-m_CoilPosition; float dist = diff.GetNorm(); return std::exp(-dist*m_CoilSensitivityFactor); } default: return 1; } } template< class ScalarType > void KspaceImageFilter< ScalarType > ::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType) { itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randGen = itk::Statistics::MersenneTwisterRandomVariateGenerator::New(); randGen->SetSeed(); if (m_UseConstantRandSeed) // always generate the same random numbers? { randGen->SetSeed(0); } else { randGen->SetSeed(); } typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0)); ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread); typedef ImageRegionConstIterator< InputImageType > InputIteratorType; float kxMax = m_Parameters->m_SignalGen.m_CroppedRegion.GetSize(0); float kyMax = m_Parameters->m_SignalGen.m_CroppedRegion.GetSize(1); float xMax = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(0); // scanner coverage in x-direction float yMax = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(1); // scanner coverage in y-direction float yMaxFov = yMax; if (m_Parameters->m_Misc.m_DoAddAliasing) yMaxFov *= m_Parameters->m_SignalGen.m_CroppingFactor; // actual FOV in y-direction (in x-direction FOV=xMax) float numPix = kxMax*kyMax; // Adjust noise variance since it is the intended variance in physical space and not in k-space: float noiseVar = m_Parameters->m_SignalGen.m_PartialFourier*m_Parameters->m_SignalGen.m_NoiseVariance/(kyMax*kxMax); while( !oit.IsAtEnd() ) { typename OutputImageType::IndexType out_idx = oit.GetIndex(); // time from maximum echo float t= m_ReadoutScheme->GetTimeFromMaxEcho(out_idx); // time passed since k-space readout started float tRead = m_ReadoutScheme->GetRedoutTime(out_idx); // time passes since application of the RF pulse float tRf = m_Parameters->m_SignalGen.m_tEcho+t; // calculate eddy current decay factor // (TODO: vielleicht umbauen dass hier die zeit vom letzten diffusionsgradienten an genommen wird. doku dann auch entsprechend anpassen.) float eddyDecay = 0; if ( m_Parameters->m_Misc.m_DoAddEddyCurrents && m_Parameters->m_SignalGen.m_EddyStrength>0) { eddyDecay = std::exp(-tRead/m_Parameters->m_SignalGen.m_Tau ); } // calcualte signal relaxation factors std::vector< float > relaxFactor; if ( m_Parameters->m_SignalGen.m_DoSimulateRelaxation) { for (unsigned int i=0; i<m_CompartmentImages.size(); i++) { relaxFactor.push_back( std::exp(-tRf/m_T2.at(i) -fabs(t)/ m_Parameters->m_SignalGen.m_tInhom) * (1.0-std::exp(-(m_Parameters->m_SignalGen.m_tRep + tRf)/m_T1.at(i))) ); } } // get current k-space index (depends on the chosen k-space readout scheme) itk::Index< 2 > kIdx = m_ReadoutScheme->GetActualKspaceIndex(out_idx); // partial fourier bool pf = false; if (kIdx[1]>kyMax*m_Parameters->m_SignalGen.m_PartialFourier) pf = true; if (!pf) { // shift k for DFT: (0 -- N) --> (-N/2 -- N/2) float kx = kIdx[0]; float ky = kIdx[1]; if ((int)kxMax%2==1){ kx -= (kxMax-1)/2; } else{ kx -= kxMax/2; } if ((int)kyMax%2==1){ ky -= (kyMax-1)/2; } else{ ky -= kyMax/2; } // add ghosting by adding gradient delay induced offset if (m_Parameters->m_Misc.m_DoAddGhosts) { if (out_idx[1]%2 == 1) kx -= m_Parameters->m_SignalGen.m_KspaceLineOffset; else kx += m_Parameters->m_SignalGen.m_KspaceLineOffset; } vcl_complex<ScalarType> s(0,0); InputIteratorType it(m_CompartmentImages.at(0), m_CompartmentImages.at(0)->GetLargestPossibleRegion() ); while( !it.IsAtEnd() ) { typename InputImageType::IndexType input_idx = it.GetIndex(); float x = input_idx[0]; float y = input_idx[1]; if ((int)xMax%2==1){ x -= (xMax-1)/2; } else{ x -= xMax/2; } if ((int)yMax%2==1){ y -= (yMax-1)/2; } else{ y -= yMax/2; } VectorType pos; pos[0] = x; pos[1] = y; pos[2] = m_Z; pos = m_Transform*pos/1000; // vector from image center to current position (in meter) vcl_complex<ScalarType> f(0, 0); // sum compartment signals and simulate relaxation for (unsigned int i=0; i<m_CompartmentImages.size(); i++) if ( m_Parameters->m_SignalGen.m_DoSimulateRelaxation) f += std::complex<ScalarType>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * relaxFactor.at(i) * m_Parameters->m_SignalGen.m_SignalScale, 0); else f += std::complex<ScalarType>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * m_Parameters->m_SignalGen.m_SignalScale, 0); if (m_Parameters->m_SignalGen.m_CoilSensitivityProfile!=SignalGenerationParameters::COIL_CONSTANT) f *= CoilSensitivity(pos); // simulate eddy currents and other distortions float omega = 0; // frequency offset if ( m_Parameters->m_SignalGen.m_EddyStrength>0 && m_Parameters->m_Misc.m_DoAddEddyCurrents && !m_IsBaseline) { omega += (m_DiffusionGradientDirection[0]*pos[0]+m_DiffusionGradientDirection[1]*pos[1]+m_DiffusionGradientDirection[2]*pos[2]) * eddyDecay; } if (m_Parameters->m_Misc.m_DoAddDistortions && m_Parameters->m_SignalGen.m_FrequencyMap.IsNotNull()) // simulate distortions { itk::Point<double, 3> point3D; itk::Image<float, 3>::IndexType index; index[0] = input_idx[0]; index[1] = input_idx[1]; index[2] = m_Zidx; if (m_Parameters->m_SignalGen.m_DoAddMotion) // we have to account for the head motion since this also moves our frequency map { m_Parameters->m_SignalGen.m_FrequencyMap->TransformIndexToPhysicalPoint(index, point3D); point3D = m_FiberBundle->TransformPoint( point3D.GetVnlVector(), -m_Rotation[0], -m_Rotation[1], -m_Rotation[2], -m_Translation[0], -m_Translation[1], -m_Translation[2] ); omega += mitk::imv::GetImageValue<float>(point3D, true, m_FmapInterpolator); } else { omega += m_Parameters->m_SignalGen.m_FrequencyMap->GetPixel(index); } } // if signal comes from outside FOV, mirror it back (wrap-around artifact - aliasing) if (y<-yMaxFov/2) y += yMaxFov; else if (y>=yMaxFov/2) y -= yMaxFov; // actual DFT term s += f * std::exp( std::complex<ScalarType>(0, 2 * itk::Math::pi * (kx*x/xMax + ky*y/yMaxFov + omega*t/1000 )) ); ++it; } s /= numPix; if (m_SpikesPerSlice>0 && sqrt(s.imag()*s.imag()+s.real()*s.real()) > sqrt(m_Spike.imag()*m_Spike.imag()+m_Spike.real()*m_Spike.real()) ) m_Spike = s; if (m_Parameters->m_SignalGen.m_NoiseVariance>0 && m_Parameters->m_Misc.m_DoAddNoise) s = vcl_complex<ScalarType>(s.real()+randGen->GetNormalVariate(0,noiseVar), s.imag()+randGen->GetNormalVariate(0,noiseVar)); outputImage->SetPixel(kIdx, s); m_KSpaceImage->SetPixel(kIdx, sqrt(s.imag()*s.imag()+s.real()*s.real()) ); } ++oit; } } template< class ScalarType > void KspaceImageFilter< ScalarType > ::AfterThreadedGenerateData() { delete m_ReadoutScheme; typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0)); float kxMax = outputImage->GetLargestPossibleRegion().GetSize(0); // k-space size in x-direction float kyMax = outputImage->GetLargestPossibleRegion().GetSize(1); // k-space size in y-direction ImageRegionIterator< OutputImageType > oit(outputImage, outputImage->GetLargestPossibleRegion()); while( !oit.IsAtEnd() ) // use hermitian k-space symmetry to fill empty k-space parts resulting from partial fourier acquisition { itk::Index< 2 > kIdx; kIdx[0] = oit.GetIndex()[0]; kIdx[1] = oit.GetIndex()[1]; // reverse phase if (!m_Parameters->m_SignalGen.m_ReversePhase) kIdx[1] = kyMax-1-kIdx[1]; if (kIdx[1]>kyMax*m_Parameters->m_SignalGen.m_PartialFourier) { // reverse readout direction if (oit.GetIndex()[1]%2 == 1) kIdx[0] = kxMax-kIdx[0]-1; // calculate symmetric index itk::Index< 2 > kIdx2; kIdx2[0] = (int)(kxMax-kIdx[0]-(int)kxMax%2)%(int)kxMax; kIdx2[1] = (int)(kyMax-kIdx[1]-(int)kyMax%2)%(int)kyMax; // use complex conjugate of symmetric index value at current index vcl_complex<ScalarType> s = outputImage->GetPixel(kIdx2); s = vcl_complex<ScalarType>(s.real(), -s.imag()); outputImage->SetPixel(kIdx, s); m_KSpaceImage->SetPixel(kIdx, sqrt(s.imag()*s.imag()+s.real()*s.real()) ); } ++oit; } itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randGen = itk::Statistics::MersenneTwisterRandomVariateGenerator::New(); randGen->SetSeed(); if (m_UseConstantRandSeed) // always generate the same random numbers? randGen->SetSeed(0); else randGen->SetSeed(); m_Spike *= m_Parameters->m_SignalGen.m_SpikeAmplitude; itk::Index< 2 > spikeIdx; for (unsigned int i=0; i<m_SpikesPerSlice; i++) { spikeIdx[0] = randGen->GetIntegerVariate()%(int)kxMax; spikeIdx[1] = randGen->GetIntegerVariate()%(int)kyMax; outputImage->SetPixel(spikeIdx, m_Spike); m_SpikeLog += "[" + boost::lexical_cast<std::string>(spikeIdx[0]) + "," + boost::lexical_cast<std::string>(spikeIdx[1]) + "," + boost::lexical_cast<std::string>(m_Zidx) + "] Magnitude: " + boost::lexical_cast<std::string>(m_Spike.real()) + "+" + boost::lexical_cast<std::string>(m_Spike.imag()) + "i\n"; } } } #endif
40.07013
309
0.648603
[ "vector" ]
74bbf0b861e68fbb97020d5a05bbae035d02837f
828
cpp
C++
visualization/src/main.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
27
2017-09-21T19:52:28.000Z
2022-03-09T13:47:02.000Z
visualization/src/main.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
12
2017-07-26T15:00:32.000Z
2021-12-03T03:08:15.000Z
visualization/src/main.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
11
2017-03-24T16:56:08.000Z
2020-11-21T13:18:33.000Z
#include <iostream> #include "pcl/console/parse.h" #include "rapter/typedefs.h" #include "rapter/visualization/visualization.h" #include "rapter/visualization/mst.hpp" #include "rapter/primitives/impl/planePrimitive.hpp" #include "rapter/primitives/impl/linePrimitive.hpp" int main(int argc, char *argv[]) { //return rapter::mstMain<float>(); if ( pcl::console::find_switch(argc,argv,"--show") ) { return rapter::vis::showCli<rapter::_2d::PrimitiveT>( argc, argv ); } else if ( pcl::console::find_switch(argc,argv,"--show3D") ) { return rapter::vis::showCli<rapter::_3d::PrimitiveT>( argc, argv ); } else { std::cerr << "[" << __func__ << "]: " << "unrecognized cli option" << std::endl; std::cout << "usage: " << "--show[3D] --help" << std::endl; } }
28.551724
88
0.621981
[ "3d" ]
74be25b5db09ce1d4ecd29663f1fa8e02567f957
3,758
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcLightSourceAmbient.cpp
yorikvanhavre/ifcplusplus
eec5160bfb07de66ad40db48bb7eca66e9351b85
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcLightSourceAmbient.cpp
yorikvanhavre/ifcplusplus
eec5160bfb07de66ad40db48bb7eca66e9351b85
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcLightSourceAmbient.cpp
yorikvanhavre/ifcplusplus
eec5160bfb07de66ad40db48bb7eca66e9351b85
[ "MIT" ]
null
null
null
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcColourRgb.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcLightSourceAmbient.h" #include "ifcpp/IFC4/include/IfcNormalisedRatioMeasure.h" #include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h" #include "ifcpp/IFC4/include/IfcStyledItem.h" // ENTITY IfcLightSourceAmbient IfcLightSourceAmbient::IfcLightSourceAmbient() {} IfcLightSourceAmbient::IfcLightSourceAmbient( int id ) { m_entity_id = id; } IfcLightSourceAmbient::~IfcLightSourceAmbient() {} shared_ptr<BuildingObject> IfcLightSourceAmbient::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcLightSourceAmbient> copy_self( new IfcLightSourceAmbient() ); if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_LightColour ) { copy_self->m_LightColour = dynamic_pointer_cast<IfcColourRgb>( m_LightColour->getDeepCopy(options) ); } if( m_AmbientIntensity ) { copy_self->m_AmbientIntensity = dynamic_pointer_cast<IfcNormalisedRatioMeasure>( m_AmbientIntensity->getDeepCopy(options) ); } if( m_Intensity ) { copy_self->m_Intensity = dynamic_pointer_cast<IfcNormalisedRatioMeasure>( m_Intensity->getDeepCopy(options) ); } return copy_self; } void IfcLightSourceAmbient::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCLIGHTSOURCEAMBIENT" << "("; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_LightColour ) { stream << "#" << m_LightColour->m_entity_id; } else { stream << "$"; } stream << ","; if( m_AmbientIntensity ) { m_AmbientIntensity->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Intensity ) { m_Intensity->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcLightSourceAmbient::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; } const std::wstring IfcLightSourceAmbient::toString() const { return L"IfcLightSourceAmbient"; } void IfcLightSourceAmbient::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 4 ){ std::stringstream err; err << "Wrong parameter count for entity IfcLightSourceAmbient, expecting 4, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_Name = IfcLabel::createObjectFromSTEP( args[0], map ); readEntityReference( args[1], m_LightColour, map ); m_AmbientIntensity = IfcNormalisedRatioMeasure::createObjectFromSTEP( args[2], map ); m_Intensity = IfcNormalisedRatioMeasure::createObjectFromSTEP( args[3], map ); } void IfcLightSourceAmbient::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) { IfcLightSource::getAttributes( vec_attributes ); } void IfcLightSourceAmbient::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) { IfcLightSource::getAttributesInverse( vec_attributes_inverse ); } void IfcLightSourceAmbient::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcLightSource::setInverseCounterparts( ptr_self_entity ); } void IfcLightSourceAmbient::unlinkFromInverseCounterparts() { IfcLightSource::unlinkFromInverseCounterparts(); }
54.463768
239
0.748803
[ "vector", "model" ]
74c35b8c53f3979b94e4178afdc78d8166e698d6
1,155
hpp
C++
Cpp/AdvancedCpp/AdvancedMultithreaded/OtherThreadImplementation/inc/thread_group.hpp
NatanMeirov/ExperisAcademyBootcamp
6608ef5571e6dc4eb1f481695da3476ecd4f7547
[ "MIT" ]
null
null
null
Cpp/AdvancedCpp/AdvancedMultithreaded/OtherThreadImplementation/inc/thread_group.hpp
NatanMeirov/ExperisAcademyBootcamp
6608ef5571e6dc4eb1f481695da3476ecd4f7547
[ "MIT" ]
null
null
null
Cpp/AdvancedCpp/AdvancedMultithreaded/OtherThreadImplementation/inc/thread_group.hpp
NatanMeirov/ExperisAcademyBootcamp
6608ef5571e6dc4eb1f481695da3476ecd4f7547
[ "MIT" ]
null
null
null
#ifndef NM_THREAD_GROUP_HPP #define NM_THREAD_GROUP_HPP #include <cstddef> // size_t #include <vector> #include <memory> // std::shared_ptr #include "icallable.hpp" #include "thread.hpp" namespace advcpp { /* Warning: The given ICallable task will be SHARED in all the N threads - make sure that the given task is thread-safe! */ class ThreadGroup { public: enum GroupDestructionAction { JOIN, DETACH, CANCEL, ASSERTION }; ThreadGroup(std::shared_ptr<ICallable> a_commonTask, const size_t a_threadsCount, GroupDestructionAction a_destructionActionIndicator = JOIN); ThreadGroup(const ThreadGroup& a_other) = delete; ThreadGroup& operator=(const ThreadGroup& a_other) = delete; ~ThreadGroup(); // Each Thread handles its destruction, specified by DestructionAction option void Join(); void Detach(); void Cancel(bool a_ensureCompleteCancelation = false); private: static constexpr Thread::DestructionAction DESTRUCT_THREAD_OPT[] = {Thread::JOIN, Thread::DETACH, Thread::CANCEL, Thread::ASSERTION}; private: std::vector<std::shared_ptr<Thread>> m_threadsGroup; }; } // advcpp #endif // NM_THREAD_GROUP_HPP
28.875
146
0.751515
[ "vector" ]
74c3eb577066dae012d9cc5185e9d373752a728a
12,563
cpp
C++
game/code/common/engine/system/debug/debugmenu.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/engine/system/debug/debugmenu.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/engine/system/debug/debugmenu.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
2
2019-03-08T03:02:45.000Z
2019-05-14T08:41:26.000Z
////////////////////////////////////////////////////// // INCLUDES ////////////////////////////////////////////////////// #include "common/engine/database/database.hpp" #include "common/engine/game/gameapp.hpp" #include "common/engine/render/font.hpp" #include "common/engine/render/material.hpp" #include "common/engine/render/simpledraw.hpp" #include "common/engine/system/debug/debugmenu.hpp" #include "common/engine/system/debug/debugvariablehelper.hpp" #include "common/engine/system/debug/directoryvariable.hpp" #include "common/engine/system/keyboard.hpp" #include "common/engine/system/memory.hpp" ////////////////////////////////////////////////////// // GLOBALS ////////////////////////////////////////////////////// namespace System { namespace Debug { DebugMenu* DebugMenu::mInstance = NULL; } } const int NUM_DISPLAY_ITEMS = 18; ////////////////////////////////////////////////////// // CLASS METHODS ////////////////////////////////////////////////////// namespace System { namespace Debug { void DebugMenu::Create() { Assert( mInstance == NULL, "" ); mInstance = NEW_PTR( "Debug Menu" ) DebugMenu; } //=========================================================================== void DebugMenu::Destroy() { DELETE_PTR( mInstance ); } //=========================================================================== DebugMenu* DebugMenu::Get() { Assert( mInstance != NULL, "" ); return mInstance; } //=========================================================================== void DebugMenu::KeyboardDown( unsigned char key ) { if ( key == System::GetKeyValue( KB_UP_ARROW ) ) { mCurrentItemIndex--; if ( mCurrentItemIndex < 0 ) { mCurrentItemIndex = 0; } if ( mCurrentItemIndex < mStartItemIndex ) { mStartItemIndex--; mEndItemIndex--; } } else if ( key == System::GetKeyValue( KB_DOWN_ARROW ) ) { mCurrentItemIndex++; int numItems = mCurrentDirectoryItem->GetDirectoryList()->GetSize(); if ( mCurrentItemIndex >= numItems ) { mCurrentItemIndex--; } if ( mCurrentItemIndex >= mEndItemIndex ) { mStartItemIndex++; mEndItemIndex++; } } else if ( key == System::GetKeyValue( KB_LEFT_ARROW ) || key == System::GetKeyValue( KB_RIGHT_ARROW ) ) { int count = 0; List<DirectoryItem*>::Iterator iter = mCurrentDirectoryItem->GetDirectoryList()->CreateIterator(); while ( iter.HasNext() ) { DirectoryItem* item = iter.Next(); if ( item->GetType() == VARIABLE_TYPE ) { DirectoryVariable* variableItem = reinterpret_cast<DirectoryVariable*>( item ); DebugVariable* variable = variableItem->GetVariable(); if ( count == mCurrentItemIndex ) { variable->KeyboardDown( key ); break; } } count++; } } } //=========================================================================== void DebugMenu::KeyboardChar( unsigned char key ) { if ( key == System::GetKeyValue( KB_ENTER ) ) { int count = 0; List<DirectoryItem*>::Iterator iter = mCurrentDirectoryItem->GetDirectoryList()->CreateIterator(); while ( iter.HasNext() ) { DirectoryItem* item = iter.Next(); if ( count == mCurrentItemIndex ) { if ( item->GetType() == SUB_DIRECTORY_TYPE ) { DirectorySubDir* subDirectoryItem = reinterpret_cast<DirectorySubDir*>( item ); mCurrentDirectoryItem = subDirectoryItem; mSelectionHistory.push( mCurrentItemIndex ); mCurrentItemIndex = 0; mStartItemIndex = 0; mEndItemIndex = NUM_DISPLAY_ITEMS; break; } } count++; } } else if ( key == System::GetKeyValue( KB_BACKSPACE ) ) { DirectorySubDir* directoryItem = mCurrentDirectoryItem->GetPreviousDirectoryItem(); if ( directoryItem != NULL ) { mCurrentDirectoryItem = directoryItem; mCurrentItemIndex = mSelectionHistory.back(); mSelectionHistory.pop(); mStartItemIndex = 0; mEndItemIndex = NUM_DISPLAY_ITEMS; } } } //=========================================================================== void DebugMenu::Update() { } //=========================================================================== void DebugMenu::Render() { Renderer::Get()->ClearDepth( NULL ); SimpleDraw* simpleDraw = GameApp::Get()->GetSimpleDraw(); Math::Matrix44 transform; transform.SetIdentity(); float halfscreenWidthSize = static_cast<float>( Database::Get()->GetAppScreenWidth() ) /2.0f; float halfscreenHeightSize = static_cast<float>( Database::Get()->GetAppScreenHeight() ) /2.0f; Math::Matrix44 orthoMatrix = Renderer::Get()->GetOrthoProjection( -halfscreenWidthSize, -halfscreenHeightSize, halfscreenWidthSize, halfscreenHeightSize, -100, 100 ); Math::Matrix44 projectionMatrix = orthoMatrix; Math::Matrix44 viewMatrix; viewMatrix.SetIdentity(); Math::Matrix44 objectToProjection = projectionMatrix * transform; objectToProjection *= viewMatrix; simpleDraw->SetProjectionMatrix( projectionMatrix ); simpleDraw->SetViewMatrix( viewMatrix ); simpleDraw->SetTransformMatrix( transform ); simpleDraw->SetDiffuseColor( Math::Vector4( 0.3f, 0.3f, 0.3f, 0.5f ) ); const float windowX = -120; const float windowWidth = 220; const float windowY = 100; const float windowHeight = 200; const Math::Vector3 v0( windowX, windowY, 0 ); const Math::Vector3 v1( windowX, windowY - windowHeight, 0 ); const Math::Vector3 v2( windowX + windowWidth, windowY - windowHeight, 0 ); const Math::Vector3 v3( windowX + windowWidth, windowY, 0 ); simpleDraw->RenderQuad( v0, v1, v2, v3 ); float textY = 0.0f; int count = 0; const float xNameOffset = windowX + 2.0f; const float xValueOffset = 50.0f; const float yNameOffset = windowY - 20.0f; const float yIncrement = 10.0f; List<DirectoryItem*>::Iterator iter = mCurrentDirectoryItem->GetDirectoryList()->CreateIterator(); while ( iter.HasNext() ) { DirectoryItem* item = iter.Next(); if ( count >= mStartItemIndex && count < mEndItemIndex ) { Math::Vector4 color = TEXT_COLOR_WHITE; if ( count == mCurrentItemIndex ) { color = TEXT_COLOR_RED; } float yPos = yNameOffset - textY; mFont->AddToBuffer( xNameOffset, yPos, 500, 50, TEXT_HORIZONTAL_ALIGN_LEFT, TEXT_VERTICAL_ALIGN_BOTTOM, color, item->GetName() ); if ( item->GetType() == VARIABLE_TYPE ) { DirectoryVariable* variableItem = reinterpret_cast<DirectoryVariable*>( item ); DebugVariable* variable = variableItem->GetVariable(); char buffer[256]; switch ( variable->GetType() ) { case System::Debug::VAR_INT: { DebugVariableInt* variableInt = reinterpret_cast<DebugVariableInt*>( variable ); snprintf( buffer, 256, "%i", (int)*variableInt ); } break; case System::Debug::VAR_FLOAT: { DebugVariableFloat* variableFloat = reinterpret_cast<DebugVariableFloat*>( variable ); snprintf( buffer, 256, "%3.2f", (float)*variableFloat ); } break; case System::Debug::VAR_BOOL: { DebugVariableBool* variableBool = reinterpret_cast<DebugVariableBool*>( variable ); if ( (bool)*variableBool == true ) { snprintf( buffer, 256, "true" ); } else { snprintf( buffer, 256, "false" ); } } break; default: break; } mFont->AddToBuffer( xValueOffset, yPos, 500, 50, TEXT_HORIZONTAL_ALIGN_LEFT, TEXT_VERTICAL_ALIGN_BOTTOM, color, buffer ); } textY += yIncrement; } count++; } transform.SetIdentity(); transform.Translate( 0, 0, 0 ); Math::Rectangle<int> scissorRectangle; scissorRectangle.SetPosition( 0, 0 ); scissorRectangle.SetWidth( Database::Get()->GetBackBufferWidth() ); scissorRectangle.SetHeight( Database::Get()->GetBackBufferHeight() ); mFont->RenderBuffers( orthoMatrix, transform, scissorRectangle ); } //=========================================================================== DirectorySubDir* DebugMenu::FindDirectoryItem( List<DirectoryItem*> &directory, const char* name ) { List<DirectoryItem*>::Iterator iter = directory.CreateIterator(); while ( iter.HasNext() ) { DirectoryItem* item = iter.Next(); if ( strcmp( item->GetName(), name ) == 0 ) { DirectorySubDir* subDirectoryItem = reinterpret_cast<DirectorySubDir*>( item ); if ( subDirectoryItem != NULL ) { return subDirectoryItem; } } } return NULL; } //=========================================================================== void DebugMenu::DeleteDirectory( List<DirectoryItem*>* directory ) { List<DirectoryItem*>::Iterator iter = directory->CreateIterator(); while ( iter.HasNext() ) { DirectoryItem* item = iter.Next(); if ( item->GetType() == SUB_DIRECTORY_TYPE ) { DirectorySubDir* subDirectoryItem = reinterpret_cast<DirectorySubDir*>( item ); DeleteDirectory( subDirectoryItem->GetDirectoryList() ); subDirectoryItem->GetDirectoryList()->Clear(); } DELETE_PTR( item ); } } //=========================================================================== bool SortFunction( DirectoryItem* item1, DirectoryItem* item2 ) { DirectoryType type1 = item1->GetType(); DirectoryType type2 = item2->GetType(); if ( type1 == VARIABLE_TYPE && type2 == SUB_DIRECTORY_TYPE ) { return false; } else if ( type2 == VARIABLE_TYPE && type1 == SUB_DIRECTORY_TYPE ) { return true; } else if ( type1 == type2 ) { if ( strcmp( item1->GetName(), item2->GetName() ) < 0 ) { return true; } else { return false; } } return false; } //=========================================================================== void DebugMenu::SortDirectory( List<DirectoryItem*>* directory ) { List<DirectoryItem*>::Iterator iter = directory->CreateIterator(); while ( iter.HasNext() ) { DirectoryItem* item = iter.Next(); if ( item->GetType() == SUB_DIRECTORY_TYPE ) { DirectorySubDir* subDirectoryItem = reinterpret_cast<DirectorySubDir*>( item ); SortDirectory( subDirectoryItem->GetDirectoryList() ); subDirectoryItem->GetDirectoryList()->Sort( SortFunction ); } } } //=========================================================================== DebugMenu::DebugMenu() { mFont = NEW_PTR( "Font" ) Font; mFont->LoadOther( "borisblackbloxx"); mFont->SetSize( 0.3f ); mCurrentItemIndex = 0; char* nextToken; DebugVariable* head = DebugVariable::GetReferenceList(); while ( head != NULL ) { char directoryPath[256]; System::StringCopy( directoryPath, 256, head->GetDirectory() ); char* directoryName; directoryName = System::StringToken( directoryPath, "/", &nextToken ); DirectorySubDir* currentDirectory = &mDirectory; while ( directoryName != NULL) { DirectorySubDir* directoryItem = FindDirectoryItem( *( currentDirectory->GetDirectoryList() ), directoryName ); if ( directoryItem == NULL ) { directoryItem = NEW_PTR( "Directory Item" ) DirectorySubDir; directoryItem->SetName( directoryName ); directoryItem->SetPreviousDirectoryItem( currentDirectory ); currentDirectory->GetDirectoryList()->InsertBack( directoryItem ); } currentDirectory = directoryItem; directoryName = System::StringToken( NULL, "/", &nextToken ); } DirectoryVariable* newItem = NEW_PTR( "Variable Item" ) DirectoryVariable; newItem->SetVariable( head ); newItem->SetName( head->GetName() ); currentDirectory->GetDirectoryList()->InsertBack( newItem ); head = head->GetNextVar(); } mStartItemIndex = 0; mEndItemIndex = NUM_DISPLAY_ITEMS; SortDirectory( mDirectory.GetDirectoryList() ); mDirectory.GetDirectoryList()->Sort( SortFunction ); mCurrentDirectoryItem = &mDirectory; } //=========================================================================== DebugMenu::~DebugMenu() { DELETE_PTR( mFont ); DeleteDirectory( mDirectory.GetDirectoryList() ); } } }
27.017204
116
0.576136
[ "render", "transform" ]
74c4034cfa09f4c3b70d693d8c21aa31284e57c1
1,556
cpp
C++
plugins/compositing_gl/src/InteractionRenderTarget.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
plugins/compositing_gl/src/InteractionRenderTarget.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
plugins/compositing_gl/src/InteractionRenderTarget.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
#include "InteractionRenderTarget.h" #include "compositing/CompositingCalls.h" megamol::compositing::InteractionRenderTarget::InteractionRenderTarget() : SimpleRenderTarget(), m_objId_render_target("ObjectId","Access the object id render target texture") { this->m_objId_render_target.SetCallback( CallTexture2D::ClassName(), "GetData", &InteractionRenderTarget::getObjectIdRenderTarget); this->m_objId_render_target.SetCallback( CallTexture2D::ClassName(), "GetMetaData", &InteractionRenderTarget::getMetaDataCallback); this->MakeSlotAvailable(&this->m_objId_render_target); } bool megamol::compositing::InteractionRenderTarget::create() { SimpleRenderTarget::create(); m_GBuffer->createColorAttachment(GL_R32I, GL_RED, GL_INT); // object ids m_GBuffer->createColorAttachment(GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT); // additional interaction information, e.g. clicked screen value return true; } bool megamol::compositing::InteractionRenderTarget::Render(core::view::CallRender3D_2& call) { SimpleRenderTarget::Render(call); GLint in[1] = {-1}; glClearBufferiv(GL_COLOR, 3, in); return true; } bool megamol::compositing::InteractionRenderTarget::getObjectIdRenderTarget(core::Call& caller) { auto ct = dynamic_cast<CallTexture2D*>(&caller); if (ct == NULL) return false; ct->setData(m_GBuffer->getColorAttachment(3), this->m_version); return true; } bool megamol::compositing::InteractionRenderTarget::getMetaDataCallback(core::Call& caller) { return true; }
33.826087
138
0.753213
[ "render", "object" ]
74c7cab754836dea2229d8875791c83b9b9ecc72
712
cc
C++
cpp/hackranker/h12.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/hackranker/h12.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/hackranker/h12.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
/* * https://www.hackerrank.com/challenges/flatland-space-stations/problem */ #include <iostream> #include <vector> #include <string> #include <algorithm> #include <iomanip> #include <cstdlib> #include <cstdio> #include <map> #include <set> #include <deque> #include <queue> using namespace std; int flatlandSpaceStations(int n, vector<int> c) { sort(c.begin(), c.end()); int mx = (c[0] - 1) >(n -1 - c[c.size() -1]) ? (c[0] -1): (n -1 - c[c.size() - 1]); for (int i = 1; i < c.size(); i++) { mx = mx > (c[i] - c[i - 1]) / 2 ? mx : (c[i] - c[i - 1]) / 2; } return mx; } //int main() { // vector<int> c = { 0, 1,2,3,4,5 }; // int k = flatlandSpaceStations(6, c); // cout << k << endl; // return 0; //}
22.25
84
0.570225
[ "vector" ]
74c96cada0f9ea353f1b01dff275c4e80aefd416
9,254
cc
C++
syntaxnet/syntaxnet/binary_segment_transitions_test.cc
GlibAI/models
47bd49001e1388dc566d3b067b8859a50fa8e2c0
[ "Apache-2.0" ]
308
2018-09-06T18:46:57.000Z
2022-03-28T08:22:45.000Z
models/syntaxnet/syntaxnet/binary_segment_transitions_test.cc
AMDS123/tensorflow-model-zoo.torch
6e4232352953f6a6a1fba4ce022cd8a462610215
[ "Apache-2.0" ]
64
2018-06-20T10:14:17.000Z
2021-09-08T05:58:25.000Z
models/syntaxnet/syntaxnet/binary_segment_transitions_test.cc
AMDS123/tensorflow-model-zoo.torch
6e4232352953f6a6a1fba4ce022cd8a462610215
[ "Apache-2.0" ]
69
2018-09-18T12:06:56.000Z
2022-03-14T11:49:16.000Z
/* Copyright 2016 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 "syntaxnet/binary_segment_state.h" #include "syntaxnet/parser_features.h" #include "syntaxnet/parser_state.h" #include "syntaxnet/parser_transitions.h" #include "syntaxnet/task_context.h" #include "syntaxnet/term_frequency_map.h" #include "syntaxnet/workspace.h" #include "tensorflow/core/platform/test.h" namespace syntaxnet { class SegmentationTransitionTest : public ::testing::Test { protected: void SetUp() override { transition_system_ = std::unique_ptr<ParserTransitionSystem>( ParserTransitionSystem::Create("binary-segment-transitions")); // Prepare a sentence. const char *str_sentence = "text: '因为 有 这样' " "token { word: '因' start: 0 end: 2 break_level: SPACE_BREAK } " "token { word: '为' start: 3 end: 5 break_level: NO_BREAK } " "token { word: ' ' start: 6 end: 6 break_level: SPACE_BREAK } " "token { word: '有' start: 7 end: 9 break_level: SPACE_BREAK } " "token { word: ' ' start: 10 end: 10 break_level: SPACE_BREAK } " "token { word: '这' start: 11 end: 13 break_level: SPACE_BREAK } " "token { word: '样' start: 14 end: 16 break_level: NO_BREAK } "; sentence_ = std::unique_ptr<Sentence>(new Sentence()); TextFormat::ParseFromString(str_sentence, sentence_.get()); word_map_.Increment("因为"); word_map_.Increment("因为"); word_map_.Increment("有"); word_map_.Increment("这"); word_map_.Increment("这"); word_map_.Increment("样"); word_map_.Increment("样"); word_map_.Increment("这样"); word_map_.Increment("这样"); string filename = tensorflow::strings::StrCat( tensorflow::testing::TmpDir(), "word-map"); word_map_.Save(filename); // Re-load in sorted order, ignore words that only occurs once. word_map_.Load(filename, 2, -1); // Prepare task context. context_ = std::unique_ptr<TaskContext>(new TaskContext()); AddInputToContext("word-map", filename, "text", ""); registry_ = std::unique_ptr<WorkspaceRegistry>( new WorkspaceRegistry()); } // Adds an input to the task context. void AddInputToContext(const string &name, const string &file_pattern, const string &file_format, const string &record_format) { TaskInput *input = context_->GetInput(name); TaskInput::Part *part = input->add_part(); part->set_file_pattern(file_pattern); part->set_file_format(file_format); part->set_record_format(record_format); } // Prepares a feature for computations. void PrepareFeature(const string &feature_name, ParserState *state) { feature_extractor_ = std::unique_ptr<ParserFeatureExtractor>( new ParserFeatureExtractor()); feature_extractor_->Parse(feature_name); feature_extractor_->Setup(context_.get()); feature_extractor_->Init(context_.get()); feature_extractor_->RequestWorkspaces(registry_.get()); workspace_.Reset(*registry_); feature_extractor_->Preprocess(&workspace_, state); } // Computes the feature value for the parser state. FeatureValue ComputeFeature(const ParserState &state) const { FeatureVector result; feature_extractor_->ExtractFeatures(workspace_, state, &result); return result.size() > 0 ? result.value(0) : -1; } void CheckStarts(const ParserState &state, const vector<int> &target) { ASSERT_EQ(state.StackSize(), target.size()); vector<int> starts; for (int i = 0; i < state.StackSize(); ++i) { EXPECT_EQ(state.Stack(i), target[i]); } } // The test sentence. std::unique_ptr<Sentence> sentence_; // Members for testing features. std::unique_ptr<ParserFeatureExtractor> feature_extractor_; std::unique_ptr<TaskContext> context_; std::unique_ptr<WorkspaceRegistry> registry_; WorkspaceSet workspace_; std::unique_ptr<ParserTransitionSystem> transition_system_; TermFrequencyMap label_map_; TermFrequencyMap word_map_; }; TEST_F(SegmentationTransitionTest, GoldNextActionTest) { BinarySegmentState *segment_state = static_cast<BinarySegmentState *>( transition_system_->NewTransitionState(true)); ParserState state(sentence_.get(), segment_state, &label_map_); // Do segmentation by following the gold actions. while (transition_system_->IsFinalState(state) == false) { ParserAction action = transition_system_->GetNextGoldAction(state); transition_system_->PerformActionWithoutHistory(action, &state); } // Test STARTs. CheckStarts(state, {5, 4, 3, 2, 0}); // Test the annotated tokens. segment_state->AddParseToDocument(state, false, sentence_.get()); ASSERT_EQ(sentence_->token_size(), 3); EXPECT_EQ(sentence_->token(0).word(), "因为"); EXPECT_EQ(sentence_->token(1).word(), "有"); EXPECT_EQ(sentence_->token(2).word(), "这样"); // Test start/end annotation of each token. EXPECT_EQ(sentence_->token(0).start(), 0); EXPECT_EQ(sentence_->token(0).end(), 5); EXPECT_EQ(sentence_->token(1).start(), 7); EXPECT_EQ(sentence_->token(1).end(), 9); EXPECT_EQ(sentence_->token(2).start(), 11); EXPECT_EQ(sentence_->token(2).end(), 16); } TEST_F(SegmentationTransitionTest, DefaultActionTest) { BinarySegmentState *segment_state = static_cast<BinarySegmentState *>( transition_system_->NewTransitionState(true)); ParserState state(sentence_.get(), segment_state, &label_map_); // Do segmentation, tagging and parsing by following the gold actions. while (transition_system_->IsFinalState(state) == false) { ParserAction action = transition_system_->GetDefaultAction(state); transition_system_->PerformActionWithoutHistory(action, &state); } // Every character should be START. CheckStarts(state, {6, 5, 4, 3, 2, 1, 0}); // Every non-space character should be a word. segment_state->AddParseToDocument(state, false, sentence_.get()); ASSERT_EQ(sentence_->token_size(), 5); EXPECT_EQ(sentence_->token(0).word(), "因"); EXPECT_EQ(sentence_->token(1).word(), "为"); EXPECT_EQ(sentence_->token(2).word(), "有"); EXPECT_EQ(sentence_->token(3).word(), "这"); EXPECT_EQ(sentence_->token(4).word(), "样"); } TEST_F(SegmentationTransitionTest, LastWordFeatureTest) { const int unk_id = word_map_.Size(); const int outside_id = unk_id + 1; // Prepare a parser state. BinarySegmentState *segment_state = new BinarySegmentState(); auto state = std::unique_ptr<ParserState>(new ParserState( sentence_.get(), segment_state, &label_map_)); // Test initial state which contains no words. PrepareFeature("last-word(1,min-freq=2)", state.get()); EXPECT_EQ(outside_id, ComputeFeature(*state)); PrepareFeature("last-word(2,min-freq=2)", state.get()); EXPECT_EQ(outside_id, ComputeFeature(*state)); PrepareFeature("last-word(3,min-freq=2)", state.get()); EXPECT_EQ(outside_id, ComputeFeature(*state)); // Test when the state contains only one start. segment_state->AddStart(0, state.get()); PrepareFeature("last-word(1,min-freq=2)", state.get()); EXPECT_EQ(outside_id, ComputeFeature(*state)); PrepareFeature("last-word(2,min-freq=2)", state.get()); EXPECT_EQ(outside_id, ComputeFeature(*state)); // Test when the state contains two starts, which forms a complete word and // the start of another new word. segment_state->AddStart(2, state.get()); EXPECT_NE(word_map_.LookupIndex("因为", unk_id), unk_id); PrepareFeature("last-word(1)", state.get()); EXPECT_EQ(word_map_.LookupIndex("因为", unk_id), ComputeFeature(*state)); // The last-word still points to outside. PrepareFeature("last-word(2,min-freq=2)", state.get()); EXPECT_EQ(outside_id, ComputeFeature(*state)); // Adding more starts that leads to the following words: // 因为 ‘ ’ 有 ‘ ’ segment_state->AddStart(3, state.get()); segment_state->AddStart(4, state.get()); // Note 有 is pruned from the map since its frequency is less than 2. EXPECT_EQ(word_map_.LookupIndex("有", unk_id), unk_id); PrepareFeature("last-word(1,min-freq=2)", state.get()); EXPECT_EQ(unk_id, ComputeFeature(*state)); // Note that last-word(2) points to ' ' which is also a unk. PrepareFeature("last-word(2,min-freq=2)", state.get()); EXPECT_EQ(unk_id, ComputeFeature(*state)); PrepareFeature("last-word(3,min-freq=2)", state.get()); EXPECT_EQ(word_map_.LookupIndex("因为", unk_id), ComputeFeature(*state)); // Adding two words: "这" and "样". segment_state->AddStart(5, state.get()); segment_state->AddStart(6, state.get()); PrepareFeature("last-word(1,min-freq=2)", state.get()); EXPECT_EQ(word_map_.LookupIndex("这", unk_id), ComputeFeature(*state)); } } // namespace syntaxnet
39.716738
80
0.702183
[ "vector" ]
74cb7dd3c16c70d754b8468d78bf783238223deb
9,938
cpp
C++
rmf_fleet_adapter/src/rmf_fleet_adapter/estimation.cpp
0to1/rmf_ros2
f5fb611c7d334e62f50b6988eb59fa275618d68b
[ "Apache-2.0" ]
1
2021-07-10T13:28:36.000Z
2021-07-10T13:28:36.000Z
rmf_fleet_adapter/src/rmf_fleet_adapter/estimation.cpp
0to1/rmf_ros2
f5fb611c7d334e62f50b6988eb59fa275618d68b
[ "Apache-2.0" ]
null
null
null
rmf_fleet_adapter/src/rmf_fleet_adapter/estimation.cpp
0to1/rmf_ros2
f5fb611c7d334e62f50b6988eb59fa275618d68b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "estimation.hpp" #include <rmf_traffic_ros2/Time.hpp> //============================================================================== void check_path_finish( rclcpp::Node* node, const rmf_fleet_msgs::msg::RobotState& state, TravelInfo& info) { // The robot believes it has reached the end of its path. const auto& wp = info.waypoints.back(); const auto& l = state.location; const Eigen::Vector2d p{l.x, l.y}; const double dist = (p - wp.position().block<2,1>(0, 0)).norm(); assert(wp.graph_index()); info.last_known_wp = *wp.graph_index(); assert(info.waypoints.size() >= 2); if (dist > 2.0) { RCLCPP_ERROR( node->get_logger(), "Robot named [%s] belonging to fleet [%s] is very far [%fm] from where " "it is supposed to be, but its remaining path is empty. This means the " "robot believes it is finished, but it is not where it's supposed to be.", info.robot_name.c_str(), info.fleet_name.c_str(), dist); estimate_state(node, state.location, info); return; } if (dist > 0.5) { RCLCPP_WARN( node->get_logger(), "The robot is somewhat far [%fm] from where it is supposed to be, " "but we will proceed anyway.", dist); const auto& last_wp = info.waypoints[info.waypoints.size()-2]; estimate_midlane_state( state.location, last_wp.graph_index(), info.waypoints.size()-1, info); } else { // We are close enough to the goal that we will say the robot is // currently located there. info.updater->update_position(*wp.graph_index(), l.yaw); } assert(info.path_finished_callback); info.path_finished_callback(); info.path_finished_callback = nullptr; info.next_arrival_estimator = nullptr; } //============================================================================== void estimate_path_traveling( rclcpp::Node* node, const rmf_fleet_msgs::msg::RobotState& state, TravelInfo& info) { assert(!state.path.empty()); const std::size_t remaining_count = state.path.size(); const std::size_t i_target_wp = info.waypoints.size() - remaining_count; info.target_plan_index = i_target_wp; const auto& target_wp = info.waypoints.at(i_target_wp); const auto& l = state.location; const auto& p = target_wp.position(); const auto interp = rmf_traffic::agv::Interpolate::positions( *info.traits, std::chrono::steady_clock::now(), {{l.x, l.y, l.yaw}, p}); const auto next_arrival = interp.back().time() - interp.front().time(); const auto now = rmf_traffic_ros2::convert(node->now()); if (target_wp.time() < now + next_arrival) { assert(info.next_arrival_estimator); // It seems the robot cannot arrive on time, so we report the earliest that // the robot can make it to its next target waypoint. info.next_arrival_estimator(i_target_wp, next_arrival); } else { assert(info.next_arrival_estimator); // It seems the robot will arrive on time, so we'll report that. info.next_arrival_estimator(i_target_wp, target_wp.time() - now); } rmf_utils::optional<std::size_t> lane_start; if (i_target_wp > 1) { lane_start = info.waypoints[i_target_wp-1].graph_index(); if (lane_start) info.last_known_wp = *lane_start; return estimate_midlane_state(l, lane_start, i_target_wp, info); } estimate_state(node, state.location, info); } //============================================================================== void estimate_midlane_state( const rmf_fleet_msgs::msg::Location& l, rmf_utils::optional<std::size_t> lane_start, const std::size_t next_index, TravelInfo& info) { assert(0 < next_index && next_index < info.waypoints.size()); const auto& target_wp = info.waypoints.at(next_index); if (!lane_start && info.last_known_wp) { // Let's see if the current position is reasonably between the last known // waypoint and the target waypoint. const auto& base_wp = info.graph->get_waypoint(*info.last_known_wp); const Eigen::Vector2d p0 = base_wp.get_location(); const Eigen::Vector2d p1 = target_wp.position().block<2,1>(0,0); const Eigen::Vector2d p_location{l.x, l.y}; const double lane_length = (p1 - p0).norm(); if (lane_length > 1e-8) { const Eigen::Vector2d pn = (p1 - p0) / lane_length; const Eigen::Vector2d p_l = p_location - p0; const double p_l_projection = p_l.dot(pn); const double lane_dist = (p_l - p_l_projection*pn).norm(); if (0.0 <= p_l_projection && p_l_projection <= lane_length && lane_dist < 2.0) { lane_start = *info.last_known_wp; } } } const std::size_t target_gi = [&]() -> std::size_t { // At least one future waypoint must have a graph index if (target_wp.graph_index()) return *target_wp.graph_index(); for (std::size_t i=next_index+1; i < info.waypoints.size(); ++i) { const auto gi = info.waypoints[i].graph_index(); if (gi) return *gi; } throw std::runtime_error( "CRITICAL ERROR: Remaining waypoint sequence has no graph indices"); }(); if (lane_start) { const auto last_gi = *lane_start; if (last_gi == target_gi) { // This implies that the robot is either waiting at or rotating on the // waypoint. info.updater->update_position(target_gi, l.yaw); } else if (const auto* forward_lane=info.graph->lane_from(last_gi, target_gi)) { // This implies that the robot is moving down a lane. std::vector<std::size_t> lanes; lanes.push_back(forward_lane->index()); if (const auto* reverse_lane = info.graph->lane_from(target_gi, last_gi)) { if (!reverse_lane->entry().event()) { // We don't allow the robot to turn back mid-lane if the reverse lane // has an entry event, because if that entry event is docking, then it // needs to be triggered for the robot to approach the exit. // // TODO(MXG): This restriction isn't needed for reversing on door or // lift events, so with some effort we could loosen this restriction // to only apply to docking. lanes.push_back(reverse_lane->index()); } } info.updater->update_position({l.x, l.y, l.yaw}, std::move(lanes)); } } // The target should always have a graph index, because only the first // waypoint in a command should ever be lacking a graph index. info.updater->update_position({l.x, l.y, l.yaw}, target_gi); } //============================================================================== void estimate_state( rclcpp::Node* node, const rmf_fleet_msgs::msg::Location& l, TravelInfo& info) { std::string last_known_map = l.level_name; if (info.last_known_wp) { const auto& last_known_wp = info.graph->get_waypoint(*info.last_known_wp); const Eigen::Vector2d p_last = last_known_wp.get_location(); const Eigen::Vector2d p{l.x, l.y}; const double dist = (p_last - p).norm(); if (dist < 0.25) { // We will assume that the robot is meant to be on this last known // waypoint. info.updater->update_position(last_known_wp.index(), l.yaw); return; } else if (dist < 1.5) { // We will assume that the robot is meant to be at this last known // waypoint, but is kind of diverged. info.updater->update_position({l.x, l.y, l.yaw}, last_known_wp.index()); return; } if (last_known_map.empty()) last_known_map = last_known_wp.get_map_name(); } if (last_known_map.empty() && l.level_name.empty()) { RCLCPP_ERROR( node->get_logger(), "Robot named [%s] belonging to fleet [%s] is lost because we cannot " "figure out what floor it is on. Please publish the robot's current " "floor name in the level_name field of its RobotState.", info.robot_name.c_str(), info.fleet_name.c_str()); return; } info.updater->update_position(last_known_map, {l.x, l.y, l.yaw}); } //============================================================================== void estimate_waypoint( rclcpp::Node* node, const rmf_fleet_msgs::msg::Location& l, TravelInfo& info) { std::string last_known_map = l.level_name; if (last_known_map.empty() && info.last_known_wp) { last_known_map = info.graph->get_waypoint(*info.last_known_wp) .get_map_name(); } const Eigen::Vector2d p(l.x, l.y); const rmf_traffic::agv::Graph::Waypoint* closest_wp = nullptr; double nearest_dist = std::numeric_limits<double>::infinity(); for (std::size_t i=0; i < info.graph->num_waypoints(); ++i) { const auto& wp = info.graph->get_waypoint(i); const Eigen::Vector2d p_wp = wp.get_location(); const double dist = (p - p_wp).norm(); if (dist < nearest_dist) { closest_wp = &wp; nearest_dist = dist; } } assert(closest_wp); if (nearest_dist > 0.5) { RCLCPP_WARN( node->get_logger(), "Robot named [%s] belonging to fleet [%s] is expected to be on a " "waypoint, but the nearest waypoint is [%fm] away.", info.robot_name.c_str(), info.fleet_name.c_str(), nearest_dist); } info.updater->update_position(closest_wp->index(), l.yaw); }
33.126667
80
0.631918
[ "vector" ]
74cb9b4e5a2f6052cc2772c38e086c1204bfc3ea
5,962
hpp
C++
Accolade/src/Managers/MemoryManager.hpp
Tackwin/BossRoom
ecad5853e591b9edc54e75448547e20e14964f72
[ "MIT" ]
null
null
null
Accolade/src/Managers/MemoryManager.hpp
Tackwin/BossRoom
ecad5853e591b9edc54e75448547e20e14964f72
[ "MIT" ]
null
null
null
Accolade/src/Managers/MemoryManager.hpp
Tackwin/BossRoom
ecad5853e591b9edc54e75448547e20e14964f72
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cstdint> #include <utility> #include <utility> #include <vector> #include <memory> #include <cmath> // trying the singleton thing // and snake_case sssssssss class MemoryManager { using u08 = std::uint8_t; struct mem_place { u08* location; std::size_t size; }; public: template<typename T> using unique_ptr = std::unique_ptr<T>; template<typename T> struct Allocator { using value_type = T; Allocator() = default; template<class U> constexpr Allocator(const Allocator<U>&) noexcept {} T& operator*() const { return *_t; }; T& operator*() { return *_t; }; T* operator->() const { return _t.get(); } T* operator->() { return _t.get(); } T* allocate(std::size_t n) { return MM::allocate(n) } void deallocate(T* p, std::size_t n) { MM::deallocate(p, n); } }; static MemoryManager& I(); /* template<typename T, class... Args> static std::shared_ptr<T> make_shared(Args&&... args) { return std::shared_ptr<T>(std::forward<Args>(args)...); const auto& ptr = MemoryManager::I().construct<T>(std::forward<Args>(args)...); return std::shared_ptr<T>( ptr, std::bind( &MemoryManager::deallocate<T>, &MemoryManager::I(), std::placeholders::_1, sizeof(T) ) ); } template<typename T> static std::shared_ptr<T> make_sshared(T* ptr) { return std::shared_ptr<T>(ptr); return std::shared_ptr<T>( ptr, std::bind( &MemoryManager::deallocate<T>, &MemoryManager::I(), std::placeholders::_1, sizeof(T) ) ); } template<typename T> static unique_ptr<T> make_unisque(T* ptr) { return std::unique_ptr<T>(ptr); //return unique_ptr<T>(ptr, [](T* ptr) {MemoryManager::I().deallocate(ptr); }); } template<typename T, class... Args> static unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(std::forward<Args>(args)...); T* ptr = MemoryManager::I().construct<T>(std::forward<Args>(args)...); return unique_ptr<T>( ptr, [](T* ptr) { MemoryManager::I().deallocate(ptr); } ); } template<typename T, typename U> static unique_ptr<T> cast_unique(U* ptr) { return unique_ptr<T>( static_cast<T*>(ptr), [](T* ptr) { MemoryManager::I().deallocate(ptr); } ); }*/ size_t get_buffer_size() const; size_t get_free_size() const; void initialize_buffer(size_t size); template<typename T> T* allocate(std::size_t n) { //testing if the memory place is big enough to hold T for (size_t i = 0u; i < _free_memory.size(); ++i) { mem_place free_place = _free_memory[i]; mem_place free_place_aligned = _free_memory[i]; void* free_place_aligned_location = (void*)free_place_aligned.location; if (!std::align( alignof(T), sizeof(T) * n, free_place_aligned_location, free_place_aligned.size )) // if we can't properly align the memory place it's no use continue; free_place_aligned.location = (u08*)free_place_aligned_location; // if it's big enough to hold T then let's use it ! if (free_place.size >= sizeof(T) * n) { //if the aligned ptr is not the normal one, then there's // a new memory place at the begining if (free_place.location != free_place_aligned.location) { _free_memory.push_back({ free_place.location, (std::size_t) ((u08*)free_place_aligned_location - free_place.location) }); } // so if it isn't _exactly_ the size there's a new place // at the end if (free_place.size != sizeof(T) * n) _free_memory.push_back({ free_place.location + sizeof(T) * n, free_place.size - sizeof(T) * n }); // we delete the memory place that we use _free_memory.erase(_free_memory.begin() + i); std::sort( _free_memory.begin(), _free_memory.end(), [](const mem_place& A, const mem_place& B) -> bool { return A.location < B.location; } ); return reinterpret_cast<T*>(free_place.location); } } throw std::runtime_error("Not enough place"); } template<typename T, class... Args> T* construct(Args&&... args) { return new(allocate<T>(1)) T(std::forward<Args>(args)...); } template<typename T> void deallocate(T* ptr, size_t size = 1) { ptr->~T(); bool flag = true; // We will create a new memory_place, i'll go through the loop // to merge all consecutive memory_place for (size_t i = 0u; i < _free_memory.size() && flag; ++i) { mem_place free_place = _free_memory[i]; // if the memory place is just succeding another, we merge them if (free_place.location + free_place.size == (u08*)ptr) { _free_memory[i].size += sizeof(T) * size; // maybe with that bigger size, the next mem_place touch me if (i + 1 < _free_memory.size()) { if ( _free_memory[i + 1].location == free_place.location + free_place.size ) { // if that''s the case, i need to grow even more _free_memory[i].size += _free_memory[i + 1].size; _free_memory.erase(std::begin(_free_memory) + i + 1); } } flag = false; } // if the memory place is just preceding another, we merge them if ( (std::size_t)free_place.location > sizeof(T) * size && free_place.location - sizeof(T) * size == (u08*)ptr ) { _free_memory[i].location -= sizeof(T) * size; _free_memory[i].size += sizeof(T) * size; flag = false; } } if (flag) { // else we just push a new memory place _free_memory.push_back({ (u08*)ptr, sizeof(T) * size }); } std::sort( _free_memory.begin(), _free_memory.end(), [](const mem_place& A, const mem_place& B) -> bool { return A.location < B.location; } ); } private: MemoryManager(); ~MemoryManager(); MemoryManager(const MemoryManager&) = delete; MemoryManager& operator=(const MemoryManager&) = delete; size_t _main_size = 0u; u08* _main_buffer = nullptr; std::vector<mem_place> _free_memory; }; // Optional using MM = MemoryManager;
23.848
81
0.639215
[ "vector" ]
74cbdcb2e458420883207277fef5bd52e9940473
1,722
cpp
C++
intelligent_camera/Mesh.cpp
Blubmin/intelligent_camera
0e9bf122f0f98681e4b5cdfb3ae6fa53ee5b7ce2
[ "Apache-2.0" ]
null
null
null
intelligent_camera/Mesh.cpp
Blubmin/intelligent_camera
0e9bf122f0f98681e4b5cdfb3ae6fa53ee5b7ce2
[ "Apache-2.0" ]
null
null
null
intelligent_camera/Mesh.cpp
Blubmin/intelligent_camera
0e9bf122f0f98681e4b5cdfb3ae6fa53ee5b7ce2
[ "Apache-2.0" ]
null
null
null
#include "Mesh.h" #include <climits> using namespace glm; using namespace std; Mesh::Mesh() { } Mesh::Mesh(const aiMesh* mesh) { this->verts = vector<vec3>(); for (int i = 0; i < mesh->mNumVertices; i++) { aiVector3D pos = mesh->mVertices[i]; this->verts.push_back(vec3(pos.x, pos.y, pos.z)); aiVector3D norm = mesh->mNormals[i]; this->norms.push_back(vec3(norm.x, norm.y, norm.z)); } for (int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; assert(face.mNumIndices == 3); for (int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } assert(indices.size() == mesh->mNumFaces * 3); materialIdx = mesh->mMaterialIndex; } Mesh::~Mesh() { } void Mesh::bindBuffers() { glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(1, &VBO_VERT); glBindBuffer(GL_ARRAY_BUFFER, VBO_VERT); glBufferData(GL_ARRAY_BUFFER, verts.size()*sizeof(vec3), verts.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glGenBuffers(1, &VBO_NORM); glBindBuffer(GL_ARRAY_BUFFER, VBO_NORM); glBufferData(GL_ARRAY_BUFFER, norms.size()*sizeof(vec3), norms.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glGenBuffers(1, &IND); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IND); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size()*sizeof(GLuint), indices.data(), GL_STATIC_DRAW); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); }
25.701493
71
0.645761
[ "mesh", "vector" ]
74ce77593db4e1ec3c04cdd8b12bf3fc2129b844
816
cc
C++
src/small-screen-lib/Init.cc
dananderson/small-screen
b85b2e36b27147b23cb7c1454109f23d32ffde4d
[ "MIT" ]
null
null
null
src/small-screen-lib/Init.cc
dananderson/small-screen
b85b2e36b27147b23cb7c1454109f23d32ffde4d
[ "MIT" ]
3
2020-09-04T19:53:40.000Z
2021-05-08T04:34:07.000Z
src/small-screen-lib/Init.cc
dananderson/small-screen
b85b2e36b27147b23cb7c1454109f23d32ffde4d
[ "MIT" ]
null
null
null
/* * Copyright (C) 2019 Daniel Anderson * * This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ #include <napi.h> #include <YogaValue.h> #include <YogaNode.h> #include <YogaGlobal.h> #include "TextLayout.h" #include "CapInsets.h" #include "Global.h" #include "StbFont.h" #include "StbFontSample.h" using namespace Napi; Object Init(Env env, Object exports) { TextLayout::Init(env, exports); CapInsets::Init(env, exports); StbFont::Init(env); StbFontSample::Init(env); Global::Init(env, exports); auto yoga = Object::New(env); exports["Yoga"] = yoga; Yoga::Value::Init(env, yoga); Yoga::Node::Init(env, yoga); Yoga::Init(env, yoga); return exports; } NODE_API_MODULE(SmallScreenLib, Init);
21.473684
122
0.681373
[ "object" ]