text
stringlengths
54
60.6k
<commit_before>/* Copyright (C) 2003 Justin Karneges Copyright (C) 2005 Brad Hards 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 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 <QtCrypto> #include <iostream> int main(int argc, char **argv) { // The Initializer object sets things up, and also // does cleanup when it goes out of scope QCA::Initializer init; QCoreApplication app(argc, argv); // we use the first argument if provided, or // use "hello" if no arguments QSecureArray arg = (argc >= 2) ? argv[1] : "hello"; // We demonstrate PEM usage here, so we need to test for // supportedIOTypes, not just supportedTypes if(!QCA::isSupported("pkey") || !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA)) printf("RSA not supported!\n"); else { // When creating a public / private key pair, you make the // private key, and then extract the public key component from it // Using RSA is very common, however DSA can provide equivalent // signature/verification. This example applies to DSA to the // extent that the operations work on that key type. // QCA provides KeyGenerator as a convenient source of new keys, // however you could also import an existing key instead. QCA::PrivateKey seckey = QCA::KeyGenerator().createRSA(1024); if(seckey.isNull()) { std::cout << "Failed to make private RSA key" << std::endl; return 1; } QCA::PublicKey pubkey = seckey.toPublicKey(); // check if the key can encrypt if(!pubkey.canEncrypt()) { std::cout << "Error: this kind of key cannot encrypt" << std::endl; return 1; } // encrypt some data - note that only the public key is required // you must also choose the algorithm to be used QSecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP); if(result.isEmpty()) { std::cout << "Error encrypting" << std::endl; return 1; } // output the encrypted data QString rstr = QCA::arrayToHex(result); std::cout << "\"" << arg.data() << "\" encrypted with RSA is \""; std::cout << qPrintable(rstr) << "\"" << std::endl; // save the private key - in a real example, make sure this goes // somewhere secure and has a good pass phrase // You can use the same technique with the public key too. QSecureArray passPhrase = "pass phrase"; seckey.toPEMFile("keyprivate.pem", passPhrase); // Read that key back in, checking if the read succeeded QCA::ConvertResult conversionResult; QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEMFile( "keyprivate.pem", passPhrase, &conversionResult); if (! QCA::ConvertGood == conversionResult) { std::cout << "Private key read failed" << std::endl; } // now decrypt that encrypted data using the private key that // we read in. The algorithm is the same. QSecureArray decrypt; if(0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) { printf("Error decrypting.\n"); return 1; } // output the resulting decrypted string std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \""; std::cout << decrypt.data() << "\"" << std::endl; // Some private keys can also be used for producing signatures if(!privateKey.canSign()) { std::cout << "Error: this kind of key cannot sign" << std::endl; return 1; } privateKey.startSign( QCA::EMSA3_MD5 ); privateKey.update( arg ); // just reuse the same message QSecureArray argSig = privateKey.signature(); // instead of using the startSign(), update(), signature() calls, // you may be better doing the whole thing in one go, using the // signMessage call. Of course you need the whole message in one // hit, which may or may not be a problem // output the resulting signature rstr = QCA::arrayToHex(argSig); std::cout << "Signature for \"" << arg.data() << "\" using RSA, is "; std::cout << "\"" << qPrintable( rstr ) << "\"" << std::endl; // to check a signature, we can if(pubkey.canVerify()) { pubkey.startVerify( QCA::EMSA3_MD5 ); pubkey.update( arg ); if ( pubkey.validSignature( argSig ) ) { std::cout << "Signature is valid" << std::endl; } else { std::cout << "Bad signature" << std::endl; } } // We can also do the verification in a single step if we // have all the message if ( pubkey.canVerify() && pubkey.verifyMessage( arg, argSig, QCA::EMSA3_MD5 ) ) { std::cout << "Signature is valid" << std::endl; } else { std::cout << "Signature could not be verified" << std::endl; } } return 0; } <commit_msg>Finish off the comment. Not sure what I was going to say...<commit_after>/* Copyright (C) 2003 Justin Karneges Copyright (C) 2005 Brad Hards 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 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 <QtCrypto> #include <iostream> int main(int argc, char **argv) { // The Initializer object sets things up, and also // does cleanup when it goes out of scope QCA::Initializer init; QCoreApplication app(argc, argv); // we use the first argument if provided, or // use "hello" if no arguments QSecureArray arg = (argc >= 2) ? argv[1] : "hello"; // We demonstrate PEM usage here, so we need to test for // supportedIOTypes, not just supportedTypes if(!QCA::isSupported("pkey") || !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA)) printf("RSA not supported!\n"); else { // When creating a public / private key pair, you make the // private key, and then extract the public key component from it // Using RSA is very common, however DSA can provide equivalent // signature/verification. This example applies to DSA to the // extent that the operations work on that key type. // QCA provides KeyGenerator as a convenient source of new keys, // however you could also import an existing key instead. QCA::PrivateKey seckey = QCA::KeyGenerator().createRSA(1024); if(seckey.isNull()) { std::cout << "Failed to make private RSA key" << std::endl; return 1; } QCA::PublicKey pubkey = seckey.toPublicKey(); // check if the key can encrypt if(!pubkey.canEncrypt()) { std::cout << "Error: this kind of key cannot encrypt" << std::endl; return 1; } // encrypt some data - note that only the public key is required // you must also choose the algorithm to be used QSecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP); if(result.isEmpty()) { std::cout << "Error encrypting" << std::endl; return 1; } // output the encrypted data QString rstr = QCA::arrayToHex(result); std::cout << "\"" << arg.data() << "\" encrypted with RSA is \""; std::cout << qPrintable(rstr) << "\"" << std::endl; // save the private key - in a real example, make sure this goes // somewhere secure and has a good pass phrase // You can use the same technique with the public key too. QSecureArray passPhrase = "pass phrase"; seckey.toPEMFile("keyprivate.pem", passPhrase); // Read that key back in, checking if the read succeeded QCA::ConvertResult conversionResult; QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEMFile( "keyprivate.pem", passPhrase, &conversionResult); if (! QCA::ConvertGood == conversionResult) { std::cout << "Private key read failed" << std::endl; } // now decrypt that encrypted data using the private key that // we read in. The algorithm is the same. QSecureArray decrypt; if(0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) { printf("Error decrypting.\n"); return 1; } // output the resulting decrypted string std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \""; std::cout << decrypt.data() << "\"" << std::endl; // Some private keys can also be used for producing signatures if(!privateKey.canSign()) { std::cout << "Error: this kind of key cannot sign" << std::endl; return 1; } privateKey.startSign( QCA::EMSA3_MD5 ); privateKey.update( arg ); // just reuse the same message QSecureArray argSig = privateKey.signature(); // instead of using the startSign(), update(), signature() calls, // you may be better doing the whole thing in one go, using the // signMessage call. Of course you need the whole message in one // hit, which may or may not be a problem // output the resulting signature rstr = QCA::arrayToHex(argSig); std::cout << "Signature for \"" << arg.data() << "\" using RSA, is "; std::cout << "\"" << qPrintable( rstr ) << "\"" << std::endl; // to check a signature, we must check that the key is // appropriate if(pubkey.canVerify()) { pubkey.startVerify( QCA::EMSA3_MD5 ); pubkey.update( arg ); if ( pubkey.validSignature( argSig ) ) { std::cout << "Signature is valid" << std::endl; } else { std::cout << "Bad signature" << std::endl; } } // We can also do the verification in a single step if we // have all the message if ( pubkey.canVerify() && pubkey.verifyMessage( arg, argSig, QCA::EMSA3_MD5 ) ) { std::cout << "Signature is valid" << std::endl; } else { std::cout << "Signature could not be verified" << std::endl; } } return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/obstacle/onboard/fusion_subnode.h" #include <unordered_map> #include "modules/common/adapters/adapter_manager.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/log.h" #include "modules/perception/common/perception_gflags.h" #include "modules/perception/onboard/event_manager.h" #include "modules/perception/onboard/shared_data_manager.h" #include "modules/perception/onboard/subnode_helper.h" namespace apollo { namespace perception { using apollo::canbus::Chassis; using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::adapter::AdapterManager; bool FusionSubnode::InitInternal() { RegistAllAlgorithm(); AdapterManager::Init(FLAGS_perception_adapter_config_filename); CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized."; AdapterManager::AddChassisCallback(&FusionSubnode::OnChassis, this); CHECK(shared_data_manager_ != nullptr); fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion)); if (fusion_ == nullptr) { AERROR << "Failed to get fusion instance: " << FLAGS_onboard_fusion; return false; } if (!fusion_->Init()) { AERROR << "Failed to init fusion:" << FLAGS_onboard_fusion; return false; } radar_object_data_ = dynamic_cast<RadarObjectData *>( shared_data_manager_->GetSharedData("RadarObjectData")); if (radar_object_data_ == nullptr) { AWARN << "Failed to get RadarObjectData."; } lidar_object_data_ = dynamic_cast<LidarObjectData *>( shared_data_manager_->GetSharedData("LidarObjectData")); if (lidar_object_data_ == nullptr) { AWARN << "Failed to get LidarObjectData."; } camera_object_data_ = dynamic_cast<CameraObjectData *>( shared_data_manager_->GetSharedData("CameraObjectData")); if (camera_object_data_ == nullptr) { AWARN << "Failed to get CameraObjectData."; } fusion_data_ = dynamic_cast<FusionSharedData *>( shared_data_manager_->GetSharedData("FusionSharedData")); if (fusion_data_ == nullptr) { AWARN << "Failed to get FusionSharedData."; } lane_shared_data_ = dynamic_cast<LaneSharedData *>( shared_data_manager_->GetSharedData("LaneSharedData")); if (lane_shared_data_ == nullptr) { AERROR << "failed to get shared data instance: LaneSharedData "; return false; } lane_objects_.reset(new LaneObjects()); if (!InitOutputStream()) { AERROR << "Failed to init output stream."; return false; } AINFO << "Init FusionSubnode succ. Using fusion:" << fusion_->name(); return true; } bool FusionSubnode::InitOutputStream() { // expect reserve_ format: // pub_driven_event_id:n // lidar_output_stream : event_id=n&sink_type=m&sink_name=x // radar_output_stream : event_id=n&sink_type=m&sink_name=x std::unordered_map<std::string, std::string> reserve_field_map; if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) { AERROR << "Failed to parse reserve string: " << reserve_; return false; } auto iter = reserve_field_map.find("pub_driven_event_id"); if (iter == reserve_field_map.end()) { AERROR << "Failed to find pub_driven_event_id:" << reserve_; return false; } pub_driven_event_id_ = static_cast<EventID>(atoi((iter->second).c_str())); auto lidar_iter = reserve_field_map.find("lidar_event_id"); if (lidar_iter == reserve_field_map.end()) { AWARN << "Failed to find lidar_event_id:" << reserve_; AINFO << "lidar_event_id will be set -1"; lidar_event_id_ = -1; } else { lidar_event_id_ = static_cast<EventID>(atoi((lidar_iter->second).c_str())); } auto radar_iter = reserve_field_map.find("radar_event_id"); if (radar_iter == reserve_field_map.end()) { AWARN << "Failed to find radar_event_id:" << reserve_; AINFO << "radar_event_id will be set -1"; radar_event_id_ = -1; } else { radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str())); } auto camera_iter = reserve_field_map.find("camera_event_id"); if (camera_iter == reserve_field_map.end()) { AWARN << "Failed to find camera_event_id:" << reserve_; AINFO << "camera_event_id will be set -1"; camera_event_id_ = -1; } else { camera_event_id_ = static_cast<EventID>(atoi((camera_iter->second).c_str())); } auto lane_iter = reserve_field_map.find("lane_event_id"); if (lane_iter == reserve_field_map.end()) { AWARN << "Failed to find camera_event_id:" << reserve_; AINFO << "camera_event_id will be set -1"; lane_event_id_ = -1; } else { lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str())); } return true; } Status FusionSubnode::ProcEvents() { for (auto event_meta : sub_meta_events_) { // ignore lane event from polling if (event_meta.event_id == lane_event_id_) continue; std::vector<Event> events; if (!SubscribeEvents(event_meta, &events)) { AERROR << "event meta id:" << event_meta.event_id << " " << event_meta.from_node << " " << event_meta.to_node; return Status(ErrorCode::PERCEPTION_ERROR, "Subscribe event fail."); } if (events.empty()) { usleep(500); continue; } Process(event_meta, events); if (event_meta.event_id != pub_driven_event_id_) { ADEBUG << "Not pub_driven_event_id, skip to publish." << " event_id:" << event_meta.event_id << " fused_obj_cnt:" << objects_.size(); continue; } // public obstacle message PerceptionObstacles obstacles; if (GeneratePbMsg(&obstacles)) { common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles); } AINFO << "Publish 3d perception fused msg. timestamp:" << GLOG_TIMESTAMP(timestamp_) << " obj_cnt:" << objects_.size(); } return Status::OK(); } Status FusionSubnode::Process(const EventMeta &event_meta, const std::vector<Event> &events) { std::vector<SensorObjects> sensor_objs; if (!BuildSensorObjs(events, &sensor_objs)) { AERROR << "Failed to build_sensor_objs"; error_code_ = common::PERCEPTION_ERROR_PROCESS; return Status(ErrorCode::PERCEPTION_ERROR, "Failed to build_sensor_objs."); } PERF_BLOCK_START(); objects_.clear(); if (!fusion_->Fuse(sensor_objs, &objects_)) { AWARN << "Failed to call fusion plugin." << " event_meta: [" << event_meta.to_string() << "] event_cnt:" << events.size() << " event_0: [" << events[0].to_string() << "]"; error_code_ = common::PERCEPTION_ERROR_PROCESS; return Status(ErrorCode::PERCEPTION_ERROR, "Failed to call fusion plugin."); } if (event_meta.event_id == lidar_event_id_) { PERF_BLOCK_END("fusion_lidar"); } else if (event_meta.event_id == radar_event_id_) { PERF_BLOCK_END("fusion_radar"); } else if (event_meta.event_id == camera_event_id_) { PERF_BLOCK_END("fusion_camera"); } if (objects_.size() > 0 && FLAGS_publish_fusion_event) { SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem); fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time; const std::string &device_id = events[0].reserve; for (auto obj : objects_) { ObjectPtr objclone(new Object()); objclone->clone(*obj); fusion_item_ptr->obstacles.push_back(objclone); } AINFO << "publishing event for timestamp deviceid and size of fusion object" << fusion_item_ptr->timestamp << " " << device_id << " " << fusion_item_ptr->obstacles.size(); PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr); } timestamp_ = sensor_objs[0].timestamp; error_code_ = common::OK; return Status::OK(); } void FusionSubnode::PublishDataAndEvent(const double &timestamp, const std::string &device_id, const SharedDataPtr<FusionItem> &data) { CommonSharedDataKey key(timestamp, device_id); bool fusion_succ = fusion_data_->Add(key, data); if (!fusion_succ) { AERROR << "fusion shared data addkey failure"; } AINFO << "adding key in fusion shared data " << key.ToString(); for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) { const EventMeta &event_meta = pub_meta_events_[idx]; Event event; event.event_id = event_meta.event_id; event.timestamp = timestamp; event.reserve = device_id; event_manager_->Publish(event); } } bool FusionSubnode::SubscribeEvents(const EventMeta &event_meta, std::vector<Event> *events) const { Event event; // no blocking while (event_manager_->Subscribe(event_meta.event_id, &event, true)) { events->push_back(event); } return true; } bool FusionSubnode::BuildSensorObjs( const std::vector<Event> &events, std::vector<SensorObjects> *multi_sensor_objs) { PERF_FUNCTION(); for (auto event : events) { std::shared_ptr<SensorObjects> sensor_objects; if (!GetSharedData(event, &sensor_objects)) { return false; } // Make sure timestamp and type are filled. sensor_objects->timestamp = event.timestamp; if (event.event_id == lidar_event_id_) { sensor_objects->sensor_type = SensorType::VELODYNE_64; } else if (event.event_id == radar_event_id_) { sensor_objects->sensor_type = SensorType::RADAR; } else if (event.event_id == camera_event_id_) { sensor_objects->sensor_type = SensorType::CAMERA; } else { AERROR << "Event id is not supported. event:" << event.to_string(); return false; } sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type); multi_sensor_objs->push_back(*sensor_objects); ADEBUG << "get sensor objs:" << sensor_objects->ToString(); } return true; } bool FusionSubnode::GetSharedData(const Event &event, std::shared_ptr<SensorObjects> *objs) { double timestamp = event.timestamp; const std::string &device_id = event.reserve; std::string data_key; if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) { AERROR << "Failed to produce shared data key. EventID:" << event.event_id << " timestamp:" << timestamp << " device_id:" << device_id; return false; } bool get_data_succ = false; if (event.event_id == lidar_event_id_ && lidar_object_data_ != nullptr) { get_data_succ = lidar_object_data_->Get(data_key, objs); } else if (event.event_id == radar_event_id_ && radar_object_data_ != nullptr) { get_data_succ = radar_object_data_->Get(data_key, objs); } else if (event.event_id == camera_event_id_ && camera_object_data_ != nullptr) { get_data_succ = camera_object_data_->Get(data_key, objs); // trying to get lane shared data as well Event lane_event; if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) { get_data_succ = lane_shared_data_->Get(data_key, &lane_objects_); ADEBUG << "getting lane data successfully for data key " << data_key; } } else { AERROR << "Event id is not supported. event:" << event.to_string(); return false; } if (!get_data_succ) { AERROR << "Failed to get shared data. event:" << event.to_string(); return false; } return true; } bool FusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) { common::adapter::AdapterManager::FillPerceptionObstaclesHeader( FLAGS_obstacle_module_name, obstacles); common::Header *header = obstacles->mutable_header(); if (pub_driven_event_id_ == lidar_event_id_) { header->set_lidar_timestamp(timestamp_ * 1e9); // in ns header->set_camera_timestamp(0); header->set_radar_timestamp(0); } else if (pub_driven_event_id_ == camera_event_id_) { header->set_lidar_timestamp(0); // in ns header->set_camera_timestamp(timestamp_ * 1e9); header->set_radar_timestamp(0); } obstacles->set_error_code(error_code_); for (const auto &obj : objects_) { PerceptionObstacle *obstacle = obstacles->add_perception_obstacle(); obj->Serialize(obstacle); } if (FLAGS_use_navigation_mode) { // generate lane marker protobuf messages LaneMarkers *lane_markers = obstacles->mutable_lane_marker(); LaneObjectsToLaneMarkerProto(*(lane_objects_), lane_markers); // Relative speed of objects + latest ego car speed in X for (auto obstacle : obstacles->perception_obstacle()) { obstacle.mutable_velocity()->set_x(obstacle.velocity().x() + chassis_speed_mps_); } } ADEBUG << "PerceptionObstacles: " << obstacles->ShortDebugString(); return true; } void FusionSubnode::RegistAllAlgorithm() { RegisterFactoryProbabilisticFusion(); RegisterFactoryAsyncFusion(); } void FusionSubnode::OnChassis(const Chassis &chassis) { ADEBUG << "Received chassis data: run chassis callback."; chassis_.CopyFrom(chassis); chassis_speed_mps_ = chassis_.speed_mps(); } } // namespace perception } // namespace apollo <commit_msg>fix fusion_subnode init failure (#3656)<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/obstacle/onboard/fusion_subnode.h" #include <unordered_map> #include "modules/common/adapters/adapter_manager.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/log.h" #include "modules/perception/common/perception_gflags.h" #include "modules/perception/onboard/event_manager.h" #include "modules/perception/onboard/shared_data_manager.h" #include "modules/perception/onboard/subnode_helper.h" namespace apollo { namespace perception { using apollo::canbus::Chassis; using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::adapter::AdapterManager; bool FusionSubnode::InitInternal() { RegistAllAlgorithm(); AdapterManager::Init(FLAGS_perception_adapter_config_filename); CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized."; AdapterManager::AddChassisCallback(&FusionSubnode::OnChassis, this); CHECK(shared_data_manager_ != nullptr); fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion)); if (fusion_ == nullptr) { AERROR << "Failed to get fusion instance: " << FLAGS_onboard_fusion; return false; } if (!fusion_->Init()) { AERROR << "Failed to init fusion:" << FLAGS_onboard_fusion; return false; } radar_object_data_ = dynamic_cast<RadarObjectData *>( shared_data_manager_->GetSharedData("RadarObjectData")); if (radar_object_data_ == nullptr) { AWARN << "Failed to get RadarObjectData."; } lidar_object_data_ = dynamic_cast<LidarObjectData *>( shared_data_manager_->GetSharedData("LidarObjectData")); if (lidar_object_data_ == nullptr) { AWARN << "Failed to get LidarObjectData."; } camera_object_data_ = dynamic_cast<CameraObjectData *>( shared_data_manager_->GetSharedData("CameraObjectData")); if (camera_object_data_ == nullptr) { AWARN << "Failed to get CameraObjectData."; } fusion_data_ = dynamic_cast<FusionSharedData *>( shared_data_manager_->GetSharedData("FusionSharedData")); if (fusion_data_ == nullptr) { AWARN << "Failed to get FusionSharedData."; } lane_shared_data_ = dynamic_cast<LaneSharedData *>( shared_data_manager_->GetSharedData("LaneSharedData")); if (lane_shared_data_ == nullptr) { AWARN << "failed to get shared data instance: LaneSharedData "; } lane_objects_.reset(new LaneObjects()); if (!InitOutputStream()) { AERROR << "Failed to init output stream."; return false; } AINFO << "Init FusionSubnode succ. Using fusion:" << fusion_->name(); return true; } bool FusionSubnode::InitOutputStream() { // expect reserve_ format: // pub_driven_event_id:n // lidar_output_stream : event_id=n&sink_type=m&sink_name=x // radar_output_stream : event_id=n&sink_type=m&sink_name=x std::unordered_map<std::string, std::string> reserve_field_map; if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) { AERROR << "Failed to parse reserve string: " << reserve_; return false; } auto iter = reserve_field_map.find("pub_driven_event_id"); if (iter == reserve_field_map.end()) { AERROR << "Failed to find pub_driven_event_id:" << reserve_; return false; } pub_driven_event_id_ = static_cast<EventID>(atoi((iter->second).c_str())); auto lidar_iter = reserve_field_map.find("lidar_event_id"); if (lidar_iter == reserve_field_map.end()) { AWARN << "Failed to find lidar_event_id:" << reserve_; AINFO << "lidar_event_id will be set -1"; lidar_event_id_ = -1; } else { lidar_event_id_ = static_cast<EventID>(atoi((lidar_iter->second).c_str())); } auto radar_iter = reserve_field_map.find("radar_event_id"); if (radar_iter == reserve_field_map.end()) { AWARN << "Failed to find radar_event_id:" << reserve_; AINFO << "radar_event_id will be set -1"; radar_event_id_ = -1; } else { radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str())); } auto camera_iter = reserve_field_map.find("camera_event_id"); if (camera_iter == reserve_field_map.end()) { AWARN << "Failed to find camera_event_id:" << reserve_; AINFO << "camera_event_id will be set -1"; camera_event_id_ = -1; } else { camera_event_id_ = static_cast<EventID>(atoi((camera_iter->second).c_str())); } auto lane_iter = reserve_field_map.find("lane_event_id"); if (lane_iter == reserve_field_map.end()) { AWARN << "Failed to find camera_event_id:" << reserve_; AINFO << "camera_event_id will be set -1"; lane_event_id_ = -1; } else { lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str())); } return true; } Status FusionSubnode::ProcEvents() { for (auto event_meta : sub_meta_events_) { // ignore lane event from polling if (event_meta.event_id == lane_event_id_) continue; std::vector<Event> events; if (!SubscribeEvents(event_meta, &events)) { AERROR << "event meta id:" << event_meta.event_id << " " << event_meta.from_node << " " << event_meta.to_node; return Status(ErrorCode::PERCEPTION_ERROR, "Subscribe event fail."); } if (events.empty()) { usleep(500); continue; } Process(event_meta, events); if (event_meta.event_id != pub_driven_event_id_) { ADEBUG << "Not pub_driven_event_id, skip to publish." << " event_id:" << event_meta.event_id << " fused_obj_cnt:" << objects_.size(); continue; } // public obstacle message PerceptionObstacles obstacles; if (GeneratePbMsg(&obstacles)) { common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles); } AINFO << "Publish 3d perception fused msg. timestamp:" << GLOG_TIMESTAMP(timestamp_) << " obj_cnt:" << objects_.size(); } return Status::OK(); } Status FusionSubnode::Process(const EventMeta &event_meta, const std::vector<Event> &events) { std::vector<SensorObjects> sensor_objs; if (!BuildSensorObjs(events, &sensor_objs)) { AERROR << "Failed to build_sensor_objs"; error_code_ = common::PERCEPTION_ERROR_PROCESS; return Status(ErrorCode::PERCEPTION_ERROR, "Failed to build_sensor_objs."); } PERF_BLOCK_START(); objects_.clear(); if (!fusion_->Fuse(sensor_objs, &objects_)) { AWARN << "Failed to call fusion plugin." << " event_meta: [" << event_meta.to_string() << "] event_cnt:" << events.size() << " event_0: [" << events[0].to_string() << "]"; error_code_ = common::PERCEPTION_ERROR_PROCESS; return Status(ErrorCode::PERCEPTION_ERROR, "Failed to call fusion plugin."); } if (event_meta.event_id == lidar_event_id_) { PERF_BLOCK_END("fusion_lidar"); } else if (event_meta.event_id == radar_event_id_) { PERF_BLOCK_END("fusion_radar"); } else if (event_meta.event_id == camera_event_id_) { PERF_BLOCK_END("fusion_camera"); } if (objects_.size() > 0 && FLAGS_publish_fusion_event) { SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem); fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time; const std::string &device_id = events[0].reserve; for (auto obj : objects_) { ObjectPtr objclone(new Object()); objclone->clone(*obj); fusion_item_ptr->obstacles.push_back(objclone); } AINFO << "publishing event for timestamp deviceid and size of fusion object" << fusion_item_ptr->timestamp << " " << device_id << " " << fusion_item_ptr->obstacles.size(); PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr); } timestamp_ = sensor_objs[0].timestamp; error_code_ = common::OK; return Status::OK(); } void FusionSubnode::PublishDataAndEvent(const double &timestamp, const std::string &device_id, const SharedDataPtr<FusionItem> &data) { CommonSharedDataKey key(timestamp, device_id); bool fusion_succ = fusion_data_->Add(key, data); if (!fusion_succ) { AERROR << "fusion shared data addkey failure"; } AINFO << "adding key in fusion shared data " << key.ToString(); for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) { const EventMeta &event_meta = pub_meta_events_[idx]; Event event; event.event_id = event_meta.event_id; event.timestamp = timestamp; event.reserve = device_id; event_manager_->Publish(event); } } bool FusionSubnode::SubscribeEvents(const EventMeta &event_meta, std::vector<Event> *events) const { Event event; // no blocking while (event_manager_->Subscribe(event_meta.event_id, &event, true)) { events->push_back(event); } return true; } bool FusionSubnode::BuildSensorObjs( const std::vector<Event> &events, std::vector<SensorObjects> *multi_sensor_objs) { PERF_FUNCTION(); for (auto event : events) { std::shared_ptr<SensorObjects> sensor_objects; if (!GetSharedData(event, &sensor_objects)) { return false; } // Make sure timestamp and type are filled. sensor_objects->timestamp = event.timestamp; if (event.event_id == lidar_event_id_) { sensor_objects->sensor_type = SensorType::VELODYNE_64; } else if (event.event_id == radar_event_id_) { sensor_objects->sensor_type = SensorType::RADAR; } else if (event.event_id == camera_event_id_) { sensor_objects->sensor_type = SensorType::CAMERA; } else { AERROR << "Event id is not supported. event:" << event.to_string(); return false; } sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type); multi_sensor_objs->push_back(*sensor_objects); ADEBUG << "get sensor objs:" << sensor_objects->ToString(); } return true; } bool FusionSubnode::GetSharedData(const Event &event, std::shared_ptr<SensorObjects> *objs) { double timestamp = event.timestamp; const std::string &device_id = event.reserve; std::string data_key; if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) { AERROR << "Failed to produce shared data key. EventID:" << event.event_id << " timestamp:" << timestamp << " device_id:" << device_id; return false; } bool get_data_succ = false; if (event.event_id == lidar_event_id_ && lidar_object_data_ != nullptr) { get_data_succ = lidar_object_data_->Get(data_key, objs); } else if (event.event_id == radar_event_id_ && radar_object_data_ != nullptr) { get_data_succ = radar_object_data_->Get(data_key, objs); } else if (event.event_id == camera_event_id_ && camera_object_data_ != nullptr) { get_data_succ = camera_object_data_->Get(data_key, objs); // trying to get lane shared data as well Event lane_event; if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) { get_data_succ = lane_shared_data_->Get(data_key, &lane_objects_); ADEBUG << "getting lane data successfully for data key " << data_key; } } else { AERROR << "Event id is not supported. event:" << event.to_string(); return false; } if (!get_data_succ) { AERROR << "Failed to get shared data. event:" << event.to_string(); return false; } return true; } bool FusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) { common::adapter::AdapterManager::FillPerceptionObstaclesHeader( FLAGS_obstacle_module_name, obstacles); common::Header *header = obstacles->mutable_header(); if (pub_driven_event_id_ == lidar_event_id_) { header->set_lidar_timestamp(timestamp_ * 1e9); // in ns header->set_camera_timestamp(0); header->set_radar_timestamp(0); } else if (pub_driven_event_id_ == camera_event_id_) { header->set_lidar_timestamp(0); // in ns header->set_camera_timestamp(timestamp_ * 1e9); header->set_radar_timestamp(0); } obstacles->set_error_code(error_code_); for (const auto &obj : objects_) { PerceptionObstacle *obstacle = obstacles->add_perception_obstacle(); obj->Serialize(obstacle); } if (FLAGS_use_navigation_mode) { // generate lane marker protobuf messages LaneMarkers *lane_markers = obstacles->mutable_lane_marker(); LaneObjectsToLaneMarkerProto(*(lane_objects_), lane_markers); // Relative speed of objects + latest ego car speed in X for (auto obstacle : obstacles->perception_obstacle()) { obstacle.mutable_velocity()->set_x(obstacle.velocity().x() + chassis_speed_mps_); } } ADEBUG << "PerceptionObstacles: " << obstacles->ShortDebugString(); return true; } void FusionSubnode::RegistAllAlgorithm() { RegisterFactoryProbabilisticFusion(); RegisterFactoryAsyncFusion(); } void FusionSubnode::OnChassis(const Chassis &chassis) { ADEBUG << "Received chassis data: run chassis callback."; chassis_.CopyFrom(chassis); chassis_speed_mps_ = chassis_.speed_mps(); } } // namespace perception } // namespace apollo <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stylematrixreferencecontext.hxx,v $ * * $Revision: 1.2 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX #define OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX #include "oox/core/contexthandler.hxx" #include "oox/drawingml/color.hxx" namespace oox { namespace drawingml { class StyleMatrixReferenceContext : public oox::core::ContextHandler { public: StyleMatrixReferenceContext( ::oox::core::ContextHandler& rParent, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs, rtl::OUString& rIdentifier, oox::drawingml::Color& rColor ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); protected: ::oox::drawingml::Color& mrColor; }; } } #endif // OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX <commit_msg>INTEGRATION: CWS xmlfilter06 (1.2.8); FILE MERGED 2008/06/30 14:50:17 dr 1.2.8.1: #i10000# resync additions<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stylematrixreferencecontext.hxx,v $ * * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX #define OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX #include "oox/core/contexthandler.hxx" #include "oox/drawingml/color.hxx" namespace oox { namespace drawingml { class StyleMatrixReferenceContext : public oox::core::ContextHandler { public: StyleMatrixReferenceContext( ::oox::core::ContextHandler& rParent, Color& rColor ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); private: Color& mrColor; }; } } #endif // OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "resizetool.h" #include "formeditorscene.h" #include "formeditorview.h" #include "formeditorwidget.h" #include "resizehandleitem.h" #include <QApplication> #include <QGraphicsSceneMouseEvent> #include <QAction> #include <QtDebug> namespace QmlDesigner { ResizeTool::ResizeTool(FormEditorView *editorView) : AbstractFormEditorTool(editorView), m_selectionIndicator(editorView->scene()->manipulatorLayerItem()), m_resizeIndicator(editorView->scene()->manipulatorLayerItem()), m_resizeManipulator(editorView->scene()->manipulatorLayerItem(), editorView) { } ResizeTool::~ResizeTool() { } void ResizeTool::mousePressEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { if (itemList.isEmpty()) return; ResizeHandleItem *resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first()); if (resizeHandle && resizeHandle->resizeController().isValid()) { m_resizeManipulator.setHandle(resizeHandle); m_resizeManipulator.begin(event->scenePos()); m_resizeIndicator.hide(); } } void ResizeTool::mouseMoveEvent(const QList<QGraphicsItem*> &, QGraphicsSceneMouseEvent *event) { bool shouldSnapping = view()->widget()->snappingAction()->isChecked(); bool shouldSnappingAndAnchoring = view()->widget()->snappingAndAnchoringAction()->isChecked(); ResizeManipulator::Snapping useSnapping = ResizeManipulator::NoSnapping; if (event->modifiers().testFlag(Qt::ControlModifier) != (shouldSnapping || shouldSnappingAndAnchoring)) { if (shouldSnappingAndAnchoring) useSnapping = ResizeManipulator::UseSnappingAndAnchoring; else useSnapping = ResizeManipulator::UseSnapping; } m_resizeManipulator.update(event->scenePos(), useSnapping); } void ResizeTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent * /*event*/) { if (itemList.isEmpty()) return; ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first()); if (resizeHandle && resizeHandle->resizeController().isValid()) { m_resizeManipulator.setHandle(resizeHandle); } else { view()->changeToSelectionTool(); return; } } void ResizeTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent * /*event*/) { if (itemList.isEmpty()) return; m_selectionIndicator.show(); m_resizeIndicator.show(); m_resizeManipulator.end(); } void ResizeTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> & /*itemList*/, QGraphicsSceneMouseEvent * /*event*/) { } void ResizeTool::keyPressEvent(QKeyEvent * event) { switch(event->key()) { case Qt::Key_Shift: case Qt::Key_Alt: case Qt::Key_Control: case Qt::Key_AltGr: event->setAccepted(false); return; } double moveStep = 1.0; if (event->modifiers().testFlag(Qt::ShiftModifier)) moveStep = 10.0; switch(event->key()) { case Qt::Key_Left: m_resizeManipulator.moveBy(-moveStep, 0.0); break; case Qt::Key_Right: m_resizeManipulator.moveBy(moveStep, 0.0); break; case Qt::Key_Up: m_resizeManipulator.moveBy(0.0, -moveStep); break; case Qt::Key_Down: m_resizeManipulator.moveBy(0.0, moveStep); break; } } void ResizeTool::keyReleaseEvent(QKeyEvent * keyEvent) { switch(keyEvent->key()) { case Qt::Key_Shift: case Qt::Key_Alt: case Qt::Key_Control: case Qt::Key_AltGr: keyEvent->setAccepted(false); return; } // if (!keyEvent->isAutoRepeat()) // m_resizeManipulator.clear(); } void ResizeTool::itemsAboutToRemoved(const QList<FormEditorItem*> & /*itemList*/) { } void ResizeTool::selectedItemsChanged(const QList<FormEditorItem*> & /*itemList*/) { m_selectionIndicator.setItems(items()); m_resizeIndicator.setItems(items()); } void ResizeTool::clear() { m_selectionIndicator.clear(); m_resizeIndicator.clear(); m_resizeManipulator.clear(); } void ResizeTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList) { m_selectionIndicator.updateItems(itemList); m_resizeIndicator.updateItems(itemList); } void ResizeTool::instancesCompleted(const QList<FormEditorItem*> &/*itemList*/) { } } <commit_msg>QmlDesigner.FormEditor: Resize only for hovering<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "resizetool.h" #include "formeditorscene.h" #include "formeditorview.h" #include "formeditorwidget.h" #include "resizehandleitem.h" #include <QApplication> #include <QGraphicsSceneMouseEvent> #include <QAction> #include <QtDebug> namespace QmlDesigner { ResizeTool::ResizeTool(FormEditorView *editorView) : AbstractFormEditorTool(editorView), m_selectionIndicator(editorView->scene()->manipulatorLayerItem()), m_resizeIndicator(editorView->scene()->manipulatorLayerItem()), m_resizeManipulator(editorView->scene()->manipulatorLayerItem(), editorView) { } ResizeTool::~ResizeTool() { } void ResizeTool::mousePressEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { if (itemList.isEmpty()) return; ResizeHandleItem *resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first()); if (resizeHandle && resizeHandle->resizeController().isValid()) { m_resizeManipulator.setHandle(resizeHandle); m_resizeManipulator.begin(event->scenePos()); m_resizeIndicator.hide(); } } void ResizeTool::mouseMoveEvent(const QList<QGraphicsItem*> &, QGraphicsSceneMouseEvent *event) { bool shouldSnapping = view()->widget()->snappingAction()->isChecked(); bool shouldSnappingAndAnchoring = view()->widget()->snappingAndAnchoringAction()->isChecked(); ResizeManipulator::Snapping useSnapping = ResizeManipulator::NoSnapping; if (event->modifiers().testFlag(Qt::ControlModifier) != (shouldSnapping || shouldSnappingAndAnchoring)) { if (shouldSnappingAndAnchoring) useSnapping = ResizeManipulator::UseSnappingAndAnchoring; else useSnapping = ResizeManipulator::UseSnapping; } m_resizeManipulator.update(event->scenePos(), useSnapping); } void ResizeTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent * /*event*/) { if (itemList.isEmpty()) { view()->changeToSelectionTool(); return; } ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first()); if (resizeHandle && resizeHandle->resizeController().isValid()) { m_resizeManipulator.setHandle(resizeHandle); } else { view()->changeToSelectionTool(); return; } } void ResizeTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent * /*event*/) { if (itemList.isEmpty()) return; m_selectionIndicator.show(); m_resizeIndicator.show(); m_resizeManipulator.end(); } void ResizeTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> & /*itemList*/, QGraphicsSceneMouseEvent * /*event*/) { } void ResizeTool::keyPressEvent(QKeyEvent * event) { switch(event->key()) { case Qt::Key_Shift: case Qt::Key_Alt: case Qt::Key_Control: case Qt::Key_AltGr: event->setAccepted(false); return; } double moveStep = 1.0; if (event->modifiers().testFlag(Qt::ShiftModifier)) moveStep = 10.0; switch(event->key()) { case Qt::Key_Left: m_resizeManipulator.moveBy(-moveStep, 0.0); break; case Qt::Key_Right: m_resizeManipulator.moveBy(moveStep, 0.0); break; case Qt::Key_Up: m_resizeManipulator.moveBy(0.0, -moveStep); break; case Qt::Key_Down: m_resizeManipulator.moveBy(0.0, moveStep); break; } } void ResizeTool::keyReleaseEvent(QKeyEvent * keyEvent) { switch(keyEvent->key()) { case Qt::Key_Shift: case Qt::Key_Alt: case Qt::Key_Control: case Qt::Key_AltGr: keyEvent->setAccepted(false); return; } // if (!keyEvent->isAutoRepeat()) // m_resizeManipulator.clear(); } void ResizeTool::itemsAboutToRemoved(const QList<FormEditorItem*> & /*itemList*/) { } void ResizeTool::selectedItemsChanged(const QList<FormEditorItem*> & /*itemList*/) { m_selectionIndicator.setItems(items()); m_resizeIndicator.setItems(items()); } void ResizeTool::clear() { m_selectionIndicator.clear(); m_resizeIndicator.clear(); m_resizeManipulator.clear(); } void ResizeTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList) { m_selectionIndicator.updateItems(itemList); m_resizeIndicator.updateItems(itemList); } void ResizeTool::instancesCompleted(const QList<FormEditorItem*> &/*itemList*/) { } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: appdata.cxx,v $ * * $Revision: 1.23 $ * * last change: $Author: obo $ $Date: 2006-09-17 16:14:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #ifndef _CACHESTR_HXX //autogen #include <tools/cachestr.hxx> #endif #ifndef _CONFIG_HXX #include <tools/config.hxx> #endif #ifndef _INETSTRM_HXX //autogen #include <svtools/inetstrm.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #define _SVSTDARR_STRINGS #include <svtools/svstdarr.hxx> #include <vos/mutex.hxx> #include <vcl/menu.hxx> #ifndef _LOGINERR_HXX #include <svtools/loginerr.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _DATETIMEITEM_HXX //autogen #include <svtools/dateitem.hxx> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif #include "comphelper/processfactory.hxx" #include "viewfrm.hxx" #include "appdata.hxx" #include "dispatch.hxx" #include "event.hxx" #include "sfxtypes.hxx" #include "doctempl.hxx" #include "arrdecl.hxx" #include "docfac.hxx" #include "docfile.hxx" #include "request.hxx" #include "referers.hxx" #include "app.hrc" #include "sfxresid.hxx" #include "objshimp.hxx" #include "appuno.hxx" #include "imestatuswindow.hxx" SfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) : pDdeService( 0 ), pDocTopics( 0 ), pTriggerTopic(0), pDdeService2(0), pFactArr(0), pTopFrames( new SfxFrameArr_Impl ), pInitLinkList(0), pMatcher( 0 ), pCancelMgr( 0 ), pLabelResMgr( 0 ), pAppDispatch(NULL), pTemplates( 0 ), pPool(0), pEventConfig(0), pDisabledSlotList( 0 ), pSecureURLs(0), pMiscConfig(0), pSaveOptions( 0 ), pUndoOptions( 0 ), pHelpOptions( 0 ), pThisDocument(0), pProgress(0), pTemplateCommon( 0 ), nDocModalMode(0), nAutoTabPageId(0), nBasicCallLevel(0), nRescheduleLocks(0), nInReschedule(0), nAsynchronCalls(0), m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow( *pApp, comphelper::getProcessServiceFactory())) , pTbxCtrlFac(0) , pStbCtrlFac(0) , pViewFrames(0) , pObjShells(0) , pSfxResManager(0) , pOfaResMgr(0) , pSimpleResManager(0) , pBasicLibContainer(0) , pDialogLibContainer(0) , pViewFrame( 0 ) , pSlotPool( 0 ) , pResMgr( 0 ) , pAppDispat( 0 ) , pInterfaces( 0 ) , nDocNo(0) , nInterfaces( 0 ) , bDowning( sal_True ), bInQuit(sal_False), bInvalidateOnUnlock(sal_False) { } SfxAppData_Impl::~SfxAppData_Impl() { DeInitDDE(); delete pTopFrames; delete pCancelMgr; delete pSecureURLs; } IMPL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void*, EMPTYARG) { pThis->GetDocumentTemplates(); return 0; } void SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide ) { AllSettings aAllSet = Application::GetSettings(); StyleSettings aStyleSet = aAllSet.GetStyleSettings(); sal_uInt32 nStyleOptions = aStyleSet.GetOptions(); if ( bDontHide ) nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED; else nStyleOptions |= STYLE_OPTION_HIDEDISABLED; aStyleSet.SetOptions( nStyleOptions ); aAllSet.SetStyleSettings( aStyleSet ); Application::SetSettings( aAllSet ); } SfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates() { if ( !pTemplates ) pTemplates = new SfxDocumentTemplates; else pTemplates->ReInitFromComponent(); return pTemplates; } <commit_msg>INTEGRATION: CWS basmgr01 (1.23.8); FILE MERGED 2006/09/28 20:25:45 fs 1.23.8.1: #i69957#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: appdata.cxx,v $ * * $Revision: 1.24 $ * * last change: $Author: kz $ $Date: 2006-11-08 11:57:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #ifndef _CACHESTR_HXX //autogen #include <tools/cachestr.hxx> #endif #ifndef _CONFIG_HXX #include <tools/config.hxx> #endif #ifndef _INETSTRM_HXX //autogen #include <svtools/inetstrm.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #define _SVSTDARR_STRINGS #include <svtools/svstdarr.hxx> #include <vos/mutex.hxx> #include <vcl/menu.hxx> #ifndef _LOGINERR_HXX #include <svtools/loginerr.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _DATETIMEITEM_HXX //autogen #include <svtools/dateitem.hxx> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif #include "comphelper/processfactory.hxx" #include "viewfrm.hxx" #include "appdata.hxx" #include "dispatch.hxx" #include "event.hxx" #include "sfxtypes.hxx" #include "doctempl.hxx" #include "arrdecl.hxx" #include "docfac.hxx" #include "docfile.hxx" #include "request.hxx" #include "referers.hxx" #include "app.hrc" #include "sfxresid.hxx" #include "objshimp.hxx" #include "appuno.hxx" #include "imestatuswindow.hxx" #include "appbaslib.hxx" #include <basic/basicmanagerrepository.hxx> #include <basic/basmgr.hxx> using ::basic::BasicManagerRepository; using ::basic::BasicManagerCreationListener; using ::com::sun::star::uno::Reference; using ::com::sun::star::frame::XModel; class SfxBasicManagerCreationListener : public ::basic::BasicManagerCreationListener { private: SfxAppData_Impl& m_rAppData; public: SfxBasicManagerCreationListener( SfxAppData_Impl& _rAppData ) :m_rAppData( _rAppData ) { } virtual void onBasicManagerCreated( const Reference< XModel >& _rxForDocument, BasicManager& _rBasicManager ); }; void SfxBasicManagerCreationListener::onBasicManagerCreated( const Reference< XModel >& _rxForDocument, BasicManager& _rBasicManager ) { if ( _rxForDocument == NULL ) m_rAppData.OnApplicationBasicManagerCreated( _rBasicManager ); } SfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) : pDdeService( 0 ), pDocTopics( 0 ), pTriggerTopic(0), pDdeService2(0), pFactArr(0), pTopFrames( new SfxFrameArr_Impl ), pInitLinkList(0), pMatcher( 0 ), pCancelMgr( 0 ), pLabelResMgr( 0 ), pAppDispatch(NULL), pTemplates( 0 ), pPool(0), pEventConfig(0), pDisabledSlotList( 0 ), pSecureURLs(0), pMiscConfig(0), pSaveOptions( 0 ), pUndoOptions( 0 ), pHelpOptions( 0 ), pThisDocument(0), pProgress(0), pTemplateCommon( 0 ), nDocModalMode(0), nAutoTabPageId(0), nBasicCallLevel(0), nRescheduleLocks(0), nInReschedule(0), nAsynchronCalls(0), m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow( *pApp, comphelper::getProcessServiceFactory())) , pTbxCtrlFac(0) , pStbCtrlFac(0) , pViewFrames(0) , pObjShells(0) , pSfxResManager(0) , pOfaResMgr(0) , pSimpleResManager(0) , pBasicManager( new SfxBasicManagerHolder ) , pBasMgrListener( new SfxBasicManagerCreationListener( *this ) ) , pViewFrame( 0 ) , pSlotPool( 0 ) , pResMgr( 0 ) , pAppDispat( 0 ) , pInterfaces( 0 ) , nDocNo(0) , nInterfaces( 0 ) , bDowning( sal_True ), bInQuit(sal_False), bInvalidateOnUnlock(sal_False) { BasicManagerRepository::registerCreationListener( *pBasMgrListener ); } SfxAppData_Impl::~SfxAppData_Impl() { DeInitDDE(); delete pTopFrames; delete pCancelMgr; delete pSecureURLs; delete pBasicManager; BasicManagerRepository::revokeCreationListener( *pBasMgrListener ); delete pBasMgrListener; } IMPL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void*, EMPTYARG) { pThis->GetDocumentTemplates(); return 0; } void SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide ) { AllSettings aAllSet = Application::GetSettings(); StyleSettings aStyleSet = aAllSet.GetStyleSettings(); sal_uInt32 nStyleOptions = aStyleSet.GetOptions(); if ( bDontHide ) nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED; else nStyleOptions |= STYLE_OPTION_HIDEDISABLED; aStyleSet.SetOptions( nStyleOptions ); aAllSet.SetStyleSettings( aStyleSet ); Application::SetSettings( aAllSet ); } SfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates() { if ( !pTemplates ) pTemplates = new SfxDocumentTemplates; else pTemplates->ReInitFromComponent(); return pTemplates; } void SfxAppData_Impl::OnApplicationBasicManagerCreated( BasicManager& _rBasicManager ) { pBasicManager->reset( &_rBasicManager ); // global constants, additionally to the ones already added by createApplicationBasicManager: // ThisComponent Reference< XModel > xThisComponent; SfxObjectShell* pDoc = SfxObjectShell::Current(); if ( pDoc ) xThisComponent = pDoc->GetModel(); _rBasicManager.InsertGlobalUNOConstant( "ThisComponent", makeAny( xThisComponent ) ); pThisDocument = pDoc; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: newhelp.hxx,v $ * * $Revision: 1.18 $ * * last change: $Author: pb $ $Date: 2001-07-09 11:36:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_SFX_NEWHELP_HXX #define INCLUDED_SFX_NEWHELP_HXX #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif namespace com { namespace sun { namespace star { namespace frame { class XFrame; } } } }; namespace com { namespace sun { namespace star { namespace awt { class XWindow; } } } }; #include <vcl/window.hxx> #include <vcl/toolbox.hxx> #include <vcl/tabpage.hxx> #include <vcl/splitwin.hxx> #include <vcl/tabctrl.hxx> #include <vcl/combobox.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/lstbox.hxx> #include <vcl/dialog.hxx> // class OpenStatusListener_Impl ----------------------------------------- class OpenStatusListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener > { private: sal_Bool m_bFinished; sal_Bool m_bSuccess; String m_aURL; Link m_aOpenLink; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xDispatch; public: OpenStatusListener_Impl() : m_bFinished( FALSE ), m_bSuccess( FALSE ) {} virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException); void AddListener( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& xDispatch, const ::com::sun::star::util::URL& aURL ); sal_Bool IsFinished() const { return m_bFinished; } sal_Bool IsSuccessful() const { return m_bSuccess; } const String& GetURL() const { return m_aURL; } void SetOpenHdl( const Link& rLink ) { m_aOpenLink = rLink; } }; // class ContentTabPage_Impl --------------------------------------------- class ContentTabPage_Impl : public TabPage { private: Window aContentWin; public: ContentTabPage_Impl( Window* pParent ); virtual void Resize(); }; // class IndexTabPage_Impl ----------------------------------------------- class IndexTabPage_Impl : public TabPage { private: FixedText aExpressionFT; ComboBox aIndexCB; PushButton aOpenBtn; Timer aFactoryTimer; long nMinWidth; String aFactory; void InitializeIndex(); void ClearIndex(); DECL_LINK( OpenHdl, PushButton* ); DECL_LINK( FactoryHdl, Timer* ); public: IndexTabPage_Impl( Window* pParent ); ~IndexTabPage_Impl(); virtual void Resize(); void SetDoubleClickHdl( const Link& rLink ); void SetFactory( const String& rFactory ); String GetFactory() const { return aFactory; } String GetSelectEntry() const; }; // class SearchTabPage_Impl ---------------------------------------------- class SearchBox_Impl : public ComboBox { private: Link aSearchLink; public: SearchBox_Impl( Window* pParent, const ResId& rResId ) : ComboBox( pParent, rResId ) { SetDropDownLineCount( 5 ); } virtual long PreNotify( NotifyEvent& rNEvt ); virtual void Select(); void SetSearchLink( const Link& rLink ) { aSearchLink = rLink; } }; class SearchTabPage_Impl : public TabPage { private: FixedText aSearchFT; SearchBox_Impl aSearchED; PushButton aSearchBtn; ListBox aResultsLB; PushButton aOpenBtn; CheckBox aScopeCB; Size aMinSize; String aFactory; void ClearSearchResults(); void RememberSearchText( const String& rSearchText ); DECL_LINK( SearchHdl, PushButton* ); DECL_LINK( OpenHdl, PushButton* ); public: SearchTabPage_Impl( Window* pParent ); ~SearchTabPage_Impl(); virtual void Resize(); void SetDoubleClickHdl( const Link& rLink ); void SetFactory( const String& rFactory ) { aFactory = rFactory; } String GetSelectEntry() const; }; // class BookmarksTabPage_Impl ------------------------------------------- class BookmarksBox_Impl : public ListBox { private: void DoAction( USHORT nAction ); public: BookmarksBox_Impl( Window* pParent, const ResId& rResId ); ~BookmarksBox_Impl(); virtual long Notify( NotifyEvent& rNEvt ); }; class BookmarksTabPage_Impl : public TabPage { private: FixedText aBookmarksFT; BookmarksBox_Impl aBookmarksBox; PushButton aBookmarksPB; long nMinWidth; public: BookmarksTabPage_Impl( Window* pParent ); virtual void Resize(); void SetDoubleClickHdl( const Link& rLink ); String GetSelectEntry() const; void AddBookmarks( const String& rTitle, const String& rURL ); }; // class SfxHelpIndexWindow_Impl ----------------------------------------- class SfxHelpIndexWindow_Impl : public Window { private: ListBox aActiveLB; FixedLine aActiveLine; TabControl aTabCtrl; Timer aInitTimer; ContentTabPage_Impl* pCPage; IndexTabPage_Impl* pIPage; SearchTabPage_Impl* pSPage; BookmarksTabPage_Impl* pFPage; long nMinWidth; void Initialize(); void SetActiveFactory(); DECL_LINK( ActivatePageHdl, TabControl* ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( InitHdl, Timer* ); public: SfxHelpIndexWindow_Impl( Window* pParent ); ~SfxHelpIndexWindow_Impl(); virtual void Resize(); void SetDoubleClickHdl( const Link& rLink ); void SetFactory( const String& rFactory, sal_Bool bActive ); String GetFactory() const { return pIPage->GetFactory(); } String GetSelectEntry() const; void AddBookmarks( const String& rTitle, const String& rURL ); }; // class SfxHelpTextWindow_Impl ------------------------------------------ class SfxHelpWindow_Impl; class SfxHelpTextWindow_Impl : public Window { private: ToolBox aToolBox; SfxHelpWindow_Impl* pHelpWin; Window* pTextWin; ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame; sal_Bool bIsDebug; public: SfxHelpTextWindow_Impl( SfxHelpWindow_Impl* pParent ); ~SfxHelpTextWindow_Impl(); virtual void Resize(); virtual long PreNotify( NotifyEvent& rNEvt ); void SetSelectHdl( const Link& rLink ) { aToolBox.SetSelectHdl( rLink ); } ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > getFrame() const { return xFrame; } }; // class SfxHelpWindow_Impl ---------------------------------------------- class HelpInterceptor_Impl; class HelpListener_Impl; class SfxHelpWindow_Impl : public SplitWindow { private: ::com::sun::star::uno::Reference < ::com::sun::star::awt::XWindow > xWindow; ::com::sun::star::uno::Reference < ::com::sun::star::frame::XStatusListener > xOpenListener; SfxHelpIndexWindow_Impl* pIndexWin; SfxHelpTextWindow_Impl* pTextWin; HelpInterceptor_Impl* pHelpInterceptor; HelpListener_Impl* pHelpListener; sal_Int32 nExpandWidth; sal_Int32 nCollapseWidth; sal_Int32 nHeight; long nIndexSize; long nTextSize; sal_Bool bIndex; virtual void Resize(); virtual void Split(); void MakeLayout(); void InitSizes(); void LoadConfig(); void SaveConfig(); DECL_LINK( SelectHdl, ToolBox* ); DECL_LINK( OpenHdl, SfxHelpIndexWindow_Impl* ); DECL_LINK( ChangeHdl, HelpListener_Impl* ); DECL_LINK( OpenDoneHdl, OpenStatusListener_Impl* ); public: SfxHelpWindow_Impl( const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& rFrame, Window* pParent, WinBits nBits ); ~SfxHelpWindow_Impl(); void setContainerWindow( ::com::sun::star::uno::Reference < ::com::sun::star::awt::XWindow > xWin ); void SetFactory( const String& rFactory, sal_Bool bStart ); void SetHelpURL( const String& rURL ); void DoAction( USHORT nActionId ); }; class SfxAddHelpBookmarkDialog_Impl : public ModalDialog { private: FixedText aTitleFT; Edit aTitleED; OKButton aOKBtn; CancelButton aEscBtn; HelpButton aHelpBtn; public: SfxAddHelpBookmarkDialog_Impl( Window* pParent, sal_Bool bRename = sal_True ); ~SfxAddHelpBookmarkDialog_Impl(); void SetTitle( const String& rTitle ); String GetTitle() const { return aTitleED.GetText(); } }; #endif // #ifndef INCLUDED_SFX_NEWHELP_HXX <commit_msg>fix: #89087# #87761# index on/off images/strings added, SelectFactory handler added<commit_after>/************************************************************************* * * $RCSfile: newhelp.hxx,v $ * * $Revision: 1.19 $ * * last change: $Author: pb $ $Date: 2001-07-12 10:27:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_SFX_NEWHELP_HXX #define INCLUDED_SFX_NEWHELP_HXX #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif namespace com { namespace sun { namespace star { namespace frame { class XFrame; } } } }; namespace com { namespace sun { namespace star { namespace awt { class XWindow; } } } }; #include <vcl/window.hxx> #include <vcl/toolbox.hxx> #include <vcl/tabpage.hxx> #include <vcl/splitwin.hxx> #include <vcl/tabctrl.hxx> #include <vcl/combobox.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/lstbox.hxx> #include <vcl/dialog.hxx> // class OpenStatusListener_Impl ----------------------------------------- class OpenStatusListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener > { private: sal_Bool m_bFinished; sal_Bool m_bSuccess; String m_aURL; Link m_aOpenLink; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xDispatch; public: OpenStatusListener_Impl() : m_bFinished( FALSE ), m_bSuccess( FALSE ) {} virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException); void AddListener( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& xDispatch, const ::com::sun::star::util::URL& aURL ); sal_Bool IsFinished() const { return m_bFinished; } sal_Bool IsSuccessful() const { return m_bSuccess; } const String& GetURL() const { return m_aURL; } void SetOpenHdl( const Link& rLink ) { m_aOpenLink = rLink; } }; // class ContentTabPage_Impl --------------------------------------------- class ContentTabPage_Impl : public TabPage { private: Window aContentWin; public: ContentTabPage_Impl( Window* pParent ); virtual void Resize(); }; // class IndexTabPage_Impl ----------------------------------------------- class IndexTabPage_Impl : public TabPage { private: FixedText aExpressionFT; ComboBox aIndexCB; PushButton aOpenBtn; Timer aFactoryTimer; long nMinWidth; String aFactory; void InitializeIndex(); void ClearIndex(); DECL_LINK( OpenHdl, PushButton* ); DECL_LINK( FactoryHdl, Timer* ); public: IndexTabPage_Impl( Window* pParent ); ~IndexTabPage_Impl(); virtual void Resize(); void SetDoubleClickHdl( const Link& rLink ); void SetFactory( const String& rFactory ); String GetFactory() const { return aFactory; } String GetSelectEntry() const; }; // class SearchTabPage_Impl ---------------------------------------------- class SearchBox_Impl : public ComboBox { private: Link aSearchLink; public: SearchBox_Impl( Window* pParent, const ResId& rResId ) : ComboBox( pParent, rResId ) { SetDropDownLineCount( 5 ); } virtual long PreNotify( NotifyEvent& rNEvt ); virtual void Select(); void SetSearchLink( const Link& rLink ) { aSearchLink = rLink; } }; class SearchTabPage_Impl : public TabPage { private: FixedText aSearchFT; SearchBox_Impl aSearchED; PushButton aSearchBtn; ListBox aResultsLB; PushButton aOpenBtn; CheckBox aScopeCB; Size aMinSize; String aFactory; void ClearSearchResults(); void RememberSearchText( const String& rSearchText ); DECL_LINK( SearchHdl, PushButton* ); DECL_LINK( OpenHdl, PushButton* ); public: SearchTabPage_Impl( Window* pParent ); ~SearchTabPage_Impl(); virtual void Resize(); void SetDoubleClickHdl( const Link& rLink ); void SetFactory( const String& rFactory ) { aFactory = rFactory; } String GetSelectEntry() const; }; // class BookmarksTabPage_Impl ------------------------------------------- class BookmarksBox_Impl : public ListBox { private: void DoAction( USHORT nAction ); public: BookmarksBox_Impl( Window* pParent, const ResId& rResId ); ~BookmarksBox_Impl(); virtual long Notify( NotifyEvent& rNEvt ); }; class BookmarksTabPage_Impl : public TabPage { private: FixedText aBookmarksFT; BookmarksBox_Impl aBookmarksBox; PushButton aBookmarksPB; long nMinWidth; public: BookmarksTabPage_Impl( Window* pParent ); virtual void Resize(); void SetDoubleClickHdl( const Link& rLink ); String GetSelectEntry() const; void AddBookmarks( const String& rTitle, const String& rURL ); }; // class SfxHelpIndexWindow_Impl ----------------------------------------- class SfxHelpIndexWindow_Impl : public Window { private: ListBox aActiveLB; FixedLine aActiveLine; TabControl aTabCtrl; Timer aInitTimer; Link aSelectFactoryLink; ContentTabPage_Impl* pCPage; IndexTabPage_Impl* pIPage; SearchTabPage_Impl* pSPage; BookmarksTabPage_Impl* pFPage; long nMinWidth; void Initialize(); void SetActiveFactory(); DECL_LINK( ActivatePageHdl, TabControl* ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( InitHdl, Timer* ); public: SfxHelpIndexWindow_Impl( Window* pParent ); ~SfxHelpIndexWindow_Impl(); virtual void Resize(); void SetDoubleClickHdl( const Link& rLink ); void SetSelectFactoryHdl( const Link& rLink ) { aSelectFactoryLink = rLink; } void SetFactory( const String& rFactory, sal_Bool bActive ); String GetFactory() const { return pIPage->GetFactory(); } String GetSelectEntry() const; void AddBookmarks( const String& rTitle, const String& rURL ); String GetActiveFactoryTitle() const { return aActiveLB.GetSelectEntry(); } }; // class SfxHelpTextWindow_Impl ------------------------------------------ class SfxHelpWindow_Impl; class SfxHelpTextWindow_Impl : public Window { private: ToolBox aToolBox; SfxHelpWindow_Impl* pHelpWin; Window* pTextWin; ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame; sal_Bool bIsDebug; sal_Bool bIsIndexOn; String aIndexOnText; String aIndexOffText; Image aIndexOnImage; Image aIndexOffImage; public: SfxHelpTextWindow_Impl( SfxHelpWindow_Impl* pParent ); ~SfxHelpTextWindow_Impl(); virtual void Resize(); virtual long PreNotify( NotifyEvent& rNEvt ); void SetSelectHdl( const Link& rLink ) { aToolBox.SetSelectHdl( rLink ); } ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > getFrame() const { return xFrame; } void ToggleIndex( sal_Bool bOn ); }; // class SfxHelpWindow_Impl ---------------------------------------------- class HelpInterceptor_Impl; class HelpListener_Impl; class SfxHelpWindow_Impl : public SplitWindow { private: ::com::sun::star::uno::Reference < ::com::sun::star::awt::XWindow > xWindow; ::com::sun::star::uno::Reference < ::com::sun::star::frame::XStatusListener > xOpenListener; SfxHelpIndexWindow_Impl* pIndexWin; SfxHelpTextWindow_Impl* pTextWin; HelpInterceptor_Impl* pHelpInterceptor; HelpListener_Impl* pHelpListener; sal_Int32 nExpandWidth; sal_Int32 nCollapseWidth; sal_Int32 nHeight; long nIndexSize; long nTextSize; sal_Bool bIndex; String aTitle; virtual void Resize(); virtual void Split(); void MakeLayout(); void InitSizes(); void LoadConfig(); void SaveConfig(); void ShowStartPage(); DECL_LINK( SelectHdl, ToolBox* ); DECL_LINK( OpenHdl, SfxHelpIndexWindow_Impl* ); DECL_LINK( SelectFactoryHdl, SfxHelpIndexWindow_Impl* ); DECL_LINK( ChangeHdl, HelpListener_Impl* ); DECL_LINK( OpenDoneHdl, OpenStatusListener_Impl* ); public: SfxHelpWindow_Impl( const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& rFrame, Window* pParent, WinBits nBits ); ~SfxHelpWindow_Impl(); void setContainerWindow( ::com::sun::star::uno::Reference < ::com::sun::star::awt::XWindow > xWin ); void SetFactory( const String& rFactory, sal_Bool bStart ); void SetHelpURL( const String& rURL ); void DoAction( USHORT nActionId ); }; class SfxAddHelpBookmarkDialog_Impl : public ModalDialog { private: FixedText aTitleFT; Edit aTitleED; OKButton aOKBtn; CancelButton aEscBtn; HelpButton aHelpBtn; public: SfxAddHelpBookmarkDialog_Impl( Window* pParent, sal_Bool bRename = sal_True ); ~SfxAddHelpBookmarkDialog_Impl(); void SetTitle( const String& rTitle ); String GetTitle() const { return aTitleED.GetText(); } }; #endif // #ifndef INCLUDED_SFX_NEWHELP_HXX <|endoftext|>
<commit_before>#include "Halide.h" #include <cstdlib> #include <chrono> #include <iostream> #include "configure.h" #include "generated_conv_layer.o.h" #include <tiramisu/utils.h> int main(int, char**) { srand(1); std::vector<double> duration_vector; double start, end; Halide::Buffer<float> input(FIN_BLOCKING, N + 2, N + 2, FIN_NB_BLOCKS, BATCH_SIZE); Halide::Buffer<float> filter(FOUT_BLOCKING, FIN_BLOCKING, K, K, FIN_NB_BLOCKS, FOUT_NB_BLOCKS); Halide::Buffer<float> bias(FOut); Halide::Buffer<float> conv(FOUT_BLOCKING, N, N, FOUT_NB_BLOCKS, BATCH_SIZE); // Initialize buffers for (int n = 0; n < BATCH_SIZE; ++n) for (int fin = 0; fin < FIn; ++fin) for (int y = 0; y < N + 2; ++y) for (int x = 0; x < N + 2; ++x) input(fin%FIN_BLOCKING, x, y, fin/FIN_BLOCKING, n) = ((float)(rand()%256 - 128)) / 127.f; for (int fout = 0; fout < FOut; ++fout) { int zero_weights = 0; for (int fin = 0; fin < FIn; ++fin) { for (int k_y = 0; k_y < K; ++k_y) for (int k_x = 0; k_x < K; ++k_x) { if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0; else filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = ((float)(rand()%256 - 128)) / 127.f; } zero_weights++; } } for (int fout = 0; fout < FOut; ++fout) bias(fout) = ((float)(rand()%256 - 128)) / 127.f; std::cout << "\t\tBuffers initialized" << std::endl; // Execute Tiramisu code for (int i = 0; i < NB_TESTS; i++) { start = rtclock(); conv_tiramisu( input.raw_buffer(), filter.raw_buffer(), bias.raw_buffer(), conv.raw_buffer() ); end = rtclock(); duration_vector.push_back((end - start) * 1000); } std::cout << "\t\tN = " << N << "; BATCH_SIZE = " << BATCH_SIZE << "; FIn = " << FIn << "; FOut = " << FOut << ";" << std::endl; std::cout << "\t\tTiramisu conv" << ": " << median(duration_vector) << "; " << std::endl; // Write results to file FILE* f = fopen("tiramisu_result.txt", "w"); if (f == NULL) { printf("Error creating tiramisu_result.txt.\n"); return 0; } for (int n = 0; n < BATCH_SIZE; ++n) for (int fout = 0; fout < FOut; ++fout) for (int y = 0; y < N; ++y) for (int x = 0; x < N; ++x) fprintf(f, "%.10g\n", conv(fout%FOUT_BLOCKING, x, y, fout/FOUT_BLOCKING, n)); fclose(f); // Compare results with Intel MKL std::ifstream mkl_result("mkl_result.txt"); float tmp; float file_count = 0, corr = 0; for (int n = 0; n < BATCH_SIZE; ++n) for (int fout = 0; fout < FOut; ++fout) for (int y = 0; y < N; ++y) for (int x = 0; x < N; ++x) { mkl_result >> tmp; file_count++; if (std::abs(conv(fout%FOUT_BLOCKING, x, y, fout/FOUT_BLOCKING, n) - tmp) <= 0.0001) corr++; } std::cout << "\t\tResult" << ":\n\n"; std::cout << "\t\tPercentage of correctness " << corr / file_count * 100 << "%" << std::endl << std::endl; return 0; } <commit_msg>Add pattern 0, 1 and 2 to data generation in Tiramisu code<commit_after>#include "Halide.h" #include <cstdlib> #include <chrono> #include <iostream> #include "configure.h" #include "generated_conv_layer.o.h" #include <tiramisu/utils.h> int main(int, char**) { srand(1); std::vector<double> duration_vector; double start, end; Halide::Buffer<float> input(FIN_BLOCKING, N + 2, N + 2, FIN_NB_BLOCKS, BATCH_SIZE); Halide::Buffer<float> filter(FOUT_BLOCKING, FIN_BLOCKING, K, K, FIN_NB_BLOCKS, FOUT_NB_BLOCKS); Halide::Buffer<float> bias(FOut); Halide::Buffer<float> conv(FOUT_BLOCKING, N, N, FOUT_NB_BLOCKS, BATCH_SIZE); // Initialize buffers for (int n = 0; n < BATCH_SIZE; ++n) for (int fin = 0; fin < FIn; ++fin) for (int y = 0; y < N + 2; ++y) for (int x = 0; x < N + 2; ++x) input(fin%FIN_BLOCKING, x, y, fin/FIN_BLOCKING, n) = ((float)(rand()%256 - 128)) / 127.f; for (int fout = 0; fout < FOut; ++fout) { int zero_weights = 0; for (int fin = 0; fin < FIn; ++fin) { for (int k_y = 0; k_y < K; ++k_y) for (int k_x = 0; k_x < K; ++k_x) { if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) { filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0; } else if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) { if (k_y == 0) filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 1; else filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0; } else if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) { if (k_y == 1) filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 1; else filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0; } else if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_2_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) { if (k_y == 2) filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 1; else filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0; } else filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = ((float)(rand()%256 - 128)) / 127.f; } zero_weights++; } } for (int fout = 0; fout < FOut; ++fout) bias(fout) = ((float)(rand()%256 - 128)) / 127.f; std::cout << "\t\tBuffers initialized" << std::endl; // Execute Tiramisu code for (int i = 0; i < NB_TESTS; i++) { start = rtclock(); conv_tiramisu( input.raw_buffer(), filter.raw_buffer(), bias.raw_buffer(), conv.raw_buffer() ); end = rtclock(); duration_vector.push_back((end - start) * 1000); } std::cout << "\t\tN = " << N << "; BATCH_SIZE = " << BATCH_SIZE << "; FIn = " << FIn << "; FOut = " << FOut << ";" << std::endl; std::cout << "\t\tTiramisu conv" << ": " << median(duration_vector) << "; " << std::endl; // Write results to file FILE* f = fopen("tiramisu_result.txt", "w"); if (f == NULL) { printf("Error creating tiramisu_result.txt.\n"); return 0; } for (int n = 0; n < BATCH_SIZE; ++n) for (int fout = 0; fout < FOut; ++fout) for (int y = 0; y < N; ++y) for (int x = 0; x < N; ++x) fprintf(f, "%.10g\n", conv(fout%FOUT_BLOCKING, x, y, fout/FOUT_BLOCKING, n)); fclose(f); // Compare results with Intel MKL std::ifstream mkl_result("mkl_result.txt"); float tmp; float file_count = 0, corr = 0; for (int n = 0; n < BATCH_SIZE; ++n) for (int fout = 0; fout < FOut; ++fout) for (int y = 0; y < N; ++y) for (int x = 0; x < N; ++x) { mkl_result >> tmp; file_count++; if (std::abs(conv(fout%FOUT_BLOCKING, x, y, fout/FOUT_BLOCKING, n) - tmp) <= 0.0001) corr++; } std::cout << "\t\tResult" << ":\n\n"; std::cout << "\t\tPercentage of correctness " << corr / file_count * 100 << "%" << std::endl << std::endl; return 0; } <|endoftext|>
<commit_before>// RUN: %clangxx -O1 %s -o %t && TSAN_OPTIONS="flush_memory_ms=1 memory_limit_mb=1" ASAN_OPTIONS="handle_segv=0 allow_user_segv_handler=1" %run %t 2>&1 | FileCheck %s // JVM uses SEGV to preempt threads. All threads do a load from a known address // periodically. When runtime needs to preempt threads, it unmaps the page. // Threads start triggering SEGV one by one. The signal handler blocks // threads while runtime does its thing. Then runtime maps the page again // and resumes the threads. // Previously this pattern conflicted with stop-the-world machinery, // because it briefly reset SEGV handler to SIG_DFL. // As the consequence JVM just silently died. // This test sets memory flushing rate to maximum, then does series of // "benign" SEGVs that are handled by signal handler, and ensures that // the process survive. #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/mman.h> #include <string.h> void *guard; void handler(int signo, siginfo_t *info, void *uctx) { mprotect(guard, 4096, PROT_READ | PROT_WRITE); } int main() { struct sigaction a, old; memset(&a, 0, sizeof(a)); memset(&old, 0, sizeof(old)); a.sa_sigaction = handler; a.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &a, &old); guard = (char *)mmap(0, 3 * 4096, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0) + 4096; for (int i = 0; i < 1000000; i++) { mprotect(guard, 4096, PROT_NONE); *(int*)guard = 1; } sigaction(SIGSEGV, &old, 0); fprintf(stderr, "DONE\n"); } // CHECK: DONE <commit_msg>asan: fix a test<commit_after>// RUN: %clangxx -O1 %s -o %t && TSAN_OPTIONS="flush_memory_ms=1 memory_limit_mb=1" ASAN_OPTIONS="handle_segv=0 allow_user_segv_handler=1" %run %t 2>&1 | FileCheck %s // JVM uses SEGV to preempt threads. All threads do a load from a known address // periodically. When runtime needs to preempt threads, it unmaps the page. // Threads start triggering SEGV one by one. The signal handler blocks // threads while runtime does its thing. Then runtime maps the page again // and resumes the threads. // Previously this pattern conflicted with stop-the-world machinery, // because it briefly reset SEGV handler to SIG_DFL. // As the consequence JVM just silently died. // This test sets memory flushing rate to maximum, then does series of // "benign" SEGVs that are handled by signal handler, and ensures that // the process survive. #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/mman.h> #include <string.h> #include <unistd.h> unsigned long page_size; void *guard; void handler(int signo, siginfo_t *info, void *uctx) { mprotect(guard, page_size, PROT_READ | PROT_WRITE); } int main() { page_size = sysconf(_SC_PAGESIZE); struct sigaction a, old; memset(&a, 0, sizeof(a)); memset(&old, 0, sizeof(old)); a.sa_sigaction = handler; a.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &a, &old); guard = mmap(0, 3 * page_size, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0); guard = (char*)guard + page_size; // work around a kernel bug for (int i = 0; i < 1000000; i++) { mprotect(guard, page_size, PROT_NONE); *(int*)guard = 1; } sigaction(SIGSEGV, &old, 0); fprintf(stderr, "DONE\n"); } // CHECK: DONE <|endoftext|>
<commit_before>//===- Chunks.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Chunks.h" #include "InputFiles.h" #include "Writer.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Object/COFF.h" #include "llvm/Support/COFF.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace llvm::object; using namespace llvm::support::endian; using namespace llvm::COFF; using llvm::RoundUpToAlignment; namespace lld { namespace coff { SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H, uint32_t SI) : File(F), Header(H), SectionIndex(SI) { // Initialize SectionName. File->getCOFFObj()->getSectionName(Header, SectionName); // Bit [20:24] contains section alignment. unsigned Shift = ((Header->Characteristics & 0xF00000) >> 20) - 1; Align = uint32_t(1) << Shift; } void SectionChunk::writeTo(uint8_t *Buf) { if (!hasData()) return; // Copy section contents from source object file to output file. ArrayRef<uint8_t> Data; File->getCOFFObj()->getSectionContents(Header, Data); memcpy(Buf + FileOff, Data.data(), Data.size()); // Apply relocations. for (const auto &I : getSectionRef().relocations()) { const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I); applyReloc(Buf, Rel); } } // Returns true if this chunk should be considered as a GC root. bool SectionChunk::isRoot() { // COMDAT sections are live only when they are referenced by something else. if (isCOMDAT()) return false; // Associative sections are live if their parent COMDATs are live, // and vice versa, so they are not considered live by themselves. if (IsAssocChild) return false; // Only code is subject of dead-stripping. return !(Header->Characteristics & IMAGE_SCN_CNT_CODE); } void SectionChunk::markLive() { if (Live) return; Live = true; // Mark all symbols listed in the relocation table for this section. for (const auto &I : getSectionRef().relocations()) { const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I); SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex); if (auto *Def = dyn_cast<Defined>(B)) Def->markLive(); } // Mark associative sections if any. for (Chunk *C : AssocChildren) C->markLive(); } void SectionChunk::addAssociative(SectionChunk *Child) { Child->IsAssocChild = true; AssocChildren.push_back(Child); } static void add16(uint8_t *P, int32_t V) { write16le(P, read16le(P) + V); } static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); } static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); } // Implements x64 PE/COFF relocations. void SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) { uint8_t *Off = Buf + FileOff + Rel->VirtualAddress; SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex); uint64_t S = cast<Defined>(Body)->getRVA(); uint64_t P = RVA + Rel->VirtualAddress; switch (Rel->Type) { case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break; case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break; case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break; case IMAGE_REL_AMD64_REL32: add32(Off, S - P - 4); break; case IMAGE_REL_AMD64_REL32_1: add32(Off, S - P - 5); break; case IMAGE_REL_AMD64_REL32_2: add32(Off, S - P - 6); break; case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break; case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break; case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break; case IMAGE_REL_AMD64_SECTION: add16(Off, Out->getSectionIndex()); break; case IMAGE_REL_AMD64_SECREL: add32(Off, S - Out->getRVA()); break; default: llvm::report_fatal_error("Unsupported relocation type"); } } bool SectionChunk::hasData() const { return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA); } uint32_t SectionChunk::getPermissions() const { return Header->Characteristics & PermMask; } bool SectionChunk::isCOMDAT() const { return Header->Characteristics & IMAGE_SCN_LNK_COMDAT; } // Prints "Discarded <symbol>" for all external function symbols. void SectionChunk::printDiscardedMessage() { uint32_t E = File->getCOFFObj()->getNumberOfSymbols(); for (uint32_t I = 0; I < E; ++I) { auto SrefOrErr = File->getCOFFObj()->getSymbol(I); COFFSymbolRef Sym = SrefOrErr.get(); if (uint32_t(Sym.getSectionNumber()) != SectionIndex) continue; if (!Sym.isFunctionDefinition()) continue; StringRef SymbolName; File->getCOFFObj()->getSymbolName(Sym, SymbolName); llvm::dbgs() << "Discarded " << SymbolName << " from " << File->getShortName() << "\n"; I += Sym.getNumberOfAuxSymbols(); } } SectionRef SectionChunk::getSectionRef() { DataRefImpl Ref; Ref.p = uintptr_t(Header); return SectionRef(Ref, File->getCOFFObj()); } uint32_t CommonChunk::getPermissions() const { return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE; } void StringChunk::writeTo(uint8_t *Buf) { memcpy(Buf + FileOff, Str.data(), Str.size()); } void ImportThunkChunk::writeTo(uint8_t *Buf) { memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData)); // The first two bytes is a JMP instruction. Fill its operand. uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize(); write32le(Buf + FileOff + 2, Operand); } } // namespace coff } // namespace lld <commit_msg>COFF: Fix typo.<commit_after>//===- Chunks.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Chunks.h" #include "InputFiles.h" #include "Writer.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Object/COFF.h" #include "llvm/Support/COFF.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace llvm::object; using namespace llvm::support::endian; using namespace llvm::COFF; using llvm::RoundUpToAlignment; namespace lld { namespace coff { SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H, uint32_t SI) : File(F), Header(H), SectionIndex(SI) { // Initialize SectionName. File->getCOFFObj()->getSectionName(Header, SectionName); // Bit [20:24] contains section alignment. unsigned Shift = ((Header->Characteristics & 0xF00000) >> 20) - 1; Align = uint32_t(1) << Shift; } void SectionChunk::writeTo(uint8_t *Buf) { if (!hasData()) return; // Copy section contents from source object file to output file. ArrayRef<uint8_t> Data; File->getCOFFObj()->getSectionContents(Header, Data); memcpy(Buf + FileOff, Data.data(), Data.size()); // Apply relocations. for (const auto &I : getSectionRef().relocations()) { const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I); applyReloc(Buf, Rel); } } // Returns true if this chunk should be considered as a GC root. bool SectionChunk::isRoot() { // COMDAT sections are live only when they are referenced by something else. if (isCOMDAT()) return false; // Associative sections are live if their parent COMDATs are live, // and vice versa, so they are not considered live by themselves. if (IsAssocChild) return false; // Only code is subject of dead-stripping. return !(Header->Characteristics & IMAGE_SCN_CNT_CODE); } void SectionChunk::markLive() { if (Live) return; Live = true; // Mark all symbols listed in the relocation table for this section. for (const auto &I : getSectionRef().relocations()) { const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I); SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex); if (auto *Def = dyn_cast<Defined>(B)) Def->markLive(); } // Mark associative sections if any. for (Chunk *C : AssocChildren) C->markLive(); } void SectionChunk::addAssociative(SectionChunk *Child) { Child->IsAssocChild = true; AssocChildren.push_back(Child); } static void add16(uint8_t *P, int16_t V) { write16le(P, read16le(P) + V); } static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); } static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); } // Implements x64 PE/COFF relocations. void SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) { uint8_t *Off = Buf + FileOff + Rel->VirtualAddress; SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex); uint64_t S = cast<Defined>(Body)->getRVA(); uint64_t P = RVA + Rel->VirtualAddress; switch (Rel->Type) { case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break; case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break; case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break; case IMAGE_REL_AMD64_REL32: add32(Off, S - P - 4); break; case IMAGE_REL_AMD64_REL32_1: add32(Off, S - P - 5); break; case IMAGE_REL_AMD64_REL32_2: add32(Off, S - P - 6); break; case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break; case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break; case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break; case IMAGE_REL_AMD64_SECTION: add16(Off, Out->getSectionIndex()); break; case IMAGE_REL_AMD64_SECREL: add32(Off, S - Out->getRVA()); break; default: llvm::report_fatal_error("Unsupported relocation type"); } } bool SectionChunk::hasData() const { return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA); } uint32_t SectionChunk::getPermissions() const { return Header->Characteristics & PermMask; } bool SectionChunk::isCOMDAT() const { return Header->Characteristics & IMAGE_SCN_LNK_COMDAT; } // Prints "Discarded <symbol>" for all external function symbols. void SectionChunk::printDiscardedMessage() { uint32_t E = File->getCOFFObj()->getNumberOfSymbols(); for (uint32_t I = 0; I < E; ++I) { auto SrefOrErr = File->getCOFFObj()->getSymbol(I); COFFSymbolRef Sym = SrefOrErr.get(); if (uint32_t(Sym.getSectionNumber()) != SectionIndex) continue; if (!Sym.isFunctionDefinition()) continue; StringRef SymbolName; File->getCOFFObj()->getSymbolName(Sym, SymbolName); llvm::dbgs() << "Discarded " << SymbolName << " from " << File->getShortName() << "\n"; I += Sym.getNumberOfAuxSymbols(); } } SectionRef SectionChunk::getSectionRef() { DataRefImpl Ref; Ref.p = uintptr_t(Header); return SectionRef(Ref, File->getCOFFObj()); } uint32_t CommonChunk::getPermissions() const { return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE; } void StringChunk::writeTo(uint8_t *Buf) { memcpy(Buf + FileOff, Str.data(), Str.size()); } void ImportThunkChunk::writeTo(uint8_t *Buf) { memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData)); // The first two bytes is a JMP instruction. Fill its operand. uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize(); write32le(Buf + FileOff + 2, Operand); } } // namespace coff } // namespace lld <|endoftext|>
<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "manager.h" #include <my_global.h> #include <signal.h> #include "thread_repository.h" #include "listener.h" #include "log.h" void manager(const char *socket_file_name) { Thread_repository thread_repository; Listener_thread_args listener_args(thread_repository, socket_file_name); /* write pid file */ /* block signals */ sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); sigaddset(&mask, SIGHUP); /* all new threads will inherite this signal mask */ pthread_sigmask(SIG_BLOCK, &mask, NULL); { /* create the listener */ pthread_t listener_thd_id; pthread_attr_t listener_thd_attr; pthread_attr_init(&listener_thd_attr); pthread_attr_setdetachstate(&listener_thd_attr, PTHREAD_CREATE_DETACHED); if (pthread_create(&listener_thd_id, &listener_thd_attr, listener, &listener_args)) die("manager(): pthread_create(listener) failed"); } /* To work nicely with LinuxThreads, the signal thread is the first thread in the process. */ int signo; sigwait(&mask, &signo); thread_repository.deliver_shutdown(); /* don't pthread_exit to kill all threads who did not shut down in time */ } <commit_msg>Fix for the unixware: non-posix sigwait<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "manager.h" #include <my_global.h> #include <signal.h> #include "thread_repository.h" #include "listener.h" #include "log.h" void manager(const char *socket_file_name) { Thread_repository thread_repository; Listener_thread_args listener_args(thread_repository, socket_file_name); /* write pid file */ /* block signals */ sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); sigaddset(&mask, SIGHUP); /* all new threads will inherite this signal mask */ pthread_sigmask(SIG_BLOCK, &mask, NULL); { /* create the listener */ pthread_t listener_thd_id; pthread_attr_t listener_thd_attr; pthread_attr_init(&listener_thd_attr); pthread_attr_setdetachstate(&listener_thd_attr, PTHREAD_CREATE_DETACHED); if (pthread_create(&listener_thd_id, &listener_thd_attr, listener, &listener_args)) die("manager(): pthread_create(listener) failed"); } /* To work nicely with LinuxThreads, the signal thread is the first thread in the process. */ int signo; my_sigwait(&mask, &signo); thread_repository.deliver_shutdown(); /* don't pthread_exit to kill all threads who did not shut down in time */ } <|endoftext|>
<commit_before>/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <QtTest/QtTest> #include <QtCore> #include "fileutils.h" #include "infocdbbackend.h" #include "cdbwriter.h" class InfoCdbBackendUnitTest : public QObject { Q_OBJECT InfoCdbBackend *backend; private slots: void initTestCase(); void listKeys(); void listPlugins(); void listKeysForPlugin(); }; void InfoCdbBackendUnitTest::initTestCase() { // FIXME: LOCAL_DIR CDBWriter writer("cache.cdb"); writer.add("KEYS", "Battery.Charging"); writer.add("KEYS", "Internet.BytesOut"); writer.add("PLUGINS", "contextkit-dbus"); writer.add("contextkit-dbus:KEYS", "Battery.Charging"); writer.add("contextkit-dbus:KEYS", "Battery.BytesOut"); writer.close(); utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR); utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null"); backend = new InfoCdbBackend(); } void InfoCdbBackendUnitTest::listKeys() { QStringList keys = backend->listKeys(); QCOMPARE(keys.count(), 2); QVERIFY(keys.contains("Battery.Charging")); QVERIFY(keys.contains("Internet.BytesOut")); } void InfoCdbBackendUnitTest::listPlugins() { QStringList plugins = backend->listPlugins(); QCOMPARE(plugins.count(), 1); QVERIFY(plugins.contains("contextkit-dbus")); } void InfoCdbBackendUnitTest::listKeysForPlugin() { QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus"); QCOMPARE(keys1.count(), 2); QVERIFY(keys1.contains("Battery.Charging")); QVERIFY(keys1.contains("Internet.BytesOut")); QStringList keys2 = backend->listKeysForPlugin("non-existant"); QCOMPARE(keys2.count(), 1); } #include "infocdbbackendunittest.moc" QTEST_MAIN(InfoCdbBackendUnitTest); <commit_msg>typeForKey.<commit_after>/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <QtTest/QtTest> #include <QtCore> #include "fileutils.h" #include "infocdbbackend.h" #include "cdbwriter.h" class InfoCdbBackendUnitTest : public QObject { Q_OBJECT InfoCdbBackend *backend; private slots: void initTestCase(); void listKeys(); void listPlugins(); void listKeysForPlugin(); void typeForKey(); }; void InfoCdbBackendUnitTest::initTestCase() { // FIXME: LOCAL_DIR CDBWriter writer("cache.cdb"); writer.add("KEYS", "Battery.Charging"); writer.add("KEYS", "Internet.BytesOut"); writer.add("PLUGINS", "contextkit-dbus"); writer.add("contextkit-dbus:KEYS", "Battery.Charging"); writer.add("contextkit-dbus:KEYS", "Internet.BytesOut"); writer.add("Battery.Charging:TYPE", "TRUTH"); writer.add("Internet.BytesOut:TYPE", "INTEGER"); writer.close(); utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR); utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null"); backend = new InfoCdbBackend(); } void InfoCdbBackendUnitTest::listKeys() { QStringList keys = backend->listKeys(); QCOMPARE(keys.count(), 2); QVERIFY(keys.contains("Battery.Charging")); QVERIFY(keys.contains("Internet.BytesOut")); } void InfoCdbBackendUnitTest::listPlugins() { QStringList plugins = backend->listPlugins(); QCOMPARE(plugins.count(), 1); QVERIFY(plugins.contains("contextkit-dbus")); } void InfoCdbBackendUnitTest::listKeysForPlugin() { QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus"); QCOMPARE(keys1.count(), 2); QVERIFY(keys1.contains("Battery.Charging")); QVERIFY(keys1.contains("Internet.BytesOut")); QStringList keys2 = backend->listKeysForPlugin("non-existant"); QCOMPARE(keys2.count(), 1); } void InfoCdbBackendUnitTest::typeForKey() { QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER")); QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString()); } #include "infocdbbackendunittest.moc" QTEST_MAIN(InfoCdbBackendUnitTest); <|endoftext|>
<commit_before>/***************************************************************************************[System.cc] Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson 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 "utils/System.h" #if defined(__linux__) #include <stdio.h> #include <stdlib.h> using namespace Minisat; // TODO: split the memory reading functions into two: one for reading high-watermark of RSS, and // one for reading the current virtual memory size. static inline int memReadStat(int field) { char name[256]; pid_t pid = getpid(); int value; sprintf(name, "/proc/%d/statm", pid); FILE* in = fopen(name, "rb"); if (in == NULL) return 0; for (; field >= 0; field--) if (fscanf(in, "%d", &value) != 1) printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1); fclose(in); return value; } static inline int memReadPeak(void) { char name[256]; pid_t pid = getpid(); sprintf(name, "/proc/%d/status", pid); FILE* in = fopen(name, "rb"); if (in == NULL) return 0; // Find the correct line, beginning with "VmPeak:": int peak_kb = 0; while (!feof(in) && fscanf(in, "VmPeak: %d kB", &peak_kb) != 1) while (!feof(in) && fgetc(in) != '\n') ; fclose(in); return peak_kb; } double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); } double Minisat::memUsedPeak() { double peak = memReadPeak() / 1024; return peak == 0 ? memUsed() : peak; } #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__gnu_hurd__) double Minisat::memUsed(void) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return (double)ru.ru_maxrss / 1024; } double Minisat::memUsedPeak(void) { return memUsed(); } #elif defined(__APPLE__) #include <malloc/malloc.h> double Minisat::memUsed(void) { malloc_statistics_t t; malloc_zone_statistics(NULL, &t); return (double)t.max_size_in_use / (1024*1024); } #else double Minisat::memUsed() { return 0; } #endif <commit_msg>Fix build and minor cleanup of System module.<commit_after>/***************************************************************************************[System.cc] Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson 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 "utils/System.h" #if defined(__linux__) #include <stdio.h> #include <stdlib.h> using namespace Minisat; static inline int memReadStat(int field) { char name[256]; pid_t pid = getpid(); int value; sprintf(name, "/proc/%d/statm", pid); FILE* in = fopen(name, "rb"); if (in == NULL) return 0; for (; field >= 0; field--) if (fscanf(in, "%d", &value) != 1) printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1); fclose(in); return value; } static inline int memReadPeak(void) { char name[256]; pid_t pid = getpid(); sprintf(name, "/proc/%d/status", pid); FILE* in = fopen(name, "rb"); if (in == NULL) return 0; // Find the correct line, beginning with "VmPeak:": int peak_kb = 0; while (!feof(in) && fscanf(in, "VmPeak: %d kB", &peak_kb) != 1) while (!feof(in) && fgetc(in) != '\n') ; fclose(in); return peak_kb; } double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); } double Minisat::memUsedPeak() { double peak = memReadPeak() / 1024; return peak == 0 ? memUsed() : peak; } #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__gnu_hurd__) double Minisat::memUsed() { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return (double)ru.ru_maxrss / 1024; } double Minisat::memUsedPeak() { return memUsed(); } #elif defined(__APPLE__) #include <malloc/malloc.h> double Minisat::memUsed() { malloc_statistics_t t; malloc_zone_statistics(NULL, &t); return (double)t.max_size_in_use / (1024*1024); } double Minisat::memUsedPeak() { return memUsed(); } #else double Minisat::memUsed() { return 0; } double Minisat::memUsedPeak() { return 0; } #endif <|endoftext|>
<commit_before>/*! * \file ak47_HardwareSerial.hpp * \author Francois Best * \date 16/06/2012 * \license GPL v3.0 - Copyright Forty Seven Effects 2012 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: http://www.gnu.org/licenses */ #pragma once BEGIN_AK47_NAMESPACE // ----------------------------------------------------------------------------- // Macros #define UBBR_VALUE(baud) (( (F_CPU) / 16 + (baud) / 2) / (baud) - 1) #define UART_OPEN_IMPL(uart, baud) \ template<> \ template<> \ inline void Uart<uart>::open<baud>() \ { \ /* Compute baud rate */ \ UBRR##uart##H = UBBR_VALUE(baud) >> 8; \ UBRR##uart##L = UBBR_VALUE(baud) & 0xFF; \ \ UCSR##uart##A = 0x00; \ UCSR##uart##B = (1 << RXEN##uart) /* Enable RX */ \ | (1 << TXEN##uart) /* Enable TX */ \ | (1 << RXCIE##uart); /* Enable RX Interrupt */ \ /* TX Interrupt will be enabled when data needs sending. */ \ \ /* Defaults to 8-bit, no parity, 1 stop bit */ \ UCSR##uart##C = (1 << UCSZ##uart##1) | (1 << UCSZ##uart##0); \ } #define UART_IMPLEMENT_OPEN(uart) \ UART_OPEN_IMPL(uart, 4800) \ UART_OPEN_IMPL(uart, 9600) \ UART_OPEN_IMPL(uart, 14400) \ UART_OPEN_IMPL(uart, 19200) \ UART_OPEN_IMPL(uart, 28800) \ UART_OPEN_IMPL(uart, 31250) \ UART_OPEN_IMPL(uart, 38400) \ UART_OPEN_IMPL(uart, 57600) \ UART_OPEN_IMPL(uart, 76800) \ UART_OPEN_IMPL(uart, 115200) \ UART_OPEN_IMPL(uart, 230400) \ UART_OPEN_IMPL(uart, 250000) \ UART_OPEN_IMPL(uart, 500000) \ UART_OPEN_IMPL(uart, 1000000) #define UART_ENABLE_TX_INT(uart) UCSR##uart##B |= (1 << UDRIE##uart) #define UART_DISABLE_TX_INT(uart) UCSR##uart##B &= ~(1 << UDRIE##uart) // ----------------------------------------------------------------------------- template<byte UartNumber> inline Uart<UartNumber>::Uart() { } template<byte UartNumber> inline Uart<UartNumber>::~Uart() { } // ----------------------------------------------------------------------------- #ifdef UART0 UART_IMPLEMENT_OPEN(0); #endif #ifdef UART1 UART_IMPLEMENT_OPEN(1); #endif #ifdef UART2 UART_IMPLEMENT_OPEN(2); #endif #ifdef UART3 UART_IMPLEMENT_OPEN(3); #endif // ----------------------------------------------------------------------------- #ifdef UART0 template<> inline void Uart<0>::close() { UCSR0B = 0x00; } #endif #ifdef UART1 template<> inline void Uart<1>::close() { UCSR1B = 0x00; } #endif #ifdef UART2 template<> inline void Uart<2>::close() { UCSR2B = 0x00; } #endif #ifdef UART3 template<> inline void Uart<3>::close() { UCSR3B = 0x00; } #endif // ----------------------------------------------------------------------------- template<byte UartNumber> inline bool Uart<UartNumber>::available() const { return !(mRxBuffer.empty()); } template<byte UartNumber> inline byte Uart<UartNumber>::read() { if (!mRxBuffer.empty()) return mRxBuffer.pop(); return 0xFF; } // ----------------------------------------------------------------------------- #ifdef UART0 template<> inline void Uart<0>::write(byte inData) { UART_DISABLE_TX_INT(0); mTxBuffer.push(inData); UART_ENABLE_TX_INT(0); } #endif #ifdef UART1 template<> inline void Uart<1>::write(byte inData) { UART_DISABLE_TX_INT(1); mTxBuffer.push(inData); UART_ENABLE_TX_INT(1); } #endif #ifdef UART2 template<> inline void Uart<2>::write(byte inData) { UART_DISABLE_TX_INT(2); mTxBuffer.push(inData); UART_ENABLE_TX_INT(2); } #endif #ifdef UART3 template<> inline void Uart<3>::write(byte inData) { UART_DISABLE_TX_INT(3); mTxBuffer.push(inData); UART_ENABLE_TX_INT(3); } #endif template<byte UartNumber> inline void Uart<UartNumber>::write(const byte* inData, unsigned inSize) { for (unsigned i = 0; i < inSize; ++i) { write(inData[i]); } } // ----------------------------------------------------------------------------- #ifdef UART0 template<> inline void Uart<0>::busyWrite(byte inData) { UDR0 = inData; while (!(UCSR0A & (1 << UDRE0))); } #endif #ifdef UART1 template<> inline void Uart<1>::busyWrite(byte inData) { UDR1 = inData; while (!(UCSR1A & (1 << UDRE1))); } #endif #ifdef UART2 template<> inline void Uart<2>::busyWrite(byte inData) { UDR2 = inData; while (!(UCSR2A & (1 << UDRE2))); } #endif #ifdef UART3 template<> inline void Uart<3>::busyWrite(byte inData) { UDR3 = inData; while (!(UCSR3A & (1 << UDRE3))); } #endif /*! \brief Write data and wait until end of transmission. Unlike write, this method will wait for each byte to be transmitted to send the next one. It does not use the TX buffer, allowing large amounts of data to be sent without the need of a big TX buffer size. */ template<byte UartNumber> inline void Uart<UartNumber>::busyWrite(const byte* inData, unsigned inSize) { for (unsigned i = 0; i < inSize; ++i) { busyWrite(inData[i]); } } // ----------------------------------------------------------------------------- template<byte UartNumber> inline void Uart<UartNumber>::clearRxBuffer() { mRxBuffer.clear(); } template<byte UartNumber> inline void Uart<UartNumber>::clearTxBuffer() { mTxBuffer.clear(); } // ----------------------------------------------------------------------------- template<byte UartNumber> inline void Uart<UartNumber>::handleByteReceived(byte inData) { mRxBuffer.push(inData); } // ----------------------------------------------------------------------------- #ifdef UART0 template<> inline void Uart<0>::handleTxReady() { if (!mTxBuffer.empty()) { UDR0 = mTxBuffer.pop(); } else { // No more data to be sent, disable TX interrupt. UART_DISABLE_TX_INT(0); } } #endif #ifdef UART1 template<> inline void Uart<1>::handleTxReady() { if (!mTxBuffer.empty()) { UDR1 = mTxBuffer.pop(); } else { // No more data to be sent, disable TX interrupt. UART_DISABLE_TX_INT(1); } } #endif #ifdef UART2 template<> inline void Uart<2>::handleTxReady() { if (!mTxBuffer.empty()) { UDR2 = mTxBuffer.pop(); } else { // No more data to be sent, disable TX interrupt. UART_DISABLE_TX_INT(2); } } #endif #ifdef UART3 template<> inline void Uart<3>::handleTxReady() { if (!mTxBuffer.empty()) { UDR3 = mTxBuffer.pop(); } else { // No more data to be sent, disable TX interrupt. UART_DISABLE_TX_INT(3); } } #endif // ----------------------------------------------------------------------------- #undef UART_OPEN_IMPL #undef UART_IMPLEMENT_OPEN #undef UBBR_VALUE #undef UART_ENABLE_TX_INT #undef UART_DISABLE_TX_INT END_AK47_NAMESPACE <commit_msg>Some UARTs need interrupts to be off when initializing.<commit_after>/*! * \file ak47_HardwareSerial.hpp * \author Francois Best * \date 16/06/2012 * \license GPL v3.0 - Copyright Forty Seven Effects 2012 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: http://www.gnu.org/licenses */ #pragma once BEGIN_AK47_NAMESPACE // ----------------------------------------------------------------------------- // Macros #define UBBR_VALUE(baud) (( (F_CPU) / 16 + (baud) / 2) / (baud) - 1) #define UART_OPEN_IMPL(uart, baud) \ template<> \ template<> \ inline void Uart<uart>::open<baud>() \ { \ cli(); \ /* Compute baud rate */ \ UBRR##uart##H = UBBR_VALUE(baud) >> 8; \ UBRR##uart##L = UBBR_VALUE(baud) & 0xFF; \ \ UCSR##uart##A = 0x00; \ UCSR##uart##B = (1 << RXEN##uart) /* Enable RX */ \ | (1 << TXEN##uart) /* Enable TX */ \ | (1 << RXCIE##uart); /* Enable RX Interrupt */ \ /* TX Interrupt will be enabled when data needs sending. */ \ \ /* Defaults to 8-bit, no parity, 1 stop bit */ \ UCSR##uart##C = (1 << UCSZ##uart##1) | (1 << UCSZ##uart##0); \ sei(); \ } #define UART_IMPLEMENT_OPEN(uart) \ UART_OPEN_IMPL(uart, 4800) \ UART_OPEN_IMPL(uart, 9600) \ UART_OPEN_IMPL(uart, 14400) \ UART_OPEN_IMPL(uart, 19200) \ UART_OPEN_IMPL(uart, 28800) \ UART_OPEN_IMPL(uart, 31250) \ UART_OPEN_IMPL(uart, 38400) \ UART_OPEN_IMPL(uart, 57600) \ UART_OPEN_IMPL(uart, 76800) \ UART_OPEN_IMPL(uart, 115200) \ UART_OPEN_IMPL(uart, 230400) \ UART_OPEN_IMPL(uart, 250000) \ UART_OPEN_IMPL(uart, 500000) \ UART_OPEN_IMPL(uart, 1000000) #define UART_ENABLE_TX_INT(uart) UCSR##uart##B |= (1 << UDRIE##uart) #define UART_DISABLE_TX_INT(uart) UCSR##uart##B &= ~(1 << UDRIE##uart) // ----------------------------------------------------------------------------- template<byte UartNumber> inline Uart<UartNumber>::Uart() { } template<byte UartNumber> inline Uart<UartNumber>::~Uart() { } // ----------------------------------------------------------------------------- #ifdef UART0 UART_IMPLEMENT_OPEN(0); #endif #ifdef UART1 UART_IMPLEMENT_OPEN(1); #endif #ifdef UART2 UART_IMPLEMENT_OPEN(2); #endif #ifdef UART3 UART_IMPLEMENT_OPEN(3); #endif // ----------------------------------------------------------------------------- #ifdef UART0 template<> inline void Uart<0>::close() { UCSR0B = 0x00; } #endif #ifdef UART1 template<> inline void Uart<1>::close() { UCSR1B = 0x00; } #endif #ifdef UART2 template<> inline void Uart<2>::close() { UCSR2B = 0x00; } #endif #ifdef UART3 template<> inline void Uart<3>::close() { UCSR3B = 0x00; } #endif // ----------------------------------------------------------------------------- template<byte UartNumber> inline bool Uart<UartNumber>::available() const { return !(mRxBuffer.empty()); } template<byte UartNumber> inline byte Uart<UartNumber>::read() { if (!mRxBuffer.empty()) return mRxBuffer.pop(); return 0xFF; } // ----------------------------------------------------------------------------- #ifdef UART0 template<> inline void Uart<0>::write(byte inData) { UART_DISABLE_TX_INT(0); mTxBuffer.push(inData); UART_ENABLE_TX_INT(0); } #endif #ifdef UART1 template<> inline void Uart<1>::write(byte inData) { UART_DISABLE_TX_INT(1); mTxBuffer.push(inData); UART_ENABLE_TX_INT(1); } #endif #ifdef UART2 template<> inline void Uart<2>::write(byte inData) { UART_DISABLE_TX_INT(2); mTxBuffer.push(inData); UART_ENABLE_TX_INT(2); } #endif #ifdef UART3 template<> inline void Uart<3>::write(byte inData) { UART_DISABLE_TX_INT(3); mTxBuffer.push(inData); UART_ENABLE_TX_INT(3); } #endif template<byte UartNumber> inline void Uart<UartNumber>::write(const byte* inData, unsigned inSize) { for (unsigned i = 0; i < inSize; ++i) { write(inData[i]); } } // ----------------------------------------------------------------------------- #ifdef UART0 template<> inline void Uart<0>::busyWrite(byte inData) { UDR0 = inData; while (!(UCSR0A & (1 << UDRE0))); } #endif #ifdef UART1 template<> inline void Uart<1>::busyWrite(byte inData) { UDR1 = inData; while (!(UCSR1A & (1 << UDRE1))); } #endif #ifdef UART2 template<> inline void Uart<2>::busyWrite(byte inData) { UDR2 = inData; while (!(UCSR2A & (1 << UDRE2))); } #endif #ifdef UART3 template<> inline void Uart<3>::busyWrite(byte inData) { UDR3 = inData; while (!(UCSR3A & (1 << UDRE3))); } #endif /*! \brief Write data and wait until end of transmission. Unlike write, this method will wait for each byte to be transmitted to send the next one. It does not use the TX buffer, allowing large amounts of data to be sent without the need of a big TX buffer size. */ template<byte UartNumber> inline void Uart<UartNumber>::busyWrite(const byte* inData, unsigned inSize) { for (unsigned i = 0; i < inSize; ++i) { busyWrite(inData[i]); } } // ----------------------------------------------------------------------------- template<byte UartNumber> inline void Uart<UartNumber>::clearRxBuffer() { mRxBuffer.clear(); } template<byte UartNumber> inline void Uart<UartNumber>::clearTxBuffer() { mTxBuffer.clear(); } // ----------------------------------------------------------------------------- template<byte UartNumber> inline void Uart<UartNumber>::handleByteReceived(byte inData) { mRxBuffer.push(inData); } // ----------------------------------------------------------------------------- #ifdef UART0 template<> inline void Uart<0>::handleTxReady() { if (!mTxBuffer.empty()) { UDR0 = mTxBuffer.pop(); } else { // No more data to be sent, disable TX interrupt. UART_DISABLE_TX_INT(0); } } #endif #ifdef UART1 template<> inline void Uart<1>::handleTxReady() { if (!mTxBuffer.empty()) { UDR1 = mTxBuffer.pop(); } else { // No more data to be sent, disable TX interrupt. UART_DISABLE_TX_INT(1); } } #endif #ifdef UART2 template<> inline void Uart<2>::handleTxReady() { if (!mTxBuffer.empty()) { UDR2 = mTxBuffer.pop(); } else { // No more data to be sent, disable TX interrupt. UART_DISABLE_TX_INT(2); } } #endif #ifdef UART3 template<> inline void Uart<3>::handleTxReady() { if (!mTxBuffer.empty()) { UDR3 = mTxBuffer.pop(); } else { // No more data to be sent, disable TX interrupt. UART_DISABLE_TX_INT(3); } } #endif // ----------------------------------------------------------------------------- #undef UART_OPEN_IMPL #undef UART_IMPLEMENT_OPEN #undef UBBR_VALUE #undef UART_ENABLE_TX_INT #undef UART_DISABLE_TX_INT END_AK47_NAMESPACE <|endoftext|>
<commit_before>#include "lib/armv7m/crt0.h" #include "lib/armv7m/exception_table.h" #include "lib/armv7m/instructions.h" #include "lib/armv7m/scb.h" #include "runtime/ramcode.h" #include "vga/graphics_1.h" #include "vga/timing.h" #include "vga/vga.h" #include "vga/rast/bitmap_1.h" #include "vga/rast/text_10x16.h" using vga::rast::Bitmap_1; typedef vga::Rasterizer::Pixel Pixel; /******************************************************************************* * Screen partitioning */ static constexpr unsigned text_cols = 800; static constexpr unsigned text_rows = 16 * 16; static constexpr unsigned gfx_cols = 800; static constexpr unsigned gfx_rows = 600 - text_rows; /******************************************************************************* * The Graphics Parts */ static Bitmap_1 gfx_rast(gfx_cols, gfx_rows); static void set_ball(vga::Graphics1 &g, unsigned x, unsigned y) { g.set_pixel(x, y); g.set_pixel(x - 1, y); g.set_pixel(x + 1, y); g.set_pixel(x, y - 1); g.set_pixel(x, y + 1); } static void clear_ball(vga::Graphics1 &g, unsigned x, unsigned y) { g.clear_pixel(x, y); g.clear_pixel(x - 1, y); g.clear_pixel(x + 1, y); g.clear_pixel(x, y - 1); g.clear_pixel(x, y + 1); } static void step_ball(int &x, int &y, int other_x, int other_y, int &xi, int &yi) { vga::Graphics1 g = gfx_rast.make_bg_graphics(); clear_ball(g, x, y); x = other_x + xi; y = other_y + yi; if (x < 0) { x = 0; xi = -xi; } if (y < 0) { y = 0; yi = -yi; } if (x >= static_cast<int>(gfx_cols)) { x = gfx_cols - 1; xi = -xi; } if (y >= static_cast<int>(gfx_rows)) { y = gfx_rows - 1; yi = -yi; } set_ball(g, x, y); ++yi; } /******************************************************************************* * The Text Parts */ static vga::rast::Text_10x16 text_rast(text_cols, text_rows, gfx_rows); static constexpr unsigned t_right_margin = (text_cols + 9) / 10; static constexpr unsigned t_bottom_margin = (text_rows + 15) / 16; static unsigned t_row = 0, t_col = 0; static void type_raw(Pixel fore, Pixel back, char c) { text_rast.put_char(t_col, t_row, fore, back, c); ++t_col; if (t_col == t_right_margin) { t_col = 0; ++t_row; if (t_row == t_bottom_margin) t_row = 0; } } static void type(Pixel fore, Pixel back, char c) { switch (c) { case '\n': do { type_raw(fore, back, ' '); } while (t_col); return; default: type_raw(fore, back, c); return; } } static void type(Pixel fore, Pixel back, char const *s) { while (char c = *s++) { type(fore, back, c); } } static void rainbow_type(char const *s) { unsigned x = 0; while (char c = *s++) { type(x & 0b111111, ~x & 0b111111, c); ++x; } } static void cursor_to(unsigned col, unsigned row) { if (col >= t_right_margin) col = t_right_margin - 1; if (row >= t_bottom_margin) row = t_bottom_margin - 1; t_col = col; t_row = row; } static void text_at(unsigned col, unsigned row, Pixel fore, Pixel back, char const *s) { cursor_to(col, row); type(fore, back, s); } static void text_centered(unsigned row, Pixel fore, Pixel back, char const *s) { unsigned len = 0; while (s[len]) ++len; unsigned left_margin = 40 - len / 2; unsigned right_margin = t_right_margin - len - left_margin; cursor_to(0, row); for (unsigned i = 0; i < left_margin; ++i) type(fore, back, ' '); type(fore, back, s); for (unsigned i = 0; i < right_margin; ++i) type(fore, back, ' '); } enum { white = 0b111111, lt_gray = 0b101010, dk_gray = 0b010101, black = 0b000000, red = 0b000011, green = 0b001100, blue = 0b110000, }; /******************************************************************************* * The Startup Routine */ void v7m_reset_handler() { armv7m::crt0_init(); runtime::ramcode_init(); // Enable fault reporting. armv7m::scb.write_shcsr(armv7m::scb.read_shcsr() .with_memfaultena(true) .with_busfaultena(true) .with_usgfaultena(true)); // Enable floating point automatic/lazy state preservation. // The CONTROL bit governing FP will be set automatically when first used. armv7m::scb_fp.write_fpccr(armv7m::scb_fp.read_fpccr() .with_aspen(true) .with_lspen(true)); armv7m::instruction_synchronization_barrier(); // Now please. // Enable access to the floating point coprocessor. armv7m::scb.write_cpacr(armv7m::scb.read_cpacr() .with_cp11(armv7m::Scb::CpAccess::full) .with_cp10(armv7m::Scb::CpAccess::full)); // It is now safe to use floating point. vga::init(); gfx_rast.activate(vga::timing_vesa_800x600_60hz); gfx_rast.set_fg_color(0b111111); gfx_rast.set_bg_color(0b100000); text_rast.activate(vga::timing_vesa_800x600_60hz); text_rast.clear_framebuffer(0); text_centered(0, white, dk_gray, "800x600 Mixed Graphics Modes Demo"); cursor_to(0, 2); type(white, black, "Bitmap framebuffer combined with "); type(black, white, "attributed"); type(red, black, " 256"); type(green, black, " color "); type(blue, black, "text."); cursor_to(0, 4); rainbow_type("The quick brown fox jumped over the lazy dog. " "0123456789!@#$%^{}"); text_at(0, 6, white, 0b100000, " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut\n" " tellus quam. Cras ornare facilisis sollicitudin. Quisque quis\n" " imperdiet mauris. Proin malesuada nibh dolor, eu luctus mauris\n" " ultricies vitae. Interdum et malesuada fames ac ante ipsum primis\n" " in faucibus. Aenean tincidunt viverra ultricies. Quisque rutrum\n" " vehicula pulvinar.\n"); text_at(0, 15, white, black, "60 fps / 40MHz pixel clock"); text_at(58, 36, white, black, "Frame number:"); vga::configure_band(0, gfx_rows, &gfx_rast); vga::configure_band(gfx_rows, text_rows, &text_rast); vga::configure_timing(vga::timing_vesa_800x600_60hz); unsigned const num_balls = 60; int x[num_balls][2], y[num_balls][2]; int xi[num_balls], yi[num_balls]; unsigned seed = 1118; for (unsigned n = 0; n < num_balls; ++n) { seed = (seed * 1664525) + 1013904223; x[n][0] = x[n][1] = seed % gfx_cols; seed = (seed * 1664525) + 1013904223; y[n][0] = y[n][1] = seed % (gfx_rows*2/3); seed = (seed * 1664525) + 1013904223; xi[n] = seed % 9 - 5; seed = (seed * 1664525) + 1013904223; yi[n] = seed % 3 - 2; } char fc[9]; fc[8] = 0; unsigned frame = 0; while (1) { unsigned f = ++frame; for (unsigned i = 8; i > 0; --i) { unsigned n = f & 0xF; fc[i - 1] = n > 9 ? 'A' + n - 10 : '0' + n; f >>= 4; } text_at(72, 15, red, black, fc); for (unsigned n = 0; n < num_balls; ++n) { step_ball(x[n][0], y[n][0], x[n][1], y[n][1], xi[n], yi[n]); } gfx_rast.flip(); f = ++frame; for (unsigned i = 8; i > 0; --i) { unsigned n = f & 0xF; fc[i - 1] = n > 9 ? 'A' + n - 10 : '0' + n; f >>= 4; } text_at(72, 15, red, black, fc); for (unsigned n = 0; n < num_balls; ++n) { step_ball(x[n][1], y[n][1], x[n][0], y[n][0], xi[n], yi[n]); } gfx_rast.flip(); } } <commit_msg>demo/hires_mix: rejigger particle simulation.<commit_after>#include "lib/armv7m/crt0.h" #include "lib/armv7m/exception_table.h" #include "lib/armv7m/instructions.h" #include "lib/armv7m/scb.h" #include "runtime/ramcode.h" #include "vga/graphics_1.h" #include "vga/timing.h" #include "vga/vga.h" #include "vga/rast/bitmap_1.h" #include "vga/rast/text_10x16.h" using vga::rast::Bitmap_1; typedef vga::Rasterizer::Pixel Pixel; /******************************************************************************* * Screen partitioning */ static constexpr unsigned text_cols = 800; static constexpr unsigned text_rows = 16 * 16; static constexpr unsigned gfx_cols = 800; static constexpr unsigned gfx_rows = 600 - text_rows; /******************************************************************************* * The Graphics Parts */ static Bitmap_1 gfx_rast(gfx_cols, gfx_rows); class Particle { public: static constexpr unsigned lifetime = 120; static unsigned seed; void randomize() { _x[0] = _x[1] = rand() % gfx_cols; _y[0] = _y[1] = rand() % (gfx_rows * 2/3); _dx = rand() % 9 - 5; _dy = rand() % 3 - 2; } void nudge(int ddx, int ddy) { _dx += ddx; _dy += ddy; } void step(vga::Graphics1 &g) { g.clear_pixel(_x[1], _y[1]); g.clear_pixel(_x[1] - 1, _y[1]); g.clear_pixel(_x[1] + 1, _y[1]); g.clear_pixel(_x[1], _y[1] - 1); g.clear_pixel(_x[1], _y[1] + 1); _x[1] = _x[0]; _y[1] = _y[0]; int x_ = _x[0] + _dx; int y_ = _y[0] + _dy; if (x_ < 0) { x_ = 0; _dx = -_dx; } if (y_ < 0) { y_ = 0; _dy = -_dy; } if (x_ >= static_cast<int>(gfx_cols)) { x_ = gfx_cols - 1; _dx = -_dx; } if (y_ >= static_cast<int>(gfx_rows)) { y_ = gfx_rows - 1; _dy = -_dy; } _x[0] = x_; _y[0] = y_; g.set_pixel(_x[0], _y[0]); g.set_pixel(_x[0] - 1, _y[0]); g.set_pixel(_x[0] + 1, _y[0]); g.set_pixel(_x[0], _y[0] - 1); g.set_pixel(_x[0], _y[0] + 1); } private: int _x[2], _y[2]; int _dx, _dy; unsigned rand() { seed = (seed * 1664525) + 1013904223; return seed; } }; unsigned Particle::seed = 1118; static constexpr unsigned particle_count = 500; static Particle particles[particle_count]; static void update_particles() { vga::Graphics1 g = gfx_rast.make_bg_graphics(); for (Particle &p : particles) { p.step(g); p.nudge(0, 1); } gfx_rast.flip(); } /******************************************************************************* * The Text Parts */ static vga::rast::Text_10x16 text_rast(text_cols, text_rows, gfx_rows); static constexpr unsigned t_right_margin = (text_cols + 9) / 10; static constexpr unsigned t_bottom_margin = (text_rows + 15) / 16; static unsigned t_row = 0, t_col = 0; static void type_raw(Pixel fore, Pixel back, char c) { text_rast.put_char(t_col, t_row, fore, back, c); ++t_col; if (t_col == t_right_margin) { t_col = 0; ++t_row; if (t_row == t_bottom_margin) t_row = 0; } } static void type(Pixel fore, Pixel back, char c) { switch (c) { case '\n': do { type_raw(fore, back, ' '); } while (t_col); return; default: type_raw(fore, back, c); return; } } static void type(Pixel fore, Pixel back, char const *s) { while (char c = *s++) { type(fore, back, c); } } static void rainbow_type(char const *s) { unsigned x = 0; while (char c = *s++) { type(x & 0b111111, ~x & 0b111111, c); ++x; } } static void cursor_to(unsigned col, unsigned row) { if (col >= t_right_margin) col = t_right_margin - 1; if (row >= t_bottom_margin) row = t_bottom_margin - 1; t_col = col; t_row = row; } static void text_at(unsigned col, unsigned row, Pixel fore, Pixel back, char const *s) { cursor_to(col, row); type(fore, back, s); } static void text_centered(unsigned row, Pixel fore, Pixel back, char const *s) { unsigned len = 0; while (s[len]) ++len; unsigned left_margin = 40 - len / 2; unsigned right_margin = t_right_margin - len - left_margin; cursor_to(0, row); for (unsigned i = 0; i < left_margin; ++i) type(fore, back, ' '); type(fore, back, s); for (unsigned i = 0; i < right_margin; ++i) type(fore, back, ' '); } enum { white = 0b111111, lt_gray = 0b101010, dk_gray = 0b010101, black = 0b000000, red = 0b000011, green = 0b001100, blue = 0b110000, }; /******************************************************************************* * The Startup Routine */ void v7m_reset_handler() { armv7m::crt0_init(); runtime::ramcode_init(); // Enable fault reporting. armv7m::scb.write_shcsr(armv7m::scb.read_shcsr() .with_memfaultena(true) .with_busfaultena(true) .with_usgfaultena(true)); // Enable floating point automatic/lazy state preservation. // The CONTROL bit governing FP will be set automatically when first used. armv7m::scb_fp.write_fpccr(armv7m::scb_fp.read_fpccr() .with_aspen(true) .with_lspen(true)); armv7m::instruction_synchronization_barrier(); // Now please. // Enable access to the floating point coprocessor. armv7m::scb.write_cpacr(armv7m::scb.read_cpacr() .with_cp11(armv7m::Scb::CpAccess::full) .with_cp10(armv7m::Scb::CpAccess::full)); // It is now safe to use floating point. vga::init(); gfx_rast.activate(vga::timing_vesa_800x600_60hz); gfx_rast.set_fg_color(0b111111); gfx_rast.set_bg_color(0b100000); text_rast.activate(vga::timing_vesa_800x600_60hz); text_rast.clear_framebuffer(0); text_centered(0, white, dk_gray, "800x600 Mixed Graphics Modes Demo"); cursor_to(0, 2); type(white, black, "Bitmap framebuffer combined with "); type(black, white, "attributed"); type(red, black, " 256"); type(green, black, " color "); type(blue, black, "text."); cursor_to(0, 4); rainbow_type("The quick brown fox jumped over the lazy dog. " "0123456789!@#$%^{}"); text_at(0, 6, white, 0b100000, " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut\n" " tellus quam. Cras ornare facilisis sollicitudin. Quisque quis\n" " imperdiet mauris. Proin malesuada nibh dolor, eu luctus mauris\n" " ultricies vitae. Interdum et malesuada fames ac ante ipsum primis\n" " in faucibus. Aenean tincidunt viverra ultricies. Quisque rutrum\n" " vehicula pulvinar.\n"); text_at(0, 15, white, black, "60 fps / 40MHz pixel clock"); text_at(58, 36, white, black, "Frame number:"); vga::configure_band(0, gfx_rows, &gfx_rast); vga::configure_band(gfx_rows, text_rows, &text_rast); vga::configure_timing(vga::timing_vesa_800x600_60hz); for (Particle &p : particles) p.randomize(); char fc[9]; fc[8] = 0; unsigned frame = 0; while (1) { unsigned f = ++frame; for (unsigned i = 8; i > 0; --i) { unsigned n = f & 0xF; fc[i - 1] = n > 9 ? 'A' + n - 10 : '0' + n; f >>= 4; } text_at(72, 15, red, black, fc); update_particles(); f = ++frame; for (unsigned i = 8; i > 0; --i) { unsigned n = f & 0xF; fc[i - 1] = n > 9 ? 'A' + n - 10 : '0' + n; f >>= 4; } text_at(72, 15, red, black, fc); update_particles(); } } <|endoftext|>
<commit_before>#include <assert.h> #include <cstdio> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Support/raw_ostream.h> #include <llvm/IRReader/IRReader.h> #include <iostream> #include <string> #include "../src/LLVMDependenceGraph.h" using namespace dg; using llvm::errs; static void dump_to_dot(LLVMDGNode *n, std::ostream& out) { const llvm::Value *val; /* do not draw multiple edges */ if (n->getDFSrun() == 1) return; else n->setDFSrun(1); for (auto I = n->control_begin(), E = n->control_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << "\n"; for (auto I = n->dependence_begin(), E = n->dependence_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << " [color=red]\n"; #if ENABLE_CFG for (auto I = n->succ_begin(), E = n->succ_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << " [style=dotted]\n"; #endif /* ENABLE_CFG */ if (n->getSubgraph()) { out << "\tNODE" << n << " -> NODE" << n->getSubgraph()->getEntry() << " [style=dashed]\n"; } } static std::string& getValueName(const llvm::Value *val, std::string &str) { llvm::raw_string_ostream s(str); str.clear(); if (llvm::isa<llvm::Function>(val)) s << "ENTRY " << val->getName(); else s << *val; return s.str(); } void print_to_dot(LLVMDependenceGraph *dg, bool issubgraph = false, const char *description = NULL) { static unsigned subgraph_no = 0; const llvm::Value *val; std::string valName; std::ostream& out = std::cout; if (!dg) return; if (issubgraph) { out << "subgraph \"cluster_" << subgraph_no++; } else { out << "digraph \""<< description ? description : "DependencyGraph"; } out << "\" {\n"; for (auto I = dg->begin(), E = dg->end(); I != E; ++I) { auto n = I->second; if (!n) { if (!llvm::isa<llvm::Function>(val)) { getValueName(dg->getEntry()->getValue(), valName); errs() << "WARN [" << valName << "]: Node is NULL for value: " << *I->first << "\n"; } continue; } val = n->getValue(); print_to_dot(n->getSubgraph(), true); print_to_dot(n->getParameters(), true); getValueName(val, valName); out << "\tNODE" << n << " [label=\"" << valName; for (auto d : n->getDefs()) { getValueName(d->getValue(), valName); out << "\\nDEF " << valName; } for (auto d : n->getPtrs()) { getValueName(d->getValue(), valName); out << "\\nPTR " << valName; } out << "\""; if (n->isLoopHeader()) out << "style=\"filled\" fillcolor=\"gray\""; out << "];\n"; //<<" (runid=" << n->getDFSrun() << ")\"];\n"; } for (auto I = dg->begin(), E = dg->end(); I != E; ++I) { auto n = I->second; if (!n) { if (!llvm::isa<llvm::Function>(val)) errs() << "WARN [" << dg << "]: Node is NULL for value: " << *I->first << "\n"; continue; } dump_to_dot(I->second, out); } out << "}\n"; } int main(int argc, char *argv[]) { llvm::LLVMContext context; llvm::SMDiagnostic SMD; std::unique_ptr<llvm::Module> M; const char *module, *ofile = NULL; if (argc == 3) { module = argv[1]; ofile = argv[2]; errs() << "Not supported yet\n"; return 1; } else if (argc == 2) { module = argv[1]; } else { errs() << "Usage: % IR_module [output_file]\n"; return 1; } M = llvm::parseIRFile(module, SMD, context); if (!M) { SMD.print(argv[0], errs()); return 1; } LLVMDependenceGraph d; d.build(&*M); print_to_dot(&d, false, "LLVM Dependence Graph"); return 0; } <commit_msg>llvm-dg-dump: add edge from call-site to parameters<commit_after>#include <assert.h> #include <cstdio> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Support/raw_ostream.h> #include <llvm/IRReader/IRReader.h> #include <iostream> #include <string> #include "../src/LLVMDependenceGraph.h" using namespace dg; using llvm::errs; static void dump_to_dot(LLVMDGNode *n, std::ostream& out) { const llvm::Value *val; /* do not draw multiple edges */ if (n->getDFSrun() == 1) return; else n->setDFSrun(1); for (auto I = n->control_begin(), E = n->control_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << "\n"; for (auto I = n->dependence_begin(), E = n->dependence_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << " [color=red]\n"; #if ENABLE_CFG for (auto I = n->succ_begin(), E = n->succ_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << " [style=dotted]\n"; #endif /* ENABLE_CFG */ if (n->getSubgraph()) { out << "\tNODE" << n << " -> NODE" << n->getSubgraph()->getEntry() << " [style=dashed]\n"; } } static std::string& getValueName(const llvm::Value *val, std::string &str) { llvm::raw_string_ostream s(str); str.clear(); if (llvm::isa<llvm::Function>(val)) s << "ENTRY " << val->getName(); else s << *val; return s.str(); } void print_to_dot(LLVMDependenceGraph *dg, bool issubgraph = false, const char *description = NULL) { static unsigned subgraph_no = 0; const llvm::Value *val; std::string valName; std::ostream& out = std::cout; if (!dg) return; if (issubgraph) { out << "subgraph \"cluster_" << subgraph_no++; } else { out << "digraph \""<< description ? description : "DependencyGraph"; } out << "\" {\n"; for (auto I = dg->begin(), E = dg->end(); I != E; ++I) { auto n = I->second; if (!n) { if (!llvm::isa<llvm::Function>(val)) { getValueName(dg->getEntry()->getValue(), valName); errs() << "WARN [" << valName << "]: Node is NULL for value: " << *I->first << "\n"; } continue; } val = n->getValue(); print_to_dot(n->getSubgraph(), true); LLVMDependenceGraph *params = n->getParameters(); if (params) { print_to_dot(params, true); // add control edge from call-site to the parameters subgraph out << "\tNODE" << n << " -> NODE" << params->getEntry() << "\n"; } getValueName(val, valName); out << "\tNODE" << n << " [label=\"" << valName; for (auto d : n->getDefs()) { getValueName(d->getValue(), valName); out << "\\nDEF " << valName; } for (auto d : n->getPtrs()) { getValueName(d->getValue(), valName); out << "\\nPTR " << valName; } out << "\""; if (n->isLoopHeader()) out << "style=\"filled\" fillcolor=\"gray\""; out << "];\n"; //<<" (runid=" << n->getDFSrun() << ")\"];\n"; } for (auto I = dg->begin(), E = dg->end(); I != E; ++I) { auto n = I->second; if (!n) { if (!llvm::isa<llvm::Function>(val)) errs() << "WARN [" << dg << "]: Node is NULL for value: " << *I->first << "\n"; continue; } dump_to_dot(I->second, out); } out << "}\n"; } int main(int argc, char *argv[]) { llvm::LLVMContext context; llvm::SMDiagnostic SMD; std::unique_ptr<llvm::Module> M; const char *module, *ofile = NULL; if (argc == 3) { module = argv[1]; ofile = argv[2]; errs() << "Not supported yet\n"; return 1; } else if (argc == 2) { module = argv[1]; } else { errs() << "Usage: % IR_module [output_file]\n"; return 1; } M = llvm::parseIRFile(module, SMD, context); if (!M) { SMD.print(argv[0], errs()); return 1; } LLVMDependenceGraph d; d.build(&*M); print_to_dot(&d, false, "LLVM Dependence Graph"); return 0; } <|endoftext|>
<commit_before>#ifndef HAVE_LLVM #error "This code needs LLVM enabled" #endif #include <set> #include <string> #include <iostream> #include <sstream> #include <fstream> #include <cassert> #include <cstdio> #include <cstdlib> // ignore unused parameters in LLVM libraries #if (__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #else #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #endif #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Instructions.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Support/raw_os_ostream.h> #include <llvm/IRReader/IRReader.h> #if LLVM_VERSION_MAJOR >= 4 #include <llvm/Bitcode/BitcodeReader.h> #else #include <llvm/Bitcode/ReaderWriter.h> #endif #if (__clang__) #pragma clang diagnostic pop // ignore -Wunused-parameter #else #pragma GCC diagnostic pop #endif #include "llvm/analysis/PointsTo/PointsTo.h" #include "analysis/PointsTo/PointsToFlowInsensitive.h" #include "analysis/PointsTo/PointsToFlowSensitive.h" #include "analysis/PointsTo/PointsToWithInvalidate.h" #include "analysis/PointsTo/Pointer.h" #include "TimeMeasure.h" using namespace dg; using namespace dg::analysis::pta; using dg::debug::TimeMeasure; using llvm::errs; static bool verbose; static bool ids_only = false; std::unique_ptr<PointerAnalysis> PA; enum PTType { FLOW_SENSITIVE = 1, FLOW_INSENSITIVE, WITH_INVALIDATE, }; static std::string getInstName(const llvm::Value *val) { std::ostringstream ostr; llvm::raw_os_ostream ro(ostr); assert(val); if (llvm::isa<llvm::Function>(val)) ro << val->getName().data(); else ro << *val; ro.flush(); // break the string if it is too long return ostr.str(); } void printPSNodeType(enum PSNodeType type) { printf("%s", PSNodeTypeToCString(type)); } static void dumpPointer(const Pointer& ptr, bool dot); static void printName(PSNode *node, bool dot) { std::string nm; const char *name = nullptr; if (node->isNull()) { name = "null"; } else if (node->isUnknownMemory()) { name = "unknown"; } else if (node->isInvalidated() && !node->getUserData<llvm::Value>()) { name = "invalidated"; } if (!name) { if (ids_only) { printf(" <%u>", node->getID()); return; } if (!node->getUserData<llvm::Value>()) { printf("<%u> (no name)\\n", node->getID()); if (node->getType() == PSNodeType::CONSTANT) { dumpPointer(*(node->pointsTo.begin()), dot); } else if (node->getType() == PSNodeType::CALL_RETURN) { if (PSNode *paired = node->getPairedNode()) printName(paired, dot); } else if (PSNodeEntry *entry = PSNodeEntry::get(node)) { printf("%s\\n", entry->getFunctionName().c_str()); } if (!dot) printf(" <%u>\n", node->getID()); return; } nm = getInstName(node->getUserData<llvm::Value>()); name = nm.c_str(); } if (ids_only) { printf(" <%u>", node->getID()); return; } // escape the " character for (int i = 0; name[i] != '\0'; ++i) { // crop long names if (i >= 70) { printf(" ..."); break; } if (name[i] == '"') putchar('\\'); putchar(name[i]); } } static void dumpPointer(const Pointer& ptr, bool dot) { printName(ptr.target, dot); if (ptr.offset.isUnknown()) puts(" + UNKNOWN"); else printf(" + %lu", *ptr.offset); } static void dumpMemoryObject(MemoryObject *mo, int ind, bool dot) { for (auto& it : mo->pointsTo) { for (const Pointer& ptr : it.second) { // print indentation printf("%*s", ind, ""); if (it.first.isUnknown()) printf("[UNKNOWN] -> "); else printf("[%lu] -> ", *it.first); dumpPointer(ptr, dot); if (dot) printf("\\n"); else putchar('\n'); } } } static void dumpMemoryMap(PointsToFlowSensitive::MemoryMapT *mm, int ind, bool dot) { for (const auto& it : *mm) { // print the key if (!dot) printf("%*s", ind, ""); putchar('['); printName(it.first, dot); if (dot) printf("\\n"); else putchar('\n'); dumpMemoryObject(it.second.get(), ind + 4, dot); } } static void dumpPointerSubgraphData(PSNode *n, PTType type, bool dot = false) { assert(n && "No node given"); if (type == FLOW_INSENSITIVE) { MemoryObject *mo = n->getData<MemoryObject>(); if (!mo) return; if (dot) printf("\\n Memory: ---\\n"); else printf(" Memory: ---\n"); dumpMemoryObject(mo, 6, dot); if (!dot) printf(" -----------\n"); } else { PointsToFlowSensitive::MemoryMapT *mm = n->getData<PointsToFlowSensitive::MemoryMapT>(); if (!mm) return; if (dot) printf("\\n Memory map: [%p]\\n", static_cast<void*>(mm)); else printf(" Memory map: [%p]\n", static_cast<void*>(mm)); dumpMemoryMap(mm, 6, dot); if (!dot) printf(" ----------------\n"); } } static void dumpPSNode(PSNode *n, PTType type) { printf("NODE %3u: ", n->getID()); printf("Ty: "); printPSNodeType(n->getType()); printf("\\n"); PSNodeAlloc *alloc = PSNodeAlloc::get(n); if (alloc && (alloc->getSize() || alloc->isHeap() || alloc->isZeroInitialized())) printf(" [size: %lu, heap: %u, zeroed: %u]", alloc->getSize(), alloc->isHeap(), alloc->isZeroInitialized()); if (n->pointsTo.empty()) { puts(" -- no points-to"); return; } else putchar('\n'); for (const Pointer& ptr : n->pointsTo) { printf(" -> "); printName(ptr.target, false); if (ptr.offset.isUnknown()) puts(" + Offset::UNKNOWN"); else printf(" + %lu\n", *ptr.offset); } if (verbose) { dumpPointerSubgraphData(n, type); } } static void dumpPointerSubgraphdot(LLVMPointerAnalysis *pta, PTType type) { printf("digraph \"Pointer State Subgraph\" {\n"); /* dump nodes */ const auto& nodes = pta->getNodes(); for (PSNode *node : nodes) { if (!node) continue; printf("\tNODE%u [label=\"<%u> ", node->getID(), node->getID()); printPSNodeType(node->getType()); printf("\\n"); printName(node, true); printf("\\nparent: %u\\n", node->getParent() ? node->getParent()->getID() : 0); PSNodeAlloc *alloc = PSNodeAlloc::get(node); if (alloc && (alloc->getSize() || alloc->isHeap() || alloc->isZeroInitialized())) printf("\\n[size: %lu, heap: %u, zeroed: %u]", alloc->getSize(), alloc->isHeap(), alloc->isZeroInitialized()); if (verbose && node->getOperandsNum() > 0) { printf("\\n--- operands ---\\n"); for (PSNode *op : node->getOperands()) { printName(op, true); printf("\\n"); } printf("------\\n"); } for (const Pointer& ptr : node->pointsTo) { printf("\\n -> "); printName(ptr.target, true); printf(" + "); if (ptr.offset.isUnknown()) printf("Offset::UNKNOWN"); else printf("%lu", *ptr.offset); } if (verbose) dumpPointerSubgraphData(node, type, true /* dot */); printf("\", shape=box"); if (node->getType() != PSNodeType::STORE) { if (node->pointsTo.size() == 0 && (node->getType() == PSNodeType::LOAD || node->getType() == PSNodeType::GEP || node->getType() == PSNodeType::CAST || node->getType() == PSNodeType::PHI)) printf(", style=filled, fillcolor=red"); } else { printf(", style=filled, fillcolor=orange"); } printf("]\n"); } /* dump edges */ for (PSNode *node : nodes) { if (!node) // node id 0 is nullptr continue; for (PSNode *succ : node->getSuccessors()) { printf("\tNODE%u -> NODE%u [penwidth=2]\n", node->getID(), succ->getID()); } for (PSNode *op : node->getOperands()) { printf("\tNODE%u -> NODE%u [color=blue,style=dotted,constraint=false]\n", op->getID(), node->getID()); } } printf("}\n"); } static void dumpPointerSubgraph(LLVMPointerAnalysis *pta, PTType type, bool todot) { assert(pta); if (todot) dumpPointerSubgraphdot(pta, type); else { const auto& nodes = pta->getNodes(); for (PSNode *node : nodes) { if (node) // node id 0 is nullptr dumpPSNode(node, type); } } } int main(int argc, char *argv[]) { llvm::Module *M; llvm::LLVMContext context; llvm::SMDiagnostic SMD; bool todot = false; const char *module = nullptr; PTType type = FLOW_INSENSITIVE; uint64_t field_senitivity = Offset::UNKNOWN; // parse options for (int i = 1; i < argc; ++i) { // run given points-to analysis if (strcmp(argv[i], "-pta") == 0) { if (strcmp(argv[i+1], "fs") == 0) type = FLOW_SENSITIVE; else if (strcmp(argv[i+1], "inv") == 0) type = WITH_INVALIDATE; } else if (strcmp(argv[i], "-pta-field-sensitive") == 0) { field_senitivity = static_cast<uint64_t>(atoll(argv[i + 1])); } else if (strcmp(argv[i], "-dot") == 0) { todot = true; } else if (strcmp(argv[i], "-ids-only") == 0) { ids_only = true; } else if (strcmp(argv[i], "-v") == 0) { verbose = true; } else { module = argv[i]; } } if (!module) { errs() << "Usage: % IR_module [output_file]\n"; return 1; } #if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR <= 5)) M = llvm::ParseIRFile(module, SMD, context); #else auto _M = llvm::parseIRFile(module, SMD, context); // _M is unique pointer, we need to get Module * M = _M.get(); #endif if (!M) { llvm::errs() << "Failed parsing '" << module << "' file:\n"; SMD.print(argv[0], errs()); return 1; } TimeMeasure tm; LLVMPointerAnalysis PTA(M, field_senitivity); tm.start(); // use createAnalysis instead of the run() method so that we won't delete // the analysis data (like memory objects) which may be needed if (type == FLOW_INSENSITIVE) { PA = std::unique_ptr<PointerAnalysis>( PTA.createPTA<analysis::pta::PointsToFlowInsensitive>() ); } else if (type == WITH_INVALIDATE) { PA = std::unique_ptr<PointerAnalysis>( PTA.createPTA<analysis::pta::PointsToWithInvalidate>() ); } else { PA = std::unique_ptr<PointerAnalysis>( PTA.createPTA<analysis::pta::PointsToFlowSensitive>() ); } // run the analysis PA->run(); tm.stop(); tm.report("INFO: Points-to analysis [new] took"); dumpPointerSubgraph(&PTA, type, todot); return 0; } <commit_msg>llvm-ps-dump: allow dumping the graph without running PTA<commit_after>#ifndef HAVE_LLVM #error "This code needs LLVM enabled" #endif #include <set> #include <string> #include <iostream> #include <sstream> #include <fstream> #include <cassert> #include <cstdio> #include <cstdlib> // ignore unused parameters in LLVM libraries #if (__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #else #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #endif #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Instructions.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Support/raw_os_ostream.h> #include <llvm/IRReader/IRReader.h> #if LLVM_VERSION_MAJOR >= 4 #include <llvm/Bitcode/BitcodeReader.h> #else #include <llvm/Bitcode/ReaderWriter.h> #endif #if (__clang__) #pragma clang diagnostic pop // ignore -Wunused-parameter #else #pragma GCC diagnostic pop #endif #include "llvm/analysis/PointsTo/PointsTo.h" #include "analysis/PointsTo/PointsToFlowInsensitive.h" #include "analysis/PointsTo/PointsToFlowSensitive.h" #include "analysis/PointsTo/PointsToWithInvalidate.h" #include "analysis/PointsTo/Pointer.h" #include "TimeMeasure.h" using namespace dg; using namespace dg::analysis::pta; using dg::debug::TimeMeasure; using llvm::errs; static bool verbose; static bool ids_only = false; static bool dump_graph_only = false; std::unique_ptr<PointerAnalysis> PA; enum PTType { FLOW_SENSITIVE = 1, FLOW_INSENSITIVE, WITH_INVALIDATE, }; static std::string getInstName(const llvm::Value *val) { std::ostringstream ostr; llvm::raw_os_ostream ro(ostr); assert(val); if (llvm::isa<llvm::Function>(val)) ro << val->getName().data(); else ro << *val; ro.flush(); // break the string if it is too long return ostr.str(); } void printPSNodeType(enum PSNodeType type) { printf("%s", PSNodeTypeToCString(type)); } static void dumpPointer(const Pointer& ptr, bool dot); static void printName(PSNode *node, bool dot) { std::string nm; const char *name = nullptr; if (node->isNull()) { name = "null"; } else if (node->isUnknownMemory()) { name = "unknown"; } else if (node->isInvalidated() && !node->getUserData<llvm::Value>()) { name = "invalidated"; } if (!name) { if (ids_only) { printf(" <%u>", node->getID()); return; } if (!node->getUserData<llvm::Value>()) { printf("<%u> (no name)\\n", node->getID()); if (node->getType() == PSNodeType::CONSTANT) { dumpPointer(*(node->pointsTo.begin()), dot); } else if (node->getType() == PSNodeType::CALL_RETURN) { if (PSNode *paired = node->getPairedNode()) printName(paired, dot); } else if (PSNodeEntry *entry = PSNodeEntry::get(node)) { printf("%s\\n", entry->getFunctionName().c_str()); } if (!dot) printf(" <%u>\n", node->getID()); return; } nm = getInstName(node->getUserData<llvm::Value>()); name = nm.c_str(); } if (ids_only) { printf(" <%u>", node->getID()); return; } // escape the " character for (int i = 0; name[i] != '\0'; ++i) { // crop long names if (i >= 70) { printf(" ..."); break; } if (name[i] == '"') putchar('\\'); putchar(name[i]); } } static void dumpPointer(const Pointer& ptr, bool dot) { printName(ptr.target, dot); if (ptr.offset.isUnknown()) puts(" + UNKNOWN"); else printf(" + %lu", *ptr.offset); } static void dumpMemoryObject(MemoryObject *mo, int ind, bool dot) { for (auto& it : mo->pointsTo) { for (const Pointer& ptr : it.second) { // print indentation printf("%*s", ind, ""); if (it.first.isUnknown()) printf("[UNKNOWN] -> "); else printf("[%lu] -> ", *it.first); dumpPointer(ptr, dot); if (dot) printf("\\n"); else putchar('\n'); } } } static void dumpMemoryMap(PointsToFlowSensitive::MemoryMapT *mm, int ind, bool dot) { for (const auto& it : *mm) { // print the key if (!dot) printf("%*s", ind, ""); putchar('['); printName(it.first, dot); if (dot) printf("\\n"); else putchar('\n'); dumpMemoryObject(it.second.get(), ind + 4, dot); } } static void dumpPointerSubgraphData(PSNode *n, PTType type, bool dot = false) { assert(n && "No node given"); if (type == FLOW_INSENSITIVE) { MemoryObject *mo = n->getData<MemoryObject>(); if (!mo) return; if (dot) printf("\\n Memory: ---\\n"); else printf(" Memory: ---\n"); dumpMemoryObject(mo, 6, dot); if (!dot) printf(" -----------\n"); } else { PointsToFlowSensitive::MemoryMapT *mm = n->getData<PointsToFlowSensitive::MemoryMapT>(); if (!mm) return; if (dot) printf("\\n Memory map: [%p]\\n", static_cast<void*>(mm)); else printf(" Memory map: [%p]\n", static_cast<void*>(mm)); dumpMemoryMap(mm, 6, dot); if (!dot) printf(" ----------------\n"); } } static void dumpPSNode(PSNode *n, PTType type) { printf("NODE %3u: ", n->getID()); printf("Ty: "); printPSNodeType(n->getType()); printf("\\n"); PSNodeAlloc *alloc = PSNodeAlloc::get(n); if (alloc && (alloc->getSize() || alloc->isHeap() || alloc->isZeroInitialized())) printf(" [size: %lu, heap: %u, zeroed: %u]", alloc->getSize(), alloc->isHeap(), alloc->isZeroInitialized()); if (n->pointsTo.empty()) { puts(" -- no points-to"); return; } else putchar('\n'); for (const Pointer& ptr : n->pointsTo) { printf(" -> "); printName(ptr.target, false); if (ptr.offset.isUnknown()) puts(" + Offset::UNKNOWN"); else printf(" + %lu\n", *ptr.offset); } if (verbose) { dumpPointerSubgraphData(n, type); } } static void dumpPointerSubgraphdot(LLVMPointerAnalysis *pta, PTType type) { printf("digraph \"Pointer State Subgraph\" {\n"); /* dump nodes */ const auto& nodes = pta->getNodes(); for (PSNode *node : nodes) { if (!node) continue; printf("\tNODE%u [label=\"<%u> ", node->getID(), node->getID()); printPSNodeType(node->getType()); printf("\\n"); printName(node, true); printf("\\nparent: %u\\n", node->getParent() ? node->getParent()->getID() : 0); PSNodeAlloc *alloc = PSNodeAlloc::get(node); if (alloc && (alloc->getSize() || alloc->isHeap() || alloc->isZeroInitialized())) printf("\\n[size: %lu, heap: %u, zeroed: %u]", alloc->getSize(), alloc->isHeap(), alloc->isZeroInitialized()); if (verbose && node->getOperandsNum() > 0) { printf("\\n--- operands ---\\n"); for (PSNode *op : node->getOperands()) { printName(op, true); printf("\\n"); } printf("------\\n"); } for (const Pointer& ptr : node->pointsTo) { printf("\\n -> "); printName(ptr.target, true); printf(" + "); if (ptr.offset.isUnknown()) printf("Offset::UNKNOWN"); else printf("%lu", *ptr.offset); } if (verbose) dumpPointerSubgraphData(node, type, true /* dot */); printf("\", shape=box"); if (node->getType() != PSNodeType::STORE) { if (node->pointsTo.size() == 0 && (node->getType() == PSNodeType::LOAD || node->getType() == PSNodeType::GEP || node->getType() == PSNodeType::CAST || node->getType() == PSNodeType::PHI)) printf(", style=filled, fillcolor=red"); } else { printf(", style=filled, fillcolor=orange"); } printf("]\n"); } /* dump edges */ for (PSNode *node : nodes) { if (!node) // node id 0 is nullptr continue; for (PSNode *succ : node->getSuccessors()) { printf("\tNODE%u -> NODE%u [penwidth=2]\n", node->getID(), succ->getID()); } for (PSNode *op : node->getOperands()) { printf("\tNODE%u -> NODE%u [color=blue,style=dotted,constraint=false]\n", op->getID(), node->getID()); } } printf("}\n"); } static void dumpPointerSubgraph(LLVMPointerAnalysis *pta, PTType type, bool todot) { assert(pta); if (todot) dumpPointerSubgraphdot(pta, type); else { const auto& nodes = pta->getNodes(); for (PSNode *node : nodes) { if (node) // node id 0 is nullptr dumpPSNode(node, type); } } } int main(int argc, char *argv[]) { llvm::Module *M; llvm::LLVMContext context; llvm::SMDiagnostic SMD; bool todot = false; const char *module = nullptr; PTType type = FLOW_INSENSITIVE; uint64_t field_senitivity = Offset::UNKNOWN; // parse options for (int i = 1; i < argc; ++i) { // run given points-to analysis if (strcmp(argv[i], "-pta") == 0) { if (strcmp(argv[i+1], "fs") == 0) type = FLOW_SENSITIVE; else if (strcmp(argv[i+1], "inv") == 0) type = WITH_INVALIDATE; } else if (strcmp(argv[i], "-pta-field-sensitive") == 0) { field_senitivity = static_cast<uint64_t>(atoll(argv[i + 1])); } else if (strcmp(argv[i], "-dot") == 0) { todot = true; } else if (strcmp(argv[i], "-ids-only") == 0) { ids_only = true; } else if (strcmp(argv[i], "-graph-only") == 0) { dump_graph_only = true; } else if (strcmp(argv[i], "-v") == 0) { verbose = true; } else { module = argv[i]; } } if (!module) { errs() << "Usage: % IR_module [output_file]\n"; return 1; } #if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR <= 5)) M = llvm::ParseIRFile(module, SMD, context); #else auto _M = llvm::parseIRFile(module, SMD, context); // _M is unique pointer, we need to get Module * M = _M.get(); #endif if (!M) { llvm::errs() << "Failed parsing '" << module << "' file:\n"; SMD.print(argv[0], errs()); return 1; } TimeMeasure tm; LLVMPointerAnalysis PTA(M, field_senitivity); tm.start(); // use createAnalysis instead of the run() method so that we won't delete // the analysis data (like memory objects) which may be needed if (type == FLOW_INSENSITIVE) { PA = std::unique_ptr<PointerAnalysis>( PTA.createPTA<analysis::pta::PointsToFlowInsensitive>() ); } else if (type == WITH_INVALIDATE) { PA = std::unique_ptr<PointerAnalysis>( PTA.createPTA<analysis::pta::PointsToWithInvalidate>() ); } else { PA = std::unique_ptr<PointerAnalysis>( PTA.createPTA<analysis::pta::PointsToFlowSensitive>() ); } if (dump_graph_only) { dumpPointerSubgraph(&PTA, type, true); return 0; } // run the analysis PA->run(); tm.stop(); tm.report("INFO: Points-to analysis [new] took"); dumpPointerSubgraph(&PTA, type, todot); return 0; } <|endoftext|>
<commit_before>#include "graphics.h" #include <SDL.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #define error(fmt, ...) _error(__LINE__, fmt, __VA_ARGS__) #define sdl_error(name, ...) _sdl_error(__LINE__, name) static void _error(long line, const char *fmt, ...); static void _sdl_error(long line, const char *name); static void check_surface(); static void check_bpp(); static int const SURFACE_WIDTH = 640; static int const SURFACE_HEIGHT = 480; static int const SURFACE_BPP = 4; //BytesPerPixel static SDL_Surface *surface = NULL; static uint32_t bgi_colors[16]; void initgraph(int *gdriver, int *gmode, const char *something) { if (surface) { error("initgraph() can only be called once", NULL); } if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { sdl_error("SDL_Init"); } if (SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL)) { sdl_error("SDL_EnableKeyRepeat"); } if ((surface = SDL_SetVideoMode( SURFACE_WIDTH, SURFACE_HEIGHT, SURFACE_BPP * 8, //Bits Per Pixel SDL_HWSURFACE | SDL_DOUBLEBUF )) == NULL) { sdl_error("SDL_SetVideoMode"); } bgi_colors[BLACK] = SDL_MapRGB(surface->format, 0x00, 0x00, 0x00); bgi_colors[BLUE] = SDL_MapRGB(surface->format, 0x00, 0x00, 0xFF); bgi_colors[GREEN] = SDL_MapRGB(surface->format, 0x00, 0xFF, 0x00); bgi_colors[CYAN] = SDL_MapRGB(surface->format, 0x00, 0xFF, 0xFF); bgi_colors[RED] = SDL_MapRGB(surface->format, 0xFF, 0x00, 0x00); bgi_colors[MAGENTA] = SDL_MapRGB(surface->format, 0xFF, 0x00, 0xFF); bgi_colors[BROWN] = SDL_MapRGB(surface->format, 0xA5, 0x2A, 0x2A); bgi_colors[LIGHTGRAY] = SDL_MapRGB(surface->format, 0xD3, 0xD3, 0xD3); bgi_colors[DARKGRAY] = SDL_MapRGB(surface->format, 0xA9, 0xA9, 0xA9); bgi_colors[LIGHTBLUE] = SDL_MapRGB(surface->format, 0xAD, 0xD8, 0xE6); bgi_colors[LIGHTGREEN] = SDL_MapRGB(surface->format, 0x90, 0xEE, 0x90); bgi_colors[LIGHTCYAN] = SDL_MapRGB(surface->format, 0xE0, 0xFF, 0xFF); bgi_colors[LIGHTRED] = SDL_MapRGB(surface->format, 0xF0, 0x80, 0x80); bgi_colors[LIGHTMAGENTA] = SDL_MapRGB(surface->format, 0xDB, 0x70, 0x93); bgi_colors[YELLOW] = SDL_MapRGB(surface->format, 0xFF, 0xFF, 0x00); bgi_colors[WHITE] = SDL_MapRGB(surface->format, 0xFF, 0xFF, 0xFF); } void closegraph(void) { if (surface) { SDL_Quit(); surface = NULL; } } int getpixel(int x, int y) { // TODO: Implement return 0; } void putpixel(int x, int y, int color) { uint8_t *pixel; check_surface(); check_bpp(); if (color < BLACK || color > WHITE) { error("Illegal color value in putpixel: %d", color); } if (SDL_LockSurface(surface) < 0) { sdl_error("SDL_LockSurface"); } pixel = ((uint8_t *) surface->pixels) + y * surface->pitch + x * SURFACE_BPP; *(Uint32 *) pixel = bgi_colors[color]; SDL_UnlockSurface(surface); SDL_Flip(surface); } int getcolor(void) { // TODO: Implement return 0; } void setcolor(int color) { // TODO: Implement } void getimage(int left, int top, int right, int bottom, void *pic) { // TODO: Implement } void putimage(int left, int top, void *pic, int mode) { // TODO: Implement } size_t imagesize(int left, int top, int right, int bottom) { // TODO: Implement return 0; } void line(int a_x, int a_y, int b_x, int b_y) { // TODO: Implement } void rectangle(int left, int top, int right, int bottom) { // TODO: Implement } void setfillstyle(int mode, int color) { // TODO: Implement } void floodfill(int x, int y, int color) { // TODO: Implement } void outtextxy(int x, int y, const char *text) { // TODO: Implement } int GetKeyState(int key) { // TODO: Implement return 0; } void SetNormalKeysMode(void) { // no implementation necessary } void SetButtonKeysMode(void) { // no implementation necessary } void delay(int milliseconds) { // TODO: Implement } void cleardevice(void) { // TODO: Implement } void itoa(int num, char *str, int base) { // Only writing impl for base 10 conversion if (base != 10) { fprintf(stderr, "iota() only supports base 10 conversion\n"); exit(1); } // Stupid unsafe itoa has no buffer size parameter, so we have // to use sprintf instead of snprintf sprintf(str, "%d", num); } static void _error(long line, const char *fmt, ...) { va_list args; va_start(args, fmt); fprintf(stderr, "graphics.cpp error on line %ld: ", line); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); closegraph(); exit(1); } static void _sdl_error(long line, const char *name) { _error(line, "SDL function %s failed. Reason: %s", name, SDL_GetError()); } static void check_surface() { if (surface == NULL) { error("surface is null", NULL); } } static void check_bpp() { if (surface->format->BytesPerPixel != SURFACE_BPP) { error("Expecting %d bytes per pxiel. Got %d", SURFACE_BPP, surface->format->BytesPerPixel); } } <commit_msg>Add implementation for getpixel<commit_after>#include "graphics.h" #include <SDL.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #define error(fmt, ...) _error(__LINE__, fmt, __VA_ARGS__) #define sdl_error(name, ...) _sdl_error(__LINE__, name) static void _error(long line, const char *fmt, ...); static void _sdl_error(long line, const char *name); static void check_surface(); static void check_bpp(); static int const SURFACE_WIDTH = 640; static int const SURFACE_HEIGHT = 480; static int const SURFACE_BPP = 4; //BytesPerPixel static SDL_Surface *surface = NULL; static uint32_t bgi_colors[16]; void initgraph(int *gdriver, int *gmode, const char *something) { if (surface) { error("initgraph() can only be called once", NULL); } if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { sdl_error("SDL_Init"); } if (SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL)) { sdl_error("SDL_EnableKeyRepeat"); } if ((surface = SDL_SetVideoMode( SURFACE_WIDTH, SURFACE_HEIGHT, SURFACE_BPP * 8, //Bits Per Pixel SDL_HWSURFACE | SDL_DOUBLEBUF )) == NULL) { sdl_error("SDL_SetVideoMode"); } bgi_colors[BLACK] = SDL_MapRGB(surface->format, 0x00, 0x00, 0x00); bgi_colors[BLUE] = SDL_MapRGB(surface->format, 0x00, 0x00, 0xFF); bgi_colors[GREEN] = SDL_MapRGB(surface->format, 0x00, 0xFF, 0x00); bgi_colors[CYAN] = SDL_MapRGB(surface->format, 0x00, 0xFF, 0xFF); bgi_colors[RED] = SDL_MapRGB(surface->format, 0xFF, 0x00, 0x00); bgi_colors[MAGENTA] = SDL_MapRGB(surface->format, 0xFF, 0x00, 0xFF); bgi_colors[BROWN] = SDL_MapRGB(surface->format, 0xA5, 0x2A, 0x2A); bgi_colors[LIGHTGRAY] = SDL_MapRGB(surface->format, 0xD3, 0xD3, 0xD3); bgi_colors[DARKGRAY] = SDL_MapRGB(surface->format, 0xA9, 0xA9, 0xA9); bgi_colors[LIGHTBLUE] = SDL_MapRGB(surface->format, 0xAD, 0xD8, 0xE6); bgi_colors[LIGHTGREEN] = SDL_MapRGB(surface->format, 0x90, 0xEE, 0x90); bgi_colors[LIGHTCYAN] = SDL_MapRGB(surface->format, 0xE0, 0xFF, 0xFF); bgi_colors[LIGHTRED] = SDL_MapRGB(surface->format, 0xF0, 0x80, 0x80); bgi_colors[LIGHTMAGENTA] = SDL_MapRGB(surface->format, 0xDB, 0x70, 0x93); bgi_colors[YELLOW] = SDL_MapRGB(surface->format, 0xFF, 0xFF, 0x00); bgi_colors[WHITE] = SDL_MapRGB(surface->format, 0xFF, 0xFF, 0xFF); } void closegraph(void) { if (surface) { SDL_Quit(); surface = NULL; } } int getpixel(int x, int y) { uint8_t *pixel; int color, pixel_value; check_surface(); check_bpp(); if (SDL_LockSurface(surface) < 0) { sdl_error("SDL_LockSurface"); } pixel = ((uint8_t *) surface->pixels) + y * surface->pitch + x * SURFACE_BPP; SDL_UnlockSurface(surface); pixel_value = *(uint32_t *) pixel; for (color = BLACK; color <= WHITE; ++color) { if (pixel_value == bgi_colors[color]) return color; } error("Unknown pixel value: %d", pixel_value); } void putpixel(int x, int y, int color) { uint8_t *pixel; check_surface(); check_bpp(); if (color < BLACK || color > WHITE) { error("Illegal color value in putpixel: %d", color); } if (SDL_LockSurface(surface) < 0) { sdl_error("SDL_LockSurface"); } pixel = ((uint8_t *) surface->pixels) + y * surface->pitch + x * SURFACE_BPP; *(Uint32 *) pixel = bgi_colors[color]; SDL_UnlockSurface(surface); SDL_Flip(surface); } int getcolor(void) { // TODO: Implement return 0; } void setcolor(int color) { // TODO: Implement } void getimage(int left, int top, int right, int bottom, void *pic) { // TODO: Implement } void putimage(int left, int top, void *pic, int mode) { // TODO: Implement } size_t imagesize(int left, int top, int right, int bottom) { // TODO: Implement return 0; } void line(int a_x, int a_y, int b_x, int b_y) { // TODO: Implement } void rectangle(int left, int top, int right, int bottom) { // TODO: Implement } void setfillstyle(int mode, int color) { // TODO: Implement } void floodfill(int x, int y, int color) { // TODO: Implement } void outtextxy(int x, int y, const char *text) { // TODO: Implement } int GetKeyState(int key) { // TODO: Implement return 0; } void SetNormalKeysMode(void) { // no implementation necessary } void SetButtonKeysMode(void) { // no implementation necessary } void delay(int milliseconds) { // TODO: Implement } void cleardevice(void) { // TODO: Implement } void itoa(int num, char *str, int base) { // Only writing impl for base 10 conversion if (base != 10) { fprintf(stderr, "iota() only supports base 10 conversion\n"); exit(1); } // Stupid unsafe itoa has no buffer size parameter, so we have // to use sprintf instead of snprintf sprintf(str, "%d", num); } static void _error(long line, const char *fmt, ...) { va_list args; va_start(args, fmt); fprintf(stderr, "graphics.cpp error on line %ld: ", line); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); closegraph(); exit(1); } static void _sdl_error(long line, const char *name) { _error(line, "SDL function %s failed. Reason: %s", name, SDL_GetError()); } static void check_surface() { if (surface == NULL) { error("surface is null", NULL); } } static void check_bpp() { if (surface->format->BytesPerPixel != SURFACE_BPP) { error("Expecting %d bytes per pxiel. Got %d", SURFACE_BPP, surface->format->BytesPerPixel); } } <|endoftext|>
<commit_before>#include "utils.h" // <GL/glext.h> on Linux, <OpenGL/glext.h> on MacOS :( #include "../glfw/deps/GL/glext.h" #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <sstream> #include <fstream> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <defer.h> #include <unistd.h> #include <stb_image.h> void flipTexture(unsigned char *textureData, int width, int height, int n) { for(int h = 0; h < height/2; ++h) { for(int w = 0; w < width; ++w) { for(int i = 0; i < n; ++i) { int offset1 = (h*width + w)*n + i; int offset2 = ((height - h - 1)*width + w)*n + i; unsigned char t = textureData[offset1]; textureData[offset1] = textureData[offset2]; textureData[offset2] = t; } } } } bool loadCommonTexture(char const* fname, GLuint textureId) { return loadCommonTextureExt(fname, textureId, false); } bool loadCommonTextureExt(char const* fname, GLuint textureId, bool flip) { int width, height, n; unsigned char *textureData = stbi_load(fname, &width, &height, &n, 0); if(textureData == nullptr) { std::cout << "ERROR: loadCommonTextureExt failed, fname = " << fname << ", stbi_load returned nullptr" << std::endl; return false; } defer(stbi_image_free(textureData)); if(flip) flipTexture(textureData, width, height, n); glBindTexture(GL_TEXTURE_2D, textureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Generate mipmaps glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, 0); // unbind return true; } #define DDS_HEADER_SIZE 128 #define DDS_SIGNATURE 0x20534444 // "DDS " #define FORMAT_CODE_DXT1 0x31545844 // "DXT1" #define FORMAT_CODE_DXT3 0x33545844 // "DXT3" #define FORMAT_CODE_DXT5 0x35545844 // "DXT5" bool loadDDSTexture(char const *fname, GLuint textureId) { int fd = open(fname, O_RDONLY, 0); if(fd < 0) { std::cout << "ERROR: loadDDSTexture - open failed, fname = " << fname << ", " << strerror(errno) << std::endl; return false; } defer(close(fd)); struct stat st; if(fstat(fd, &st) < 0) { std::cout << "ERROR: loadDDSTexture - fstat failed, fname = " << fname << ", " << strerror(errno) << std::endl; return false; } size_t fsize = (size_t)st.st_size; if(fsize < DDS_HEADER_SIZE) { std::cout << "ERROR: loadDDSTexture failed, fname = " << fname << ", fsize = " << fsize << ", less then DDS_HEADER_SIZE (" << DDS_HEADER_SIZE << ")" << std::endl; return false; } unsigned char* dataPtr = (unsigned char*)mmap(nullptr, fsize, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0); if(dataPtr == MAP_FAILED) { std::cout << "ERROR: loadDDSTexture - mmap failed, fname = " << fname << ", " << strerror(errno) << std::endl; return false; } defer(munmap(dataPtr, fsize)); unsigned int signature = *(unsigned int*)&(dataPtr[ 0]); unsigned int height = *(unsigned int*)&(dataPtr[12]); unsigned int width = *(unsigned int*)&(dataPtr[16]); unsigned int mipMapNumber = *(unsigned int*)&(dataPtr[28]); unsigned int formatCode = *(unsigned int*)&(dataPtr[84]); if(signature != DDS_SIGNATURE) { std::cout << "ERROR: loadDDSTexture failed, fname = " << fname << "invalid signature: 0x" << std::hex << signature << std::endl; return false; } unsigned int format; switch(formatCode) { case FORMAT_CODE_DXT1: format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; case FORMAT_CODE_DXT3: format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; case FORMAT_CODE_DXT5: format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; default: std::cout << "ERROR: loadDDSTexture failed, fname = " << fname << ", unknown formatCode: 0x" << std::hex << formatCode << std::endl; return false; } glBindTexture(GL_TEXTURE_2D, textureId); glPixelStorei(GL_UNPACK_ALIGNMENT,1); unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16; unsigned int offset = DDS_HEADER_SIZE; // load mipmaps for (unsigned int level = 0; level < mipMapNumber; ++level) { unsigned int size = ((width+3)/4)*((height+3)/4)*blockSize; if(fsize < offset + size) { std::cout << "ERROR: loadDDSTexture failed, fname = " << fname << ", fsize = " << fsize << ", level = " << level << ", offset = " << offset << ", size = " << size << std::endl; return false; } glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, 0, size, dataPtr + offset); width = width > 1 ? width >> 1 : 1; height = height > 1 ? height >> 1 : 1; offset += size; } // glBindTexture(GL_TEXTURE_2D, 0); // unbind return true; } bool checkShaderCompileStatus(GLuint obj) { GLint status; glGetShaderiv(obj, GL_COMPILE_STATUS, &status); if(status == GL_FALSE) { GLint length; glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &length); std::vector<char> log((unsigned long)length); glGetShaderInfoLog(obj, length, &length, &log[0]); std::cerr << &log[0]; return true; } return false; } bool checkProgramLinkStatus(GLuint obj) { GLint status; glGetProgramiv(obj, GL_LINK_STATUS, &status); if(status == GL_FALSE) { GLint length; glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &length); std::vector<char> log((unsigned long) length); glGetProgramInfoLog(obj, length, &length, &log[0]); std::cerr << &log[0]; return true; } return false; } GLuint loadShader(char const *fname, GLenum shaderType, bool *errorFlagPtr) { std::ifstream fileStream(fname); std::stringstream buffer; buffer << fileStream.rdbuf(); std::string shaderSource(buffer.str()); GLuint shaderId = glCreateShader(shaderType); const GLchar * const shaderSourceCStr = shaderSource.c_str(); glShaderSource(shaderId, 1, &shaderSourceCStr, nullptr); glCompileShader(shaderId); *errorFlagPtr = checkShaderCompileStatus(shaderId); if(*errorFlagPtr) { glDeleteShader(shaderId); return 0; } return shaderId; } GLuint prepareProgram(const std::vector<GLuint>& shaders, bool *errorFlagPtr) { *errorFlagPtr = false; GLuint programId = glCreateProgram(); for(auto it = shaders.cbegin(); it != shaders.cend(); ++it) { glAttachShader(programId, *it); } glLinkProgram(programId); *errorFlagPtr = checkProgramLinkStatus(programId); if(*errorFlagPtr) { glDeleteProgram(programId); return 0; } return programId; } <commit_msg>There is no MAP_POPILATE on Mac<commit_after>#include "utils.h" // <GL/glext.h> on Linux, <OpenGL/glext.h> on MacOS :( #include "../glfw/deps/GL/glext.h" #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <sstream> #include <fstream> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <defer.h> #include <unistd.h> #include <stb_image.h> void flipTexture(unsigned char *textureData, int width, int height, int n) { for(int h = 0; h < height/2; ++h) { for(int w = 0; w < width; ++w) { for(int i = 0; i < n; ++i) { int offset1 = (h*width + w)*n + i; int offset2 = ((height - h - 1)*width + w)*n + i; unsigned char t = textureData[offset1]; textureData[offset1] = textureData[offset2]; textureData[offset2] = t; } } } } bool loadCommonTexture(char const* fname, GLuint textureId) { return loadCommonTextureExt(fname, textureId, false); } bool loadCommonTextureExt(char const* fname, GLuint textureId, bool flip) { int width, height, n; unsigned char *textureData = stbi_load(fname, &width, &height, &n, 0); if(textureData == nullptr) { std::cout << "ERROR: loadCommonTextureExt failed, fname = " << fname << ", stbi_load returned nullptr" << std::endl; return false; } defer(stbi_image_free(textureData)); if(flip) flipTexture(textureData, width, height, n); glBindTexture(GL_TEXTURE_2D, textureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Generate mipmaps glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, 0); // unbind return true; } #define DDS_HEADER_SIZE 128 #define DDS_SIGNATURE 0x20534444 // "DDS " #define FORMAT_CODE_DXT1 0x31545844 // "DXT1" #define FORMAT_CODE_DXT3 0x33545844 // "DXT3" #define FORMAT_CODE_DXT5 0x35545844 // "DXT5" bool loadDDSTexture(char const *fname, GLuint textureId) { int fd = open(fname, O_RDONLY, 0); if(fd < 0) { std::cout << "ERROR: loadDDSTexture - open failed, fname = " << fname << ", " << strerror(errno) << std::endl; return false; } defer(close(fd)); struct stat st; if(fstat(fd, &st) < 0) { std::cout << "ERROR: loadDDSTexture - fstat failed, fname = " << fname << ", " << strerror(errno) << std::endl; return false; } size_t fsize = (size_t)st.st_size; if(fsize < DDS_HEADER_SIZE) { std::cout << "ERROR: loadDDSTexture failed, fname = " << fname << ", fsize = " << fsize << ", less then DDS_HEADER_SIZE (" << DDS_HEADER_SIZE << ")" << std::endl; return false; } unsigned char* dataPtr = (unsigned char*)mmap(nullptr, fsize, PROT_READ, MAP_PRIVATE, fd, 0); if(dataPtr == MAP_FAILED) { std::cout << "ERROR: loadDDSTexture - mmap failed, fname = " << fname << ", " << strerror(errno) << std::endl; return false; } defer(munmap(dataPtr, fsize)); unsigned int signature = *(unsigned int*)&(dataPtr[ 0]); unsigned int height = *(unsigned int*)&(dataPtr[12]); unsigned int width = *(unsigned int*)&(dataPtr[16]); unsigned int mipMapNumber = *(unsigned int*)&(dataPtr[28]); unsigned int formatCode = *(unsigned int*)&(dataPtr[84]); if(signature != DDS_SIGNATURE) { std::cout << "ERROR: loadDDSTexture failed, fname = " << fname << "invalid signature: 0x" << std::hex << signature << std::endl; return false; } unsigned int format; switch(formatCode) { case FORMAT_CODE_DXT1: format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; case FORMAT_CODE_DXT3: format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; case FORMAT_CODE_DXT5: format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; default: std::cout << "ERROR: loadDDSTexture failed, fname = " << fname << ", unknown formatCode: 0x" << std::hex << formatCode << std::endl; return false; } glBindTexture(GL_TEXTURE_2D, textureId); glPixelStorei(GL_UNPACK_ALIGNMENT,1); unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16; unsigned int offset = DDS_HEADER_SIZE; // load mipmaps for (unsigned int level = 0; level < mipMapNumber; ++level) { unsigned int size = ((width+3)/4)*((height+3)/4)*blockSize; if(fsize < offset + size) { std::cout << "ERROR: loadDDSTexture failed, fname = " << fname << ", fsize = " << fsize << ", level = " << level << ", offset = " << offset << ", size = " << size << std::endl; return false; } glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, 0, size, dataPtr + offset); width = width > 1 ? width >> 1 : 1; height = height > 1 ? height >> 1 : 1; offset += size; } // glBindTexture(GL_TEXTURE_2D, 0); // unbind return true; } bool checkShaderCompileStatus(GLuint obj) { GLint status; glGetShaderiv(obj, GL_COMPILE_STATUS, &status); if(status == GL_FALSE) { GLint length; glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &length); std::vector<char> log((unsigned long)length); glGetShaderInfoLog(obj, length, &length, &log[0]); std::cerr << &log[0]; return true; } return false; } bool checkProgramLinkStatus(GLuint obj) { GLint status; glGetProgramiv(obj, GL_LINK_STATUS, &status); if(status == GL_FALSE) { GLint length; glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &length); std::vector<char> log((unsigned long) length); glGetProgramInfoLog(obj, length, &length, &log[0]); std::cerr << &log[0]; return true; } return false; } GLuint loadShader(char const *fname, GLenum shaderType, bool *errorFlagPtr) { std::ifstream fileStream(fname); std::stringstream buffer; buffer << fileStream.rdbuf(); std::string shaderSource(buffer.str()); GLuint shaderId = glCreateShader(shaderType); const GLchar * const shaderSourceCStr = shaderSource.c_str(); glShaderSource(shaderId, 1, &shaderSourceCStr, nullptr); glCompileShader(shaderId); *errorFlagPtr = checkShaderCompileStatus(shaderId); if(*errorFlagPtr) { glDeleteShader(shaderId); return 0; } return shaderId; } GLuint prepareProgram(const std::vector<GLuint>& shaders, bool *errorFlagPtr) { *errorFlagPtr = false; GLuint programId = glCreateProgram(); for(auto it = shaders.cbegin(); it != shaders.cend(); ++it) { glAttachShader(programId, *it); } glLinkProgram(programId); *errorFlagPtr = checkProgramLinkStatus(programId); if(*errorFlagPtr) { glDeleteProgram(programId); return 0; } return programId; } <|endoftext|>
<commit_before>#include <vnl/vnl_matrix_fixed.txx> template class vnl_matrix_fixed<double,1,1>; <commit_msg>BUG: This source should use VNL_MATRIX_FIXED_INSTANTIATE to create the instantiation.<commit_after>#include <vnl/vnl_matrix_fixed.txx> VNL_MATRIX_FIXED_INSTANTIATE(double,1,1); <|endoftext|>
<commit_before>/*********************************************** Copyright (C) 2014 Schutz Sacha This file is part of QJsonModel (https://github.com/dridk/QJsonmodel). QJsonModel 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. QJsonModel 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 QJsonModel. If not, see <http://www.gnu.org/licenses/>. **********************************************/ #include "qjsonmodel.h" #include <QFile> #include <QDebug> #include <QJsonDocument> #include <QJsonObject> #include <QIcon> #include <QFont> QJsonModel::QJsonModel(QObject *parent) : QAbstractItemModel(parent) { mRootItem = new QJsonTreeItem; mHeaders.append("key"); mHeaders.append("value"); } bool QJsonModel::load(const QString &fileName) { QFile file(fileName); bool success = false; if (file.open(QIODevice::ReadOnly)) { success = load(&file); file.close(); } else success = false; return success; } bool QJsonModel::load(QIODevice *device) { return loadJson(device->readAll()); } bool QJsonModel::loadJson(const QByteArray &json) { mDocument = QJsonDocument::fromJson(json); if (!mDocument.isNull()) { beginResetModel(); mRootItem = QJsonTreeItem::load(QJsonValue(mDocument.object())); endResetModel(); return true; } return false; } QVariant QJsonModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); QJsonTreeItem *item = static_cast<QJsonTreeItem*>(index.internalPointer()); if ((role == Qt::DecorationRole) && (index.column() == 0)){ return mTypeIcons.value(item->type()); } if (role == Qt::DisplayRole) { if (index.column() == 0) return QString("%1").arg(item->key()); if (index.column() == 1) return QString("%1").arg(item->value()); } return QVariant(); } QVariant QJsonModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { return mHeaders.value(section); } else return QVariant(); } QModelIndex QJsonModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); QJsonTreeItem *parentItem; if (!parent.isValid()) parentItem = mRootItem; else parentItem = static_cast<QJsonTreeItem*>(parent.internalPointer()); QJsonTreeItem *childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); else return QModelIndex(); } QModelIndex QJsonModel::parent(const QModelIndex &index) const { if (!index.isValid()) return QModelIndex(); QJsonTreeItem *childItem = static_cast<QJsonTreeItem*>(index.internalPointer()); QJsonTreeItem *parentItem = childItem->parent(); if (parentItem == mRootItem) return QModelIndex(); return createIndex(parentItem->row(), 0, parentItem); } int QJsonModel::rowCount(const QModelIndex &parent) const { QJsonTreeItem *parentItem; if (parent.column() > 0) return 0; if (!parent.isValid()) parentItem = mRootItem; else parentItem = static_cast<QJsonTreeItem*>(parent.internalPointer()); return parentItem->childCount(); } int QJsonModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 2; } void QJsonModel::setIcon(const QJsonValue::Type &type, const QIcon &icon) { mTypeIcons.insert(type,icon); } <commit_msg>Load root item either from array or object<commit_after>/*********************************************** Copyright (C) 2014 Schutz Sacha This file is part of QJsonModel (https://github.com/dridk/QJsonmodel). QJsonModel 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. QJsonModel 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 QJsonModel. If not, see <http://www.gnu.org/licenses/>. **********************************************/ #include "qjsonmodel.h" #include <QFile> #include <QDebug> #include <QJsonDocument> #include <QJsonObject> #include <QIcon> #include <QFont> QJsonModel::QJsonModel(QObject *parent) : QAbstractItemModel(parent) { mRootItem = new QJsonTreeItem; mHeaders.append("key"); mHeaders.append("value"); } bool QJsonModel::load(const QString &fileName) { QFile file(fileName); bool success = false; if (file.open(QIODevice::ReadOnly)) { success = load(&file); file.close(); } else success = false; return success; } bool QJsonModel::load(QIODevice *device) { return loadJson(device->readAll()); } bool QJsonModel::loadJson(const QByteArray &json) { mDocument = QJsonDocument::fromJson(json); if (!mDocument.isNull()) { beginResetModel(); if (mDocument.isArray()) { mRootItem = QJsonTreeItem::load(QJsonValue(mDocument.array())); } else { mRootItem = QJsonTreeItem::load(QJsonValue(mDocument.object())); } endResetModel(); return true; } return false; } QVariant QJsonModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); QJsonTreeItem *item = static_cast<QJsonTreeItem*>(index.internalPointer()); if ((role == Qt::DecorationRole) && (index.column() == 0)){ return mTypeIcons.value(item->type()); } if (role == Qt::DisplayRole) { if (index.column() == 0) return QString("%1").arg(item->key()); if (index.column() == 1) return QString("%1").arg(item->value()); } return QVariant(); } QVariant QJsonModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { return mHeaders.value(section); } else return QVariant(); } QModelIndex QJsonModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); QJsonTreeItem *parentItem; if (!parent.isValid()) parentItem = mRootItem; else parentItem = static_cast<QJsonTreeItem*>(parent.internalPointer()); QJsonTreeItem *childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); else return QModelIndex(); } QModelIndex QJsonModel::parent(const QModelIndex &index) const { if (!index.isValid()) return QModelIndex(); QJsonTreeItem *childItem = static_cast<QJsonTreeItem*>(index.internalPointer()); QJsonTreeItem *parentItem = childItem->parent(); if (parentItem == mRootItem) return QModelIndex(); return createIndex(parentItem->row(), 0, parentItem); } int QJsonModel::rowCount(const QModelIndex &parent) const { QJsonTreeItem *parentItem; if (parent.column() > 0) return 0; if (!parent.isValid()) parentItem = mRootItem; else parentItem = static_cast<QJsonTreeItem*>(parent.internalPointer()); return parentItem->childCount(); } int QJsonModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 2; } void QJsonModel::setIcon(const QJsonValue::Type &type, const QIcon &icon) { mTypeIcons.insert(type,icon); } <|endoftext|>
<commit_before>/** * kmcomposereditor.cpp * * Copyright (C) 2007, 2008 Laurent Montel <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "kmcomposereditor.h" #include "kmcomposewin.h" #include "kmcommands.h" #include "kmmsgdict.h" #include "kmfolder.h" #include "maillistdrag.h" #include <kmime/kmime_codecs.h> #include <KPIMTextEdit/EMailQuoteHighlighter> #include <KAction> #include <KActionCollection> #include <KFileDialog> #include <KLocale> #include <KMenu> #include <KMessageBox> #include <KPushButton> #include <QBuffer> #include <QClipboard> #include <QDropEvent> #include <QFileInfo> KMComposerEditor::KMComposerEditor( KMComposeWin *win,QWidget *parent) :KMeditor(parent),m_composerWin(win) { } KMComposerEditor::~KMComposerEditor() { } void KMComposerEditor::createActions( KActionCollection *actionCollection ) { KMeditor::createActions( actionCollection ); mPasteQuotation = new KAction( i18n("Pa&ste as Quotation"), this ); actionCollection->addAction("paste_quoted", mPasteQuotation ); connect( mPasteQuotation, SIGNAL(triggered(bool) ), this, SLOT( slotPasteAsQuotation()) ); mAddQuoteChars = new KAction( i18n("Add &Quote Characters"), this ); actionCollection->addAction( "tools_quote", mAddQuoteChars ); connect( mAddQuoteChars, SIGNAL(triggered(bool) ), this, SLOT(slotAddQuotes()) ); mRemQuoteChars = new KAction( i18n("Re&move Quote Characters"), this ); actionCollection->addAction( "tools_unquote", mRemQuoteChars ); connect (mRemQuoteChars, SIGNAL(triggered(bool) ), this, SLOT(slotRemoveQuotes()) ); } void KMComposerEditor::setHighlighterColors(KPIMTextEdit::EMailQuoteHighlighter * highlighter) { // defaults from kmreaderwin.cpp. FIXME: centralize somewhere. QColor color1( 0x00, 0x80, 0x00 ); QColor color2( 0x00, 0x70, 0x00 ); QColor color3( 0x00, 0x60, 0x00 ); QColor misspelled = Qt::red; if ( !GlobalSettings::self()->useDefaultColors() ) { KConfigGroup readerConfig( KMKernel::config(), "Reader" ); color3 = readerConfig.readEntry( "QuotedText3", color3 ); color2 = readerConfig.readEntry( "QuotedText2", color2 ); color1 = readerConfig.readEntry( "QuotedText1", color1 ); misspelled = readerConfig.readEntry( "MisspelledColor", misspelled ); } highlighter->setQuoteColor( Qt::black /* ignored anyway */, color3, color2, color1, misspelled ); } QString KMComposerEditor::smartQuote( const QString & msg ) { return m_composerWin->smartQuote( msg ); } const QString KMComposerEditor::defaultQuoteSign() const { if ( !m_quotePrefix.simplified().isEmpty() ) return m_quotePrefix; else return KPIMTextEdit::TextEdit::defaultQuoteSign(); } int KMComposerEditor::quoteLength( const QString& line ) const { if ( !m_quotePrefix.simplified().isEmpty() ) { if ( line.startsWith( m_quotePrefix ) ) return m_quotePrefix.length(); else return 0; } else return KPIMTextEdit::TextEdit::quoteLength( line ); } void KMComposerEditor::setQuotePrefixName( const QString &quotePrefix ) { m_quotePrefix = quotePrefix; } QString KMComposerEditor::quotePrefixName() const { if ( !m_quotePrefix.simplified().isEmpty() ) return m_quotePrefix; else return ">"; } void KMComposerEditor::replaceUnknownChars( const QTextCodec *codec ) { QTextCursor cursor( document() ); cursor.beginEditBlock(); while ( !cursor.atEnd() ) { cursor.movePosition( QTextCursor::NextCharacter, QTextCursor::KeepAnchor ); QChar cur = cursor.selectedText().at( 0 ); if ( !codec->canEncode( cur ) ) { cursor.insertText( "?" ); } else { cursor.clearSelection(); } } cursor.endEditBlock(); } bool KMComposerEditor::canInsertFromMimeData( const QMimeData *source ) const { if ( KPIM::MailList::canDecode( source ) ) return true; if ( source->hasFormat( "text/x-kmail-textsnippet" ) ) return true; if ( source->hasUrls() ) return true; return KPIMTextEdit::TextEdit::canInsertFromMimeData( source ); } void KMComposerEditor::insertFromMimeData( const QMimeData *source ) { // If this is a list of mails, attach those mails as forwards. if ( KPIM::MailList::canDecode( source ) ) { // Decode the list of serial numbers stored as the drag data QByteArray serNums = KPIM::MailList::serialsFromMimeData( source ); QBuffer serNumBuffer( &serNums ); serNumBuffer.open( QIODevice::ReadOnly ); QDataStream serNumStream( &serNumBuffer ); quint32 serNum; KMFolder *folder = 0; int idx; QList<KMMsgBase*> messageList; while ( !serNumStream.atEnd() ) { KMMsgBase *msgBase = 0; serNumStream >> serNum; KMMsgDict::instance()->getLocation( serNum, &folder, &idx ); if ( folder ) { msgBase = folder->getMsgBase( idx ); } if ( msgBase ) { messageList.append( msgBase ); } } serNumBuffer.close(); uint identity = folder ? folder->identity() : 0; KMCommand *command = new KMForwardAttachedCommand( m_composerWin, messageList, identity, m_composerWin ); command->start(); return; } if ( source->hasFormat( "text/x-kmail-textsnippet" ) ) { emit insertSnippet(); return; } // If this is a URL list, add those files as attachments or text const KUrl::List urlList = KUrl::List::fromMimeData( source ); if ( !urlList.isEmpty() ) { KMenu p; const QAction *addAsTextAction = p.addAction( i18n("Add as &Text") ); const QAction *addAsAttachmentAction = p.addAction( i18n("Add as &Attachment") ); const QAction *selectedAction = p.exec( QCursor::pos() ); if ( selectedAction == addAsTextAction ) { foreach( const KUrl &url, urlList ) { textCursor().insertText(url.url()); } } else if ( selectedAction == addAsAttachmentAction ) { foreach( const KUrl &url, urlList ) { m_composerWin->addAttach( url ); } } return; } KPIMTextEdit::TextEdit::insertFromMimeData(source); } #include "kmcomposereditor.moc" <commit_msg>Bring back the ability to drag images from KSnapshot and add them as attachments.<commit_after>/** * kmcomposereditor.cpp * * Copyright (C) 2007, 2008 Laurent Montel <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "kmcomposereditor.h" #include "kmcomposewin.h" #include "kmcommands.h" #include "kmmsgdict.h" #include "kmfolder.h" #include "maillistdrag.h" #include <kmime/kmime_codecs.h> #include <KPIMTextEdit/EMailQuoteHighlighter> #include <KAction> #include <KActionCollection> #include <KFileDialog> #include <KLocale> #include <KMenu> #include <KMessageBox> #include <KPushButton> #include <KInputDialog> #include <QBuffer> #include <QClipboard> #include <QDropEvent> #include <QFileInfo> KMComposerEditor::KMComposerEditor( KMComposeWin *win,QWidget *parent) :KMeditor(parent),m_composerWin(win) { } KMComposerEditor::~KMComposerEditor() { } void KMComposerEditor::createActions( KActionCollection *actionCollection ) { KMeditor::createActions( actionCollection ); mPasteQuotation = new KAction( i18n("Pa&ste as Quotation"), this ); actionCollection->addAction("paste_quoted", mPasteQuotation ); connect( mPasteQuotation, SIGNAL(triggered(bool) ), this, SLOT( slotPasteAsQuotation()) ); mAddQuoteChars = new KAction( i18n("Add &Quote Characters"), this ); actionCollection->addAction( "tools_quote", mAddQuoteChars ); connect( mAddQuoteChars, SIGNAL(triggered(bool) ), this, SLOT(slotAddQuotes()) ); mRemQuoteChars = new KAction( i18n("Re&move Quote Characters"), this ); actionCollection->addAction( "tools_unquote", mRemQuoteChars ); connect (mRemQuoteChars, SIGNAL(triggered(bool) ), this, SLOT(slotRemoveQuotes()) ); } void KMComposerEditor::setHighlighterColors(KPIMTextEdit::EMailQuoteHighlighter * highlighter) { // defaults from kmreaderwin.cpp. FIXME: centralize somewhere. QColor color1( 0x00, 0x80, 0x00 ); QColor color2( 0x00, 0x70, 0x00 ); QColor color3( 0x00, 0x60, 0x00 ); QColor misspelled = Qt::red; if ( !GlobalSettings::self()->useDefaultColors() ) { KConfigGroup readerConfig( KMKernel::config(), "Reader" ); color3 = readerConfig.readEntry( "QuotedText3", color3 ); color2 = readerConfig.readEntry( "QuotedText2", color2 ); color1 = readerConfig.readEntry( "QuotedText1", color1 ); misspelled = readerConfig.readEntry( "MisspelledColor", misspelled ); } highlighter->setQuoteColor( Qt::black /* ignored anyway */, color3, color2, color1, misspelled ); } QString KMComposerEditor::smartQuote( const QString & msg ) { return m_composerWin->smartQuote( msg ); } const QString KMComposerEditor::defaultQuoteSign() const { if ( !m_quotePrefix.simplified().isEmpty() ) return m_quotePrefix; else return KPIMTextEdit::TextEdit::defaultQuoteSign(); } int KMComposerEditor::quoteLength( const QString& line ) const { if ( !m_quotePrefix.simplified().isEmpty() ) { if ( line.startsWith( m_quotePrefix ) ) return m_quotePrefix.length(); else return 0; } else return KPIMTextEdit::TextEdit::quoteLength( line ); } void KMComposerEditor::setQuotePrefixName( const QString &quotePrefix ) { m_quotePrefix = quotePrefix; } QString KMComposerEditor::quotePrefixName() const { if ( !m_quotePrefix.simplified().isEmpty() ) return m_quotePrefix; else return ">"; } void KMComposerEditor::replaceUnknownChars( const QTextCodec *codec ) { QTextCursor cursor( document() ); cursor.beginEditBlock(); while ( !cursor.atEnd() ) { cursor.movePosition( QTextCursor::NextCharacter, QTextCursor::KeepAnchor ); QChar cur = cursor.selectedText().at( 0 ); if ( !codec->canEncode( cur ) ) { cursor.insertText( "?" ); } else { cursor.clearSelection(); } } cursor.endEditBlock(); } bool KMComposerEditor::canInsertFromMimeData( const QMimeData *source ) const { if ( source->hasImage() && source->hasFormat( "image/png" ) ) return true; if ( KPIM::MailList::canDecode( source ) ) return true; if ( source->hasFormat( "text/x-kmail-textsnippet" ) ) return true; if ( source->hasUrls() ) return true; return KPIMTextEdit::TextEdit::canInsertFromMimeData( source ); } void KMComposerEditor::insertFromMimeData( const QMimeData *source ) { // If this is a PNG image, either add it as an attachment or as an inline image if ( source->hasImage() && source->hasFormat( "image/png" ) ) { if ( textMode() == KRichTextEdit::Rich ) { KMenu menu; const QAction *addAsInlineImageAction = menu.addAction( i18n("Add as &Inline Image") ); /*const QAction *addAsAttachmentAction = */menu.addAction( i18n("Add as &Attachment") ); const QAction *selectedAction = menu.exec( QCursor::pos() ); if ( selectedAction == addAsInlineImageAction ) { // Let the textedit from kdepimlibs handle inline images KPIMTextEdit::TextEdit::insertFromMimeData( source ); return; } // else fall through } // Ok, when we reached this point, the user wants to add the image as an attachment. // Ask for the filename first. bool ok; const QString attName = KInputDialog::getText( "KMail", i18n( "Name of the attachment:" ), QString(), &ok, this ); if ( !ok ) { return; } const QByteArray imageData = source->data( "image/png" ); m_composerWin->addAttachment( attName, "base64", imageData, "image", "png", QByteArray(), QString(), QByteArray() ); return; } // If this is a list of mails, attach those mails as forwards. if ( KPIM::MailList::canDecode( source ) ) { // Decode the list of serial numbers stored as the drag data QByteArray serNums = KPIM::MailList::serialsFromMimeData( source ); QBuffer serNumBuffer( &serNums ); serNumBuffer.open( QIODevice::ReadOnly ); QDataStream serNumStream( &serNumBuffer ); quint32 serNum; KMFolder *folder = 0; int idx; QList<KMMsgBase*> messageList; while ( !serNumStream.atEnd() ) { KMMsgBase *msgBase = 0; serNumStream >> serNum; KMMsgDict::instance()->getLocation( serNum, &folder, &idx ); if ( folder ) { msgBase = folder->getMsgBase( idx ); } if ( msgBase ) { messageList.append( msgBase ); } } serNumBuffer.close(); uint identity = folder ? folder->identity() : 0; KMCommand *command = new KMForwardAttachedCommand( m_composerWin, messageList, identity, m_composerWin ); command->start(); return; } if ( source->hasFormat( "text/x-kmail-textsnippet" ) ) { emit insertSnippet(); return; } // If this is a URL list, add those files as attachments or text const KUrl::List urlList = KUrl::List::fromMimeData( source ); if ( !urlList.isEmpty() ) { KMenu p; const QAction *addAsTextAction = p.addAction( i18n("Add as &Text") ); const QAction *addAsAttachmentAction = p.addAction( i18n("Add as &Attachment") ); const QAction *selectedAction = p.exec( QCursor::pos() ); if ( selectedAction == addAsTextAction ) { foreach( const KUrl &url, urlList ) { textCursor().insertText(url.url()); } } else if ( selectedAction == addAsAttachmentAction ) { foreach( const KUrl &url, urlList ) { m_composerWin->addAttach( url ); } } return; } KPIMTextEdit::TextEdit::insertFromMimeData( source ); } #include "kmcomposereditor.moc" <|endoftext|>
<commit_before><commit_msg>sorted_vector: removing the vector::ersase makes more sense<commit_after><|endoftext|>
<commit_before>#include "~/gitRepos/night/sandbox/tests/testHeader.hpp" /* /* Testing " ' */ #define BOXIFY(x) \ { \ if ((x) >= 0.5) \ x -= 1.; \ else if ((x) < -0.5) \ x += 1.; \ } typedef int blah234; // 0.9899*sqrt(8.0*log(10.0))/(PI*freq); const tFloat hat_t0 = 1.3523661426929/freq; /* Testing 3 */ const tFloat &hat_t1 = hat_t0; occaFunction tFloat hatWavelet(tFloat t); occaFunction tFloat dummyFunction(shared tFloat t){ return 0; } occaFunction tFloat hatWavelet(tFloat t); occaFunction tFloat hatWavelet(tFloat t){ const tFloat pift = PI*freq*(t - hat_t0); const tFloat pift2 = pift*pift; double *psi @(dim(X,Y,Z), idxOrder(2,1,0)); psi(a,b,c); double *phi @dim(D); phi(blah + 1); double *delta @(dim(AI,BJ,BI,AJ), idxOrder(3,2,1,0)); for(int ai = 0; ai < 10; ++ai) @loopOrder("a", 1) { for(int bj = 0; bj < 10; ++bj) @loopOrder("b", 1) { for(int bi = 0; bi < 10; ++bi) @loopOrder("b", 0) { for(int aj = 0; aj < 10; ++aj) @loopOrder("a", 0) { delta(aj,bi,bj,ai) = 0; } } } } return (1. - 2.0*pift2)*exp(-pift2); } const int2 * const a34; float numberSamples[] = {1, +1, -1, 1., +1., -1., 1.0, -1.0, +1.0, 1.0f, -1.0f, +1.0f, 1.01F, -1.01F, +1.01F, 1l, -1l, +1l, 1.01L, -1.01L, +1.01L, 0b001, -0b010, +0b011, 0B100, -0B101, +0B110, 00001, -00010, +00011, 00100, -00101, +00110, 0x001, -0x010, +0x011, 0X100, -0X101, +0X110}; #if 1 occaKernel void fd2d(tFloat *u1, tFloat *u2, tFloat *u3, const texture tFloat tex1[], texture tFloat tex2[][], texture tFloat **tex3, const tFloat currentTime){ const int bDimX = 16; const int bDimY = 16 + bDimX; const int bDimZ = 16 + bDimY; const int lDimX = 16 + bDimY; int lDimY = lDimX; int lDimZ = lDimX + lDimY; double2 s[2]; BOXIFY(s[i].x); for(int n = 0; n < bDimX; ++n; tile(lDimX)){ } // for(int2 i(0,1); i.x < bDimX, i.y < bDimY; i.y += 2, ++i.x; tile(lDimX,lDimY)){ // } // for(int2 i(0,1); i.x < bDimX, i.y < bDimY; ++i; tile(lDimX,lDimY)){ // } for(int by = 0; by < bDimY; by += 16; outer0){ for(int bx = 0; bx < bDimX; bx += 16; outer1){ shared tFloat Lu[bDimY + 2*sr][bDimX + 2*sr]; exclusive tFloat r_u2 = 2, r_u3 = 3, r_u4[3], *r_u5, *r_u6[3]; for(int ly = by; ly < (by + lDimY); ++ly; inner1){ for(int lx = bx; lx < (by + lDimX); ++lx; inner0){ const int tx = bx * lDimX + lx; const int ty = by * lDimY + ly; float2 sj, si; float2 s = sj - si; Lu[0] = WR_MIN(Lu[tx], Lu[tx+512]); int y1, y2; { y1 = y2 = 0; } int tmpin = *u1; switch(y1){ case 0 : printf("0\n"); break; case 1 : {printf("1\n");} default: printf("default\n"); break; } switch(y2) case 0: printf("0\n"); const int id = ty*w + tx; float *__u1 = &u1[bDimX]; float *__u2 = (float*) (&(u1[bDimX])); float data = tex1[0][0]; tex1[0][0] = data; r_u2 = u2[id]; r_u3 = u3[id]; const int nX1 = (tx - sr + w) % w; const int nY1 = (ty - sr + h) % h; const int nX2 = (tx + bDimX - sr + w) % w; const int nY2 = (ty + bDimY - sr + h) % h; Lu[ly][lx] = u2[nY1*w + nX1]; if(lx < 2*sr){ Lu[ly][lx + bDimX] = u2[nY1*w + nX2]; if(ly < 2*sr) Lu[ly + bDimY][lx + bDimX] = u2[nY2*w + nX2]; } if(ly < 2*sr) Lu[ly + bDimY][lx] = u2[nY2*w + nX1]; a.b = 3; } } // barrier(localMemFence); for(int ly = 0; ly < lDimY; ++ly; inner1){ for(int lx = 0; lx < lDimX; ++lx; inner0){ const int tx = bx * lDimX + lx; const int ty = by * lDimY + ly; const int id = ty*w + tx; tFloat lap = 0.0; if(true) blah; else if(true) blah; else blah; for(int i = 0; i < (2*sr + 1); i++){ lap += xStencil[i]*Lu[ly + sr][lx + i] + xStencil[i]*Lu[ly + i][lx + sr]; if(i < 2) continue; break; } continue; for(int i = 0; i < (2*sr + 1); i++){ lap += xStencil[i]*Lu[ly + sr][lx + i] + xStencil[i]*Lu[ly + i][lx + sr]; } const tFloat u_n1 = (-tStencil[1]*r_u2 - tStencil[2]*r_u3 + lap)/tStencil[0]; if((tx == mX) && (ty == mY)) u1[id] = u_n1 + hatWavelet(currentTime, 1, 2)/tStencil[0]; else u1[id] = u_n1; } } } } } #endif <commit_msg>[Parser] Added e to the numberSamples in test.cpp<commit_after>#include "~/gitRepos/night/sandbox/tests/testHeader.hpp" /* /* Testing " ' */ #define BOXIFY(x) \ { \ if ((x) >= 0.5) \ x -= 1.; \ else if ((x) < -0.5) \ x += 1.; \ } typedef int blah234; // 0.9899*sqrt(8.0*log(10.0))/(PI*freq); const tFloat hat_t0 = 1.3523661426929/freq; /* Testing 3 */ const tFloat &hat_t1 = hat_t0; occaFunction tFloat hatWavelet(tFloat t); occaFunction tFloat dummyFunction(shared tFloat t){ return 0; } occaFunction tFloat hatWavelet(tFloat t); occaFunction tFloat hatWavelet(tFloat t){ const tFloat pift = PI*freq*(t - hat_t0); const tFloat pift2 = pift*pift; double *psi @(dim(X,Y,Z), idxOrder(2,1,0)); psi(a,b,c); double *phi @dim(D); phi(blah + 1); double *delta @(dim(BJ,BI,BJ,AI), idxOrder(3,2,1,0)); for(int ai = 0; ai < 10; ++ai) @loopOrder("a", 1) { for(int bj = 0; bj < 10; ++bj) @loopOrder("b", 1) { for(int bi = 0; bi < 10; ++bi) @loopOrder("b", 0) { for(int aj = 0; aj < 10; ++aj) @loopOrder("a", 0) { delta(aj,bi,bj,ai) = 0; } } } } return (1. - 2.0*pift2)*exp(-pift2); } const int2 * const a34; float numberSamples[] = {1, +1, -1, 1., +1., -1., 1.0, -1.0, +1.0, 1.0f, -1.0f, +1.0f, 1.01F, -1.01F, +1.01F, 1.0e1f, -1.0e-11f, +1.0e+111f, 1.0E1, -1.0E-11, +1.0E+111, 1.01F, -1.01F, +1.01F, 1l, -1l, +1l, 1.01L, -1.01L, +1.01L, 0b001, -0b010, +0b011, 0B100, -0B101, +0B110, 00001, -00010, +00011, 00100, -00101, +00110, 0x001, -0x010, +0x011, 0X100, -0X101, +0X110}; #if 1 occaKernel void fd2d(tFloat *u1, tFloat *u2, tFloat *u3, const texture tFloat tex1[], texture tFloat tex2[][], texture tFloat **tex3, const tFloat currentTime){ const int bDimX = 16; const int bDimY = 16 + bDimX; const int bDimZ = 16 + bDimY; const int lDimX = 16 + bDimY; int lDimY = lDimX; int lDimZ = lDimX + lDimY; double2 s[2]; BOXIFY(s[i].x); for(int n = 0; n < bDimX; ++n; tile(lDimX)){ } // for(int2 i(0,1); i.x < bDimX, i.y < bDimY; i.y += 2, ++i.x; tile(lDimX,lDimY)){ // } // for(int2 i(0,1); i.x < bDimX, i.y < bDimY; ++i; tile(lDimX,lDimY)){ // } for(int by = 0; by < bDimY; by += 16; outer0){ for(int bx = 0; bx < bDimX; bx += 16; outer1){ shared tFloat Lu[bDimY + 2*sr][bDimX + 2*sr]; exclusive tFloat r_u2 = 2, r_u3 = 3, r_u4[3], *r_u5, *r_u6[3]; for(int ly = by; ly < (by + lDimY); ++ly; inner1){ for(int lx = bx; lx < (by + lDimX); ++lx; inner0){ const int tx = bx * lDimX + lx; const int ty = by * lDimY + ly; float2 sj, si; float2 s = sj - si; Lu[0] = WR_MIN(Lu[tx], Lu[tx+512]); int y1, y2; { y1 = y2 = 0; } int tmpin = *u1; switch(y1){ case 0 : printf("0\n"); break; case 1 : {printf("1\n");} default: printf("default\n"); break; } switch(y2) case 0: printf("0\n"); const int id = ty*w + tx; float *__u1 = &u1[bDimX]; float *__u2 = (float*) (&(u1[bDimX])); float data = tex1[0][0]; tex1[0][0] = data; r_u2 = u2[id]; r_u3 = u3[id]; const int nX1 = (tx - sr + w) % w; const int nY1 = (ty - sr + h) % h; const int nX2 = (tx + bDimX - sr + w) % w; const int nY2 = (ty + bDimY - sr + h) % h; Lu[ly][lx] = u2[nY1*w + nX1]; if(lx < 2*sr){ Lu[ly][lx + bDimX] = u2[nY1*w + nX2]; if(ly < 2*sr) Lu[ly + bDimY][lx + bDimX] = u2[nY2*w + nX2]; } if(ly < 2*sr) Lu[ly + bDimY][lx] = u2[nY2*w + nX1]; a.b = 3; } } // barrier(localMemFence); for(int ly = 0; ly < lDimY; ++ly; inner1){ for(int lx = 0; lx < lDimX; ++lx; inner0){ const int tx = bx * lDimX + lx; const int ty = by * lDimY + ly; const int id = ty*w + tx; tFloat lap = 0.0; if(true) blah; else if(true) blah; else blah; for(int i = 0; i < (2*sr + 1); i++){ lap += xStencil[i]*Lu[ly + sr][lx + i] + xStencil[i]*Lu[ly + i][lx + sr]; if(i < 2) continue; break; } continue; for(int i = 0; i < (2*sr + 1); i++){ lap += xStencil[i]*Lu[ly + sr][lx + i] + xStencil[i]*Lu[ly + i][lx + sr]; } const tFloat u_n1 = (-tStencil[1]*r_u2 - tStencil[2]*r_u3 + lap)/tStencil[0]; if((tx == mX) && (ty == mY)) u1[id] = u_n1 + hatWavelet(currentTime, 1, 2)/tStencil[0]; else u1[id] = u_n1; } } } } } #endif <|endoftext|>
<commit_before>#include "llvm/Pass.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/DenseSet.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/TypeBuilder.h" using namespace llvm; namespace { struct PointerObservation : public FunctionPass { static char ID; PointerObservation() : FunctionPass(ID) {} bool runOnFunction(Function& f) override { // Identify injection points DenseSet<Instruction*> pointerInstructions; for(BasicBlock &bb : f) { for(Instruction &i : bb) { if (GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(&i)) { pointerInstructions.insert(gep); } } } // Inject instructions for (Instruction *i : pointerInstructions) { errs() << "Injections print operation\n"; IRBuilder<> builder(i); Function *printfFunction = getPrintFPrototype(i->getContext(), i->getModule()); builder.CreateCall(printfFunction, geti8StrVal(*i->getModule(), "test\n", "name")); } return true; } Function *getPrintFPrototype(LLVMContext &ctx, Module *mod) { FunctionType *printf_type = TypeBuilder<int(char*, ...), false>::get(getGlobalContext()); Function *func = cast<Function>(mod->getOrInsertFunction("printf", printf_type, AttributeSet().addAttribute(mod->getContext(), 1U, Attribute::NoAlias))); return func; } Constant* geti8StrVal(Module& M, char const* str, Twine const& name) { LLVMContext& ctx = getGlobalContext(); Constant* strConstant = ConstantDataArray::getString(ctx, str); GlobalVariable* GVStr = new GlobalVariable(M, strConstant->getType(), true, GlobalValue::InternalLinkage, strConstant, name); Constant* zero = Constant::getNullValue(IntegerType::getInt32Ty(ctx)); Constant* indices[] = {zero, zero}; Constant* strVal = ConstantExpr::getGetElementPtr(Type::getInt8PtrTy(ctx), GVStr, indices, true); return strVal; } }; } char PointerObservation::ID = 0; static RegisterPass<PointerObservation> X("PointerObservation", "Injects print calls before pointer operations", false, false);<commit_msg>Corrected strings<commit_after>#include "llvm/Pass.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/DenseSet.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/TypeBuilder.h" using namespace llvm; namespace { struct PointerObservation : public FunctionPass { static char ID; PointerObservation() : FunctionPass(ID) {} bool runOnFunction(Function& f) override { // Identify injection points DenseSet<Instruction*> pointerInstructions; for(BasicBlock &bb : f) { for(Instruction &i : bb) { if (GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(&i)) { pointerInstructions.insert(gep); } } } // Inject instructions for (Instruction *i : pointerInstructions) { errs() << "Injecting print operation\n"; IRBuilder<> builder(i); Function *printfFunction = getPrintFPrototype(i->getContext(), i->getModule()); builder.CreateCall(printfFunction, geti8StrVal(*i->getModule(), "Pointer instruction\n", "name")); } return true; } Function *getPrintFPrototype(LLVMContext &ctx, Module *mod) { FunctionType *printf_type = TypeBuilder<int(char*, ...), false>::get(getGlobalContext()); Function *func = cast<Function>(mod->getOrInsertFunction("printf", printf_type, AttributeSet().addAttribute(mod->getContext(), 1U, Attribute::NoAlias))); return func; } Constant* geti8StrVal(Module& M, char const* str, Twine const& name) { LLVMContext& ctx = getGlobalContext(); Constant* strConstant = ConstantDataArray::getString(ctx, str); GlobalVariable* GVStr = new GlobalVariable(M, strConstant->getType(), true, GlobalValue::InternalLinkage, strConstant, name); Constant* zero = Constant::getNullValue(IntegerType::getInt32Ty(ctx)); Constant* indices[] = {zero, zero}; Constant* strVal = ConstantExpr::getGetElementPtr(Type::getInt8PtrTy(ctx), GVStr, indices, true); return strVal; } }; } char PointerObservation::ID = 0; static RegisterPass<PointerObservation> X("PointerObservation", "Injects print calls before pointer operations", false, false);<|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "BenchTimer.h" #include "PictureBenchmark.h" #include "SkBenchLogger.h" #include "SkCanvas.h" #include "SkGraphics.h" #include "SkMath.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkStream.h" #include "SkTArray.h" #include "picture_utils.h" const int DEFAULT_REPEATS = 100; static void usage(const char* argv0) { SkDebugf("SkPicture benchmarking tool\n"); SkDebugf("\n" "Usage: \n" " %s <inputDir>...\n" " [--logFile filename][--timers [wcgWC]*][--logPerIter 1|0][--min]\n" " [--repeat] \n" " [--mode pow2tile minWidth height[] (multi) | record | simple\n" " | tile width[] height[] (multi) | playbackCreation]\n" " [--pipe]\n" " [--device bitmap" #if SK_SUPPORT_GPU " | gpu" #endif "]" , argv0); SkDebugf("\n\n"); SkDebugf( " inputDir: A list of directories and files to use as input. Files are\n" " expected to have the .skp extension.\n\n" " --logFile filename : destination for writing log output, in addition to stdout.\n"); SkDebugf(" --logPerIter 1|0 : " "Log each repeat timer instead of mean, default is disabled.\n"); SkDebugf(" --min : Print the minimum times (instead of average).\n"); SkDebugf(" --timers [wcgWC]* : " "Display wall, cpu, gpu, truncated wall or truncated cpu time for each picture.\n"); SkDebugf( " --mode pow2tile minWidht height[] (multi) | record | simple\n" " | tile width[] height[] (multi) | playbackCreation:\n" " Run in the corresponding mode.\n" " Default is simple.\n"); SkDebugf( " pow2tile minWidth height[], Creates tiles with widths\n" " that are all a power of two\n" " such that they minimize the\n" " amount of wasted tile space.\n" " minWidth is the minimum width\n" " of these tiles and must be a\n" " power of two. Simple\n" " rendering using these tiles\n" " is benchmarked.\n" " Append \"multi\" for multithreaded\n" " drawing.\n"); SkDebugf( " record, Benchmark picture to picture recording.\n"); SkDebugf( " simple, Benchmark a simple rendering.\n"); SkDebugf( " tile width[] height[], Benchmark simple rendering using\n" " tiles with the given dimensions.\n" " Append \"multi\" for multithreaded\n" " drawing.\n"); SkDebugf( " playbackCreation, Benchmark creation of the SkPicturePlayback.\n"); SkDebugf("\n"); SkDebugf( " --pipe: Benchmark SkGPipe rendering. Compatible with tiled, multithreaded rendering.\n"); SkDebugf( " --device bitmap" #if SK_SUPPORT_GPU " | gpu" #endif ": Use the corresponding device. Default is bitmap.\n"); SkDebugf( " bitmap, Render to a bitmap.\n"); #if SK_SUPPORT_GPU SkDebugf( " gpu, Render to the GPU.\n"); #endif SkDebugf("\n"); SkDebugf( " --repeat: " "Set the number of times to repeat each test." " Default is %i.\n", DEFAULT_REPEATS); } SkBenchLogger gLogger; static void run_single_benchmark(const SkString& inputPath, sk_tools::PictureBenchmark& benchmark) { SkFILEStream inputStream; inputStream.setPath(inputPath.c_str()); if (!inputStream.isValid()) { SkString err; err.printf("Could not open file %s\n", inputPath.c_str()); gLogger.logError(err); return; } SkPicture picture(&inputStream); SkString filename; sk_tools::get_basename(&filename, inputPath); SkString result; result.printf("running bench [%i %i] %s ", picture.width(), picture.height(), filename.c_str()); gLogger.logProgress(result); benchmark.run(&picture); } static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs, sk_tools::PictureBenchmark* benchmark) { const char* argv0 = argv[0]; char* const* stop = argv + argc; int repeats = DEFAULT_REPEATS; sk_tools::PictureRenderer::SkDeviceTypes deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType; sk_tools::PictureRenderer* renderer = NULL; // Create a string to show our current settings. // TODO: Make it prettier. Currently it just repeats the command line. SkString commandLine("bench_pictures:"); for (int i = 1; i < argc; i++) { commandLine.appendf(" %s", *(argv+i)); } commandLine.append("\n"); bool usePipe = false; bool multiThreaded = false; bool useTiles = false; const char* widthString = NULL; const char* heightString = NULL; bool isPowerOf2Mode = false; const char* mode = NULL; for (++argv; argv < stop; ++argv) { if (0 == strcmp(*argv, "--repeat")) { ++argv; if (argv < stop) { repeats = atoi(*argv); if (repeats < 1) { gLogger.logError("--repeat must be given a value > 0\n"); exit(-1); } } else { gLogger.logError("Missing arg for --repeat\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--pipe")) { usePipe = true; } else if (0 == strcmp(*argv, "--logFile")) { argv++; if (argv < stop) { if (!gLogger.SetLogFile(*argv)) { SkString str; str.printf("Could not open %s for writing.", *argv); gLogger.logError(str); usage(argv0); exit(-1); } } else { gLogger.logError("Missing arg for --logFile\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--mode")) { ++argv; if (argv >= stop) { gLogger.logError("Missing mode for --mode\n"); usage(argv0); exit(-1); } if (0 == strcmp(*argv, "record")) { renderer = SkNEW(sk_tools::RecordPictureRenderer); } else if (0 == strcmp(*argv, "simple")) { renderer = SkNEW(sk_tools::SimplePictureRenderer); } else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) { useTiles = true; mode = *argv; if (0 == strcmp(*argv, "pow2tile")) { isPowerOf2Mode = true; } ++argv; if (argv >= stop) { SkString err; err.printf("Missing width for --mode %s\n", mode); gLogger.logError(err); usage(argv0); exit(-1); } widthString = *argv; ++argv; if (argv >= stop) { gLogger.logError("Missing height for --mode tile\n"); usage(argv0); exit(-1); } heightString = *argv; ++argv; if (argv < stop && 0 == strcmp(*argv, "multi")) { multiThreaded = true; } else { --argv; } } else if (0 == strcmp(*argv, "playbackCreation")) { renderer = SkNEW(sk_tools::PlaybackCreationRenderer); } else { SkString err; err.printf("%s is not a valid mode for --mode\n", *argv); gLogger.logError(err); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--device")) { ++argv; if (argv >= stop) { gLogger.logError("Missing mode for --deivce\n"); usage(argv0); exit(-1); } if (0 == strcmp(*argv, "bitmap")) { deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType; } #if SK_SUPPORT_GPU else if (0 == strcmp(*argv, "gpu")) { deviceType = sk_tools::PictureRenderer::kGPU_DeviceType; } #endif else { SkString err; err.printf("%s is not a valid mode for --device\n", *argv); gLogger.logError(err); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--timers")) { ++argv; if (argv < stop) { bool timerWall = false; bool truncatedTimerWall = false; bool timerCpu = false; bool truncatedTimerCpu = false; bool timerGpu = false; for (char* t = *argv; *t; ++t) { switch (*t) { case 'w': timerWall = true; break; case 'c': timerCpu = true; break; case 'W': truncatedTimerWall = true; break; case 'C': truncatedTimerCpu = true; break; case 'g': timerGpu = true; break; default: { break; } } } benchmark->setTimersToShow(timerWall, truncatedTimerWall, timerCpu, truncatedTimerCpu, timerGpu); } else { gLogger.logError("Missing arg for --timers\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--min")) { benchmark->setPrintMin(true); } else if (0 == strcmp(*argv, "--logPerIter")) { ++argv; if (argv < stop) { bool log = atoi(*argv) != 0; benchmark->setLogPerIter(log); } else { gLogger.logError("Missing arg for --logPerIter\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) { usage(argv0); exit(0); } else { inputs->push_back(SkString(*argv)); } } if (useTiles) { SkASSERT(NULL == renderer); sk_tools::TiledPictureRenderer* tiledRenderer = SkNEW(sk_tools::TiledPictureRenderer); if (isPowerOf2Mode) { int minWidth = atoi(widthString); if (!SkIsPow2(minWidth) || minWidth < 0) { tiledRenderer->unref(); SkString err; err.printf("-mode %s must be given a width" " value that is a power of two\n", mode); gLogger.logError(err); exit(-1); } tiledRenderer->setTileMinPowerOf2Width(minWidth); } else if (sk_tools::is_percentage(widthString)) { tiledRenderer->setTileWidthPercentage(atof(widthString)); if (!(tiledRenderer->getTileWidthPercentage() > 0)) { tiledRenderer->unref(); gLogger.logError("--mode tile must be given a width percentage > 0\n"); exit(-1); } } else { tiledRenderer->setTileWidth(atoi(widthString)); if (!(tiledRenderer->getTileWidth() > 0)) { tiledRenderer->unref(); gLogger.logError("--mode tile must be given a width > 0\n"); exit(-1); } } if (sk_tools::is_percentage(heightString)) { tiledRenderer->setTileHeightPercentage(atof(heightString)); if (!(tiledRenderer->getTileHeightPercentage() > 0)) { tiledRenderer->unref(); gLogger.logError("--mode tile must be given a height percentage > 0\n"); exit(-1); } } else { tiledRenderer->setTileHeight(atoi(heightString)); if (!(tiledRenderer->getTileHeight() > 0)) { tiledRenderer->unref(); gLogger.logError("--mode tile must be given a height > 0\n"); exit(-1); } } tiledRenderer->setMultiThreaded(multiThreaded); tiledRenderer->setUsePipe(usePipe); renderer = tiledRenderer; } else if (usePipe) { renderer = SkNEW(sk_tools::PipePictureRenderer); } if (inputs->count() < 1) { SkDELETE(benchmark); usage(argv0); exit(-1); } if (NULL == renderer) { renderer = SkNEW(sk_tools::SimplePictureRenderer); } benchmark->setRenderer(renderer)->unref(); benchmark->setRepeats(repeats); benchmark->setDeviceType(deviceType); benchmark->setLogger(&gLogger); // Report current settings: gLogger.logProgress(commandLine); } static void process_input(const SkString& input, sk_tools::PictureBenchmark& benchmark) { SkOSFile::Iter iter(input.c_str(), "skp"); SkString inputFilename; if (iter.next(&inputFilename)) { do { SkString inputPath; sk_tools::make_filepath(&inputPath, input, inputFilename); run_single_benchmark(inputPath, benchmark); } while(iter.next(&inputFilename)); } else { run_single_benchmark(input, benchmark); } } int main(int argc, char* const argv[]) { #ifdef SK_ENABLE_INST_COUNT gPrintInstCount = true; #endif SkAutoGraphics ag; SkTArray<SkString> inputs; sk_tools::PictureBenchmark benchmark; parse_commandline(argc, argv, &inputs, &benchmark); for (int i = 0; i < inputs.count(); ++i) { process_input(inputs[i], benchmark); } } <commit_msg>Do not exit on failure to open logFile<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "BenchTimer.h" #include "PictureBenchmark.h" #include "SkBenchLogger.h" #include "SkCanvas.h" #include "SkGraphics.h" #include "SkMath.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkStream.h" #include "SkTArray.h" #include "picture_utils.h" const int DEFAULT_REPEATS = 100; static void usage(const char* argv0) { SkDebugf("SkPicture benchmarking tool\n"); SkDebugf("\n" "Usage: \n" " %s <inputDir>...\n" " [--logFile filename][--timers [wcgWC]*][--logPerIter 1|0][--min]\n" " [--repeat] \n" " [--mode pow2tile minWidth height[] (multi) | record | simple\n" " | tile width[] height[] (multi) | playbackCreation]\n" " [--pipe]\n" " [--device bitmap" #if SK_SUPPORT_GPU " | gpu" #endif "]" , argv0); SkDebugf("\n\n"); SkDebugf( " inputDir: A list of directories and files to use as input. Files are\n" " expected to have the .skp extension.\n\n" " --logFile filename : destination for writing log output, in addition to stdout.\n"); SkDebugf(" --logPerIter 1|0 : " "Log each repeat timer instead of mean, default is disabled.\n"); SkDebugf(" --min : Print the minimum times (instead of average).\n"); SkDebugf(" --timers [wcgWC]* : " "Display wall, cpu, gpu, truncated wall or truncated cpu time for each picture.\n"); SkDebugf( " --mode pow2tile minWidht height[] (multi) | record | simple\n" " | tile width[] height[] (multi) | playbackCreation:\n" " Run in the corresponding mode.\n" " Default is simple.\n"); SkDebugf( " pow2tile minWidth height[], Creates tiles with widths\n" " that are all a power of two\n" " such that they minimize the\n" " amount of wasted tile space.\n" " minWidth is the minimum width\n" " of these tiles and must be a\n" " power of two. Simple\n" " rendering using these tiles\n" " is benchmarked.\n" " Append \"multi\" for multithreaded\n" " drawing.\n"); SkDebugf( " record, Benchmark picture to picture recording.\n"); SkDebugf( " simple, Benchmark a simple rendering.\n"); SkDebugf( " tile width[] height[], Benchmark simple rendering using\n" " tiles with the given dimensions.\n" " Append \"multi\" for multithreaded\n" " drawing.\n"); SkDebugf( " playbackCreation, Benchmark creation of the SkPicturePlayback.\n"); SkDebugf("\n"); SkDebugf( " --pipe: Benchmark SkGPipe rendering. Compatible with tiled, multithreaded rendering.\n"); SkDebugf( " --device bitmap" #if SK_SUPPORT_GPU " | gpu" #endif ": Use the corresponding device. Default is bitmap.\n"); SkDebugf( " bitmap, Render to a bitmap.\n"); #if SK_SUPPORT_GPU SkDebugf( " gpu, Render to the GPU.\n"); #endif SkDebugf("\n"); SkDebugf( " --repeat: " "Set the number of times to repeat each test." " Default is %i.\n", DEFAULT_REPEATS); } SkBenchLogger gLogger; static void run_single_benchmark(const SkString& inputPath, sk_tools::PictureBenchmark& benchmark) { SkFILEStream inputStream; inputStream.setPath(inputPath.c_str()); if (!inputStream.isValid()) { SkString err; err.printf("Could not open file %s\n", inputPath.c_str()); gLogger.logError(err); return; } SkPicture picture(&inputStream); SkString filename; sk_tools::get_basename(&filename, inputPath); SkString result; result.printf("running bench [%i %i] %s ", picture.width(), picture.height(), filename.c_str()); gLogger.logProgress(result); benchmark.run(&picture); } static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs, sk_tools::PictureBenchmark* benchmark) { const char* argv0 = argv[0]; char* const* stop = argv + argc; int repeats = DEFAULT_REPEATS; sk_tools::PictureRenderer::SkDeviceTypes deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType; sk_tools::PictureRenderer* renderer = NULL; // Create a string to show our current settings. // TODO: Make it prettier. Currently it just repeats the command line. SkString commandLine("bench_pictures:"); for (int i = 1; i < argc; i++) { commandLine.appendf(" %s", *(argv+i)); } commandLine.append("\n"); bool usePipe = false; bool multiThreaded = false; bool useTiles = false; const char* widthString = NULL; const char* heightString = NULL; bool isPowerOf2Mode = false; const char* mode = NULL; for (++argv; argv < stop; ++argv) { if (0 == strcmp(*argv, "--repeat")) { ++argv; if (argv < stop) { repeats = atoi(*argv); if (repeats < 1) { gLogger.logError("--repeat must be given a value > 0\n"); exit(-1); } } else { gLogger.logError("Missing arg for --repeat\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--pipe")) { usePipe = true; } else if (0 == strcmp(*argv, "--logFile")) { argv++; if (argv < stop) { if (!gLogger.SetLogFile(*argv)) { SkString str; str.printf("Could not open %s for writing.", *argv); gLogger.logError(str); usage(argv0); // TODO(borenet): We're disabling this for now, due to // write-protected Android devices. The very short-term // solution is to ignore the fact that we have no log file. //exit(-1); } } else { gLogger.logError("Missing arg for --logFile\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--mode")) { ++argv; if (argv >= stop) { gLogger.logError("Missing mode for --mode\n"); usage(argv0); exit(-1); } if (0 == strcmp(*argv, "record")) { renderer = SkNEW(sk_tools::RecordPictureRenderer); } else if (0 == strcmp(*argv, "simple")) { renderer = SkNEW(sk_tools::SimplePictureRenderer); } else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) { useTiles = true; mode = *argv; if (0 == strcmp(*argv, "pow2tile")) { isPowerOf2Mode = true; } ++argv; if (argv >= stop) { SkString err; err.printf("Missing width for --mode %s\n", mode); gLogger.logError(err); usage(argv0); exit(-1); } widthString = *argv; ++argv; if (argv >= stop) { gLogger.logError("Missing height for --mode tile\n"); usage(argv0); exit(-1); } heightString = *argv; ++argv; if (argv < stop && 0 == strcmp(*argv, "multi")) { multiThreaded = true; } else { --argv; } } else if (0 == strcmp(*argv, "playbackCreation")) { renderer = SkNEW(sk_tools::PlaybackCreationRenderer); } else { SkString err; err.printf("%s is not a valid mode for --mode\n", *argv); gLogger.logError(err); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--device")) { ++argv; if (argv >= stop) { gLogger.logError("Missing mode for --device\n"); usage(argv0); exit(-1); } if (0 == strcmp(*argv, "bitmap")) { deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType; } #if SK_SUPPORT_GPU else if (0 == strcmp(*argv, "gpu")) { deviceType = sk_tools::PictureRenderer::kGPU_DeviceType; } #endif else { SkString err; err.printf("%s is not a valid mode for --device\n", *argv); gLogger.logError(err); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--timers")) { ++argv; if (argv < stop) { bool timerWall = false; bool truncatedTimerWall = false; bool timerCpu = false; bool truncatedTimerCpu = false; bool timerGpu = false; for (char* t = *argv; *t; ++t) { switch (*t) { case 'w': timerWall = true; break; case 'c': timerCpu = true; break; case 'W': truncatedTimerWall = true; break; case 'C': truncatedTimerCpu = true; break; case 'g': timerGpu = true; break; default: { break; } } } benchmark->setTimersToShow(timerWall, truncatedTimerWall, timerCpu, truncatedTimerCpu, timerGpu); } else { gLogger.logError("Missing arg for --timers\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--min")) { benchmark->setPrintMin(true); } else if (0 == strcmp(*argv, "--logPerIter")) { ++argv; if (argv < stop) { bool log = atoi(*argv) != 0; benchmark->setLogPerIter(log); } else { gLogger.logError("Missing arg for --logPerIter\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) { usage(argv0); exit(0); } else { inputs->push_back(SkString(*argv)); } } if (useTiles) { SkASSERT(NULL == renderer); sk_tools::TiledPictureRenderer* tiledRenderer = SkNEW(sk_tools::TiledPictureRenderer); if (isPowerOf2Mode) { int minWidth = atoi(widthString); if (!SkIsPow2(minWidth) || minWidth < 0) { tiledRenderer->unref(); SkString err; err.printf("-mode %s must be given a width" " value that is a power of two\n", mode); gLogger.logError(err); exit(-1); } tiledRenderer->setTileMinPowerOf2Width(minWidth); } else if (sk_tools::is_percentage(widthString)) { tiledRenderer->setTileWidthPercentage(atof(widthString)); if (!(tiledRenderer->getTileWidthPercentage() > 0)) { tiledRenderer->unref(); gLogger.logError("--mode tile must be given a width percentage > 0\n"); exit(-1); } } else { tiledRenderer->setTileWidth(atoi(widthString)); if (!(tiledRenderer->getTileWidth() > 0)) { tiledRenderer->unref(); gLogger.logError("--mode tile must be given a width > 0\n"); exit(-1); } } if (sk_tools::is_percentage(heightString)) { tiledRenderer->setTileHeightPercentage(atof(heightString)); if (!(tiledRenderer->getTileHeightPercentage() > 0)) { tiledRenderer->unref(); gLogger.logError("--mode tile must be given a height percentage > 0\n"); exit(-1); } } else { tiledRenderer->setTileHeight(atoi(heightString)); if (!(tiledRenderer->getTileHeight() > 0)) { tiledRenderer->unref(); gLogger.logError("--mode tile must be given a height > 0\n"); exit(-1); } } tiledRenderer->setMultiThreaded(multiThreaded); tiledRenderer->setUsePipe(usePipe); renderer = tiledRenderer; } else if (usePipe) { renderer = SkNEW(sk_tools::PipePictureRenderer); } if (inputs->count() < 1) { SkDELETE(benchmark); usage(argv0); exit(-1); } if (NULL == renderer) { renderer = SkNEW(sk_tools::SimplePictureRenderer); } benchmark->setRenderer(renderer)->unref(); benchmark->setRepeats(repeats); benchmark->setDeviceType(deviceType); benchmark->setLogger(&gLogger); // Report current settings: gLogger.logProgress(commandLine); } static void process_input(const SkString& input, sk_tools::PictureBenchmark& benchmark) { SkOSFile::Iter iter(input.c_str(), "skp"); SkString inputFilename; if (iter.next(&inputFilename)) { do { SkString inputPath; sk_tools::make_filepath(&inputPath, input, inputFilename); run_single_benchmark(inputPath, benchmark); } while(iter.next(&inputFilename)); } else { run_single_benchmark(input, benchmark); } } int main(int argc, char* const argv[]) { #ifdef SK_ENABLE_INST_COUNT gPrintInstCount = true; #endif SkAutoGraphics ag; SkTArray<SkString> inputs; sk_tools::PictureBenchmark benchmark; parse_commandline(argc, argv, &inputs, &benchmark); for (int i = 0; i < inputs.count(); ++i) { process_input(inputs[i], benchmark); } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <getopt.h> #include <algorithm> #include <memory> #include <zcm/zcm-cpp.hpp> #include <zcm/zcm_coretypes.h> #include "zcm/json/json.h" #include "util/TranscoderPluginDb.hpp" using namespace std; struct Args { string inlog = ""; string outlog = ""; string plugin_path = ""; bool debug = false; bool parse(int argc, char *argv[]) { // set some defaults const char *optstring = "l:o:p:dh"; struct option long_opts[] = { { "log", required_argument, 0, 'l' }, { "output", required_argument, 0, 'o' }, { "plugin-path", required_argument, 0, 'p' }, { "debug", no_argument, 0, 'd' }, { "help", no_argument, 0, 'h' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0) { switch (c) { case 'l': inlog = string(optarg); break; case 'o': outlog = string(optarg); break; case 'p': plugin_path = string(optarg); break; case 'd': debug = true; break; case 'h': default: usage(); return false; }; } if (inlog == "") { cerr << "Please specify logfile input" << endl; return false; } if (outlog == "") { cerr << "Please specify log file output" << endl; return false; } const char* plugin_path_env = getenv("ZCM_LOG_TRANSCODER_PLUGINS_PATH"); if (plugin_path == "" && plugin_path_env) plugin_path = plugin_path_env; if (plugin_path == "") { cerr << "No plugin specified. Nothing to do" << endl; return false; } return true; } void usage() { cout << "usage: zcm-log-transcoder [options]" << endl << "" << endl << " Convert messages in one log file from one zcm type to another" << endl << "" << endl << "Example:" << endl << " zcm-log-transcoder -l zcm.log -o zcmout.log -p path/to/plugin.so" << endl << "" << endl << "Options:" << endl << "" << endl << " -h, --help Shows this help text and exits" << endl << " -l, --log=logfile Input log to convert" << endl << " -o, --output=logfile Output converted log file" << endl << " -p, --plugin-path=path Path to shared library containing transcoder plugins" << endl << " Can also be specified via the environment variable" << endl << " ZCM_LOG_TRANSCODER_PLUGINS_PATH" << endl << " -d, --debug Run a dry run to ensure proper transcoder setup" << endl << endl << endl; } }; int main(int argc, char* argv[]) { Args args; if (!args.parse(argc, argv)) return 1; zcm::LogFile inlog(args.inlog, "r"); if (!inlog.good()) { cerr << "Unable to open input zcm log: " << args.inlog << endl; return 1; } fseeko(inlog.getFilePtr(), 0, SEEK_END); off64_t logSize = ftello(inlog.getFilePtr()); fseeko(inlog.getFilePtr(), 0, SEEK_SET); zcm::LogFile outlog(args.outlog, "w"); if (!outlog.good()) { cerr << "Unable to open output zcm log: " << args.inlog << endl; return 1; } vector<zcm::TranscoderPlugin*> plugins; TranscoderPluginDb pluginDb(args.plugin_path, args.debug); vector<const zcm::TranscoderPlugin*> dbPlugins = pluginDb.getPlugins(); if (dbPlugins.empty()) { cerr << "Couldn't find any plugins. Aborting." << endl; return 1; } vector<string> dbPluginNames = pluginDb.getPluginNames(); for (size_t i = 0; i < dbPlugins.size(); ++i) { plugins.push_back((zcm::TranscoderPlugin*) dbPlugins[i]); if (args.debug) cout << "Loaded plugin: " << dbPluginNames[i] << endl; } if (args.debug) return 0; size_t numInEvents = 0, numOutEvents = 0; const zcm::LogEvent* evt; off64_t offset; while (1) { offset = ftello(inlog.getFilePtr()); static int lastPrintPercent = 0; int percent = (100.0 * offset / (logSize == 0 ? 1 : logSize)) * 100; if (percent != lastPrintPercent) { cout << "\r" << "Percent Complete: " << (percent / 100) << flush; lastPrintPercent = percent; } evt = inlog.readNextEvent(); if (evt == nullptr) break; vector<const zcm::LogEvent*> evts; if (!plugins.empty()) { int64_t msg_hash; __int64_t_decode_array(evt->data, 0, 8, &msg_hash, 1); for (auto& p : plugins) { vector<const zcm::LogEvent*> pevts = p->transcodeEvent((uint64_t) msg_hash, evt); evts.insert(evts.end(), pevts.begin(), pevts.end()); } } if (evts.empty()) evts.push_back(evt); for (auto* evt : evts) { if (!evt) continue; outlog.writeEvent(evt); numOutEvents++; } numInEvents++; } cout << endl; inlog.close(); outlog.close(); cout << "Transcoded " << numInEvents << " events into " << numOutEvents << " events" << endl; return 0; } <commit_msg>Fixed printout for transcoder<commit_after>#include <iostream> #include <fstream> #include <getopt.h> #include <algorithm> #include <memory> #include <zcm/zcm-cpp.hpp> #include <zcm/zcm_coretypes.h> #include "zcm/json/json.h" #include "util/TranscoderPluginDb.hpp" using namespace std; struct Args { string inlog = ""; string outlog = ""; string plugin_path = ""; bool debug = false; bool parse(int argc, char *argv[]) { // set some defaults const char *optstring = "l:o:p:dh"; struct option long_opts[] = { { "log", required_argument, 0, 'l' }, { "output", required_argument, 0, 'o' }, { "plugin-path", required_argument, 0, 'p' }, { "debug", no_argument, 0, 'd' }, { "help", no_argument, 0, 'h' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0) { switch (c) { case 'l': inlog = string(optarg); break; case 'o': outlog = string(optarg); break; case 'p': plugin_path = string(optarg); break; case 'd': debug = true; break; case 'h': default: usage(); return false; }; } if (inlog == "") { cerr << "Please specify logfile input" << endl; return false; } if (outlog == "") { cerr << "Please specify log file output" << endl; return false; } const char* plugin_path_env = getenv("ZCM_LOG_TRANSCODER_PLUGINS_PATH"); if (plugin_path == "" && plugin_path_env) plugin_path = plugin_path_env; if (plugin_path == "") { cerr << "No plugin specified. Nothing to do" << endl; return false; } return true; } void usage() { cout << "usage: zcm-log-transcoder [options]" << endl << "" << endl << " Convert messages in one log file from one zcm type to another" << endl << "" << endl << "Example:" << endl << " zcm-log-transcoder -l zcm.log -o zcmout.log -p path/to/plugin.so" << endl << "" << endl << "Options:" << endl << "" << endl << " -h, --help Shows this help text and exits" << endl << " -l, --log=logfile Input log to convert" << endl << " -o, --output=logfile Output converted log file" << endl << " -p, --plugin-path=path Path to shared library containing transcoder plugins" << endl << " Can also be specified via the environment variable" << endl << " ZCM_LOG_TRANSCODER_PLUGINS_PATH" << endl << " -d, --debug Run a dry run to ensure proper transcoder setup" << endl << endl << endl; } }; int main(int argc, char* argv[]) { Args args; if (!args.parse(argc, argv)) return 1; zcm::LogFile inlog(args.inlog, "r"); if (!inlog.good()) { cerr << "Unable to open input zcm log: " << args.inlog << endl; return 1; } fseeko(inlog.getFilePtr(), 0, SEEK_END); off64_t logSize = ftello(inlog.getFilePtr()); fseeko(inlog.getFilePtr(), 0, SEEK_SET); zcm::LogFile outlog(args.outlog, "w"); if (!outlog.good()) { cerr << "Unable to open output zcm log: " << args.outlog << endl; return 1; } vector<zcm::TranscoderPlugin*> plugins; TranscoderPluginDb pluginDb(args.plugin_path, args.debug); vector<const zcm::TranscoderPlugin*> dbPlugins = pluginDb.getPlugins(); if (dbPlugins.empty()) { cerr << "Couldn't find any plugins. Aborting." << endl; return 1; } vector<string> dbPluginNames = pluginDb.getPluginNames(); for (size_t i = 0; i < dbPlugins.size(); ++i) { plugins.push_back((zcm::TranscoderPlugin*) dbPlugins[i]); if (args.debug) cout << "Loaded plugin: " << dbPluginNames[i] << endl; } if (args.debug) return 0; size_t numInEvents = 0, numOutEvents = 0; const zcm::LogEvent* evt; off64_t offset; while (1) { offset = ftello(inlog.getFilePtr()); static int lastPrintPercent = 0; int percent = (100.0 * offset / (logSize == 0 ? 1 : logSize)) * 100; if (percent != lastPrintPercent) { cout << "\r" << "Percent Complete: " << (percent / 100) << flush; lastPrintPercent = percent; } evt = inlog.readNextEvent(); if (evt == nullptr) break; vector<const zcm::LogEvent*> evts; if (!plugins.empty()) { int64_t msg_hash; __int64_t_decode_array(evt->data, 0, 8, &msg_hash, 1); for (auto& p : plugins) { vector<const zcm::LogEvent*> pevts = p->transcodeEvent((uint64_t) msg_hash, evt); evts.insert(evts.end(), pevts.begin(), pevts.end()); } } if (evts.empty()) evts.push_back(evt); for (auto* evt : evts) { if (!evt) continue; outlog.writeEvent(evt); numOutEvents++; } numInEvents++; } cout << endl; inlog.close(); outlog.close(); cout << "Transcoded " << numInEvents << " events into " << numOutEvents << " events" << endl; return 0; } <|endoftext|>
<commit_before>#include <windows.h> #include <vector> #include "ddraw7proxy.hpp" #include "detours.h" /*static*/ DirectSurface7Proxy* DirectSurface7Proxy::g_Primary; /*static*/ DirectSurface7Proxy* DirectSurface7Proxy::g_BackBuffer; /*static*/ DirectSurface7Proxy* DirectSurface7Proxy::g_FakePrimary; HINSTANCE gDllInstance = NULL; HRESULT WINAPI NewDirectDrawCreate(GUID* lpGUID, IDirectDraw** lplpDD, IUnknown* pUnkOuter); using TDirectDrawCreate = decltype(&NewDirectDrawCreate); inline void FatalExit(const char* msg) { ::MessageBox(NULL, msg, "Error", MB_OK | MB_ICONEXCLAMATION); exit(-1); } static HMODULE LoadRealDDrawDll() { char infoBuf[MAX_PATH] = {}; ::GetSystemDirectory(infoBuf, MAX_PATH); strcat_s(infoBuf, "\\ddraw.dll"); const HMODULE hRealDll = ::LoadLibrary(infoBuf); if (!hRealDll) { FatalExit("Can't load or find real DDraw.dll"); } return hRealDll; } template<class T> inline T TGetProcAddress(HMODULE hDll, const char* func) { #pragma warning(suppress: 4191) return reinterpret_cast<T>(::GetProcAddress(hDll, func)); } static TDirectDrawCreate GetFunctionPointersToRealDDrawFunctions(HMODULE hRealDll) { auto ptr = TGetProcAddress<TDirectDrawCreate>(hRealDll, "DirectDrawCreate"); if (!ptr) { FatalExit("Can't find DirectDrawCreate function in real dll"); } return ptr; } // ================= WNDPROC g_pOldProc = 0; static LRESULT CALLBACK NewWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: break; case WM_ERASEBKGND: { RECT rcWin; HDC hDC = GetDC(hwnd); GetClipBox((HDC)wParam, &rcWin); FillRect(hDC, &rcWin, GetSysColorBrush(COLOR_DESKTOP)); // hBrush can be obtained by calling GetWindowLong() } return TRUE; case WM_GETICON: case WM_MOUSEACTIVATE: case WM_NCLBUTTONDOWN: case WM_NCMOUSELEAVE: case WM_KILLFOCUS: case WM_SETFOCUS: case WM_ACTIVATEAPP: case WM_NCHITTEST: case WM_ACTIVATE: case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: case WM_NCCALCSIZE: case WM_MOVE: case WM_WINDOWPOSCHANGED: case WM_WINDOWPOSCHANGING: case WM_NCMOUSEMOVE: case WM_MOUSEMOVE: return DefWindowProc(hwnd, message, wParam, lParam); case WM_SETCURSOR: { // Set the cursor so the resize cursor or whatever doesn't "stick" // when we move the mouse over the game window. static HCURSOR cur = LoadCursor(0, IDC_ARROW); if (cur) { SetCursor(cur); } return DefWindowProc(hwnd, message, wParam, lParam); } case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(hwnd, &ps); EndPaint(hwnd, &ps); } return FALSE; } return g_pOldProc(hwnd, message, wParam, lParam); } static void CenterWnd(HWND wnd) { RECT r, r1; GetWindowRect(wnd, &r); GetWindowRect(GetDesktopWindow(), &r1); MoveWindow(wnd, ((r1.right - r1.left) - (r.right - r.left)) / 2, ((r1.bottom - r1.top) - (r.bottom - r.top)) / 2, (r.right - r.left), (r.bottom - r.top), 0); } static void SubClassWindow() { HWND wnd = FindWindow("ABE_WINCLASS", NULL); g_pOldProc = (WNDPROC)SetWindowLong(wnd, GWL_WNDPROC, (LONG)NewWindowProc); for (int i = 0; i < 70; ++i) { ShowCursor(TRUE); } RECT rc; SetRect(&rc, 0, 0, 640, 480); AdjustWindowRectEx(&rc, WS_OVERLAPPEDWINDOW | WS_VISIBLE, TRUE, 0); SetWindowPos(wnd, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top, SWP_SHOWWINDOW); ShowWindow(wnd, SW_HIDE); CenterWnd(wnd); ShowWindow(wnd, SW_SHOW); InvalidateRect(GetDesktopWindow(), NULL, TRUE); } static void PatchWindowTitle() { HWND wnd = FindWindow("ABE_WINCLASS", NULL); if (wnd) { const int length = GetWindowTextLength(wnd) + 1; std::vector< char > titleBuffer(length+1); if (GetWindowText(wnd, titleBuffer.data(), length)) { std::string titleStr(titleBuffer.data()); titleStr += " under ALIVE hook"; SetWindowText(wnd, titleStr.c_str()); } } } template<class FunctionType, class RealFunctionType = FunctionType> class Hook { public: Hook(const Hook&) = delete; Hook& operator = (const Hook&) = delete; explicit Hook(FunctionType oldFunc) : mOldPtr(oldFunc) { } explicit Hook(DWORD oldFunc) : mOldPtr(reinterpret_cast<FunctionType>(oldFunc)) { } void Install(FunctionType newFunc) { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)mOldPtr, newFunc); if (DetourTransactionCommit() != NO_ERROR) { FatalExit("detouring failed"); } } RealFunctionType Real() const { #pragma warning(suppress: 4191) return reinterpret_cast<RealFunctionType>(mOldPtr); } private: FunctionType mOldPtr; }; static int __fastcall set_first_camera_hook(void *thisPtr, void*, __int16 a2, __int16 a3, __int16 a4, __int16 a5, __int16 a6, __int16 a7); typedef int(__thiscall* set_first_camera_thiscall)(void *thisPtr, __int16 a2, __int16 a3, __int16 a4, __int16 a5, __int16 a6, __int16 a7); namespace Hooks { Hook<decltype(&::SetWindowLongA)> SetWindowLong(::SetWindowLongA); Hook<decltype(&::set_first_camera_hook), set_first_camera_thiscall> set_first_camera(0x00401415); } LONG WINAPI Hook_SetWindowLongA(HWND hWnd, int nIndex, LONG dwNewLong) { if (nIndex == GWL_STYLE) { dwNewLong = WS_OVERLAPPEDWINDOW | WS_VISIBLE; } return Hooks::SetWindowLong.Real()(hWnd, nIndex, dwNewLong); } static int __fastcall set_first_camera_hook(void *thisPtr, void* , __int16 levelNumber, __int16 pathNumber, __int16 cameraNumber, __int16 screenChangeEffect, __int16 a6, __int16 a7) { // AE Cheat screen, I think we have to fake cheat input or set a bool for this to work :( // cameraNumber = 31; // Setting to Feco lets us go directly in game, with the side effect that pausing will crash // and some other nasties, still its good enough for debugging animations levelNumber = 5; // Abe "hello" screen when levelNumber is left as the intro level cameraNumber = 1; // pathNumber = 4; // 5 = "flash" on // 4 = top to bottom // 8 = door effect/sound screenChangeEffect = 5; return Hooks::set_first_camera.Real()(thisPtr, levelNumber, pathNumber, cameraNumber, screenChangeEffect, a6, a7); } void HookMain() { Hooks::SetWindowLong.Install(Hook_SetWindowLongA); Hooks::set_first_camera.Install(set_first_camera_hook); SubClassWindow(); PatchWindowTitle(); } // Proxy DLL entry point HRESULT WINAPI NewDirectDrawCreate(GUID* lpGUID, IDirectDraw** lplpDD, IUnknown* pUnkOuter) { const HMODULE hDDrawDll = LoadRealDDrawDll(); const TDirectDrawCreate pRealDirectDrawCreate = GetFunctionPointersToRealDDrawFunctions(hDDrawDll); const HRESULT ret = pRealDirectDrawCreate(lpGUID, lplpDD, pUnkOuter); if (SUCCEEDED(ret)) { *lplpDD = new DirectDraw7Proxy(*lplpDD); HookMain(); } return ret; } extern "C" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID /*lpReserved*/) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { gDllInstance = hModule; } return TRUE; } <commit_msg>add hook for anim_decode, serves as a base for extracting the anim id/frame/index that is being rendered<commit_after>#include <windows.h> #include <vector> #include "ddraw7proxy.hpp" #include "detours.h" #include "logger.hpp" /*static*/ DirectSurface7Proxy* DirectSurface7Proxy::g_Primary; /*static*/ DirectSurface7Proxy* DirectSurface7Proxy::g_BackBuffer; /*static*/ DirectSurface7Proxy* DirectSurface7Proxy::g_FakePrimary; HINSTANCE gDllInstance = NULL; HRESULT WINAPI NewDirectDrawCreate(GUID* lpGUID, IDirectDraw** lplpDD, IUnknown* pUnkOuter); using TDirectDrawCreate = decltype(&NewDirectDrawCreate); inline void FatalExit(const char* msg) { ::MessageBox(NULL, msg, "Error", MB_OK | MB_ICONEXCLAMATION); exit(-1); } static HMODULE LoadRealDDrawDll() { char infoBuf[MAX_PATH] = {}; ::GetSystemDirectory(infoBuf, MAX_PATH); strcat_s(infoBuf, "\\ddraw.dll"); const HMODULE hRealDll = ::LoadLibrary(infoBuf); if (!hRealDll) { FatalExit("Can't load or find real DDraw.dll"); } return hRealDll; } template<class T> inline T TGetProcAddress(HMODULE hDll, const char* func) { #pragma warning(suppress: 4191) return reinterpret_cast<T>(::GetProcAddress(hDll, func)); } static TDirectDrawCreate GetFunctionPointersToRealDDrawFunctions(HMODULE hRealDll) { auto ptr = TGetProcAddress<TDirectDrawCreate>(hRealDll, "DirectDrawCreate"); if (!ptr) { FatalExit("Can't find DirectDrawCreate function in real dll"); } return ptr; } // ================= WNDPROC g_pOldProc = 0; static LRESULT CALLBACK NewWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: break; case WM_ERASEBKGND: { RECT rcWin; HDC hDC = GetDC(hwnd); GetClipBox((HDC)wParam, &rcWin); FillRect(hDC, &rcWin, GetSysColorBrush(COLOR_DESKTOP)); // hBrush can be obtained by calling GetWindowLong() } return TRUE; case WM_GETICON: case WM_MOUSEACTIVATE: case WM_NCLBUTTONDOWN: case WM_NCMOUSELEAVE: case WM_KILLFOCUS: case WM_SETFOCUS: case WM_ACTIVATEAPP: case WM_NCHITTEST: case WM_ACTIVATE: case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: case WM_NCCALCSIZE: case WM_MOVE: case WM_WINDOWPOSCHANGED: case WM_WINDOWPOSCHANGING: case WM_NCMOUSEMOVE: case WM_MOUSEMOVE: return DefWindowProc(hwnd, message, wParam, lParam); case WM_SETCURSOR: { // Set the cursor so the resize cursor or whatever doesn't "stick" // when we move the mouse over the game window. static HCURSOR cur = LoadCursor(0, IDC_ARROW); if (cur) { SetCursor(cur); } return DefWindowProc(hwnd, message, wParam, lParam); } case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(hwnd, &ps); EndPaint(hwnd, &ps); } return FALSE; } return g_pOldProc(hwnd, message, wParam, lParam); } static void CenterWnd(HWND wnd) { RECT r, r1; GetWindowRect(wnd, &r); GetWindowRect(GetDesktopWindow(), &r1); MoveWindow(wnd, ((r1.right - r1.left) - (r.right - r.left)) / 2, ((r1.bottom - r1.top) - (r.bottom - r.top)) / 2, (r.right - r.left), (r.bottom - r.top), 0); } static void SubClassWindow() { HWND wnd = FindWindow("ABE_WINCLASS", NULL); g_pOldProc = (WNDPROC)SetWindowLong(wnd, GWL_WNDPROC, (LONG)NewWindowProc); for (int i = 0; i < 70; ++i) { ShowCursor(TRUE); } RECT rc; SetRect(&rc, 0, 0, 640, 480); AdjustWindowRectEx(&rc, WS_OVERLAPPEDWINDOW | WS_VISIBLE, TRUE, 0); SetWindowPos(wnd, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top, SWP_SHOWWINDOW); ShowWindow(wnd, SW_HIDE); CenterWnd(wnd); ShowWindow(wnd, SW_SHOW); InvalidateRect(GetDesktopWindow(), NULL, TRUE); } static void PatchWindowTitle() { HWND wnd = FindWindow("ABE_WINCLASS", NULL); if (wnd) { const int length = GetWindowTextLength(wnd) + 1; std::vector< char > titleBuffer(length+1); if (GetWindowText(wnd, titleBuffer.data(), length)) { std::string titleStr(titleBuffer.data()); titleStr += " under ALIVE hook"; SetWindowText(wnd, titleStr.c_str()); } } } template<class FunctionType, class RealFunctionType = FunctionType> class Hook { public: Hook(const Hook&) = delete; Hook& operator = (const Hook&) = delete; explicit Hook(FunctionType oldFunc) : mOldPtr(oldFunc) { } explicit Hook(DWORD oldFunc) : mOldPtr(reinterpret_cast<FunctionType>(oldFunc)) { } void Install(FunctionType newFunc) { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)mOldPtr, newFunc); if (DetourTransactionCommit() != NO_ERROR) { FatalExit("detouring failed"); } } RealFunctionType Real() const { #pragma warning(suppress: 4191) return reinterpret_cast<RealFunctionType>(mOldPtr); } private: FunctionType mOldPtr; }; static int __fastcall set_first_camera_hook(void *thisPtr, void*, __int16 a2, __int16 a3, __int16 a4, __int16 a5, __int16 a6, __int16 a7); typedef int(__thiscall* set_first_camera_thiscall)(void *thisPtr, __int16 a2, __int16 a3, __int16 a4, __int16 a5, __int16 a6, __int16 a7); struct anim_struct { void* mVtbl; BYTE field_4; // max w? BYTE field_5; // max h? WORD flags; DWORD field_8; WORD field_C; WORD field_E; DWORD field_10; DWORD field_14; DWORD mFrameTableOffset; // offset to frame table from anim data header DWORD field_1C; void** field_20; // pointer to a pointer which points to anim data? DWORD iDbufPtr; DWORD iAnimSize; DWORD field_2C; DWORD field_30; DWORD field_34; DWORD field_38; DWORD field_3C; DWORD field_40; DWORD field_44; DWORD field_48; DWORD field_4C; DWORD field_50; DWORD field_54; DWORD field_58; DWORD field_5C; DWORD field_60; DWORD field_64; DWORD field_68; DWORD field_6C; DWORD field_70; DWORD field_74; DWORD field_78; DWORD field_7C; DWORD field_80; WORD iRect; WORD field_86; WORD field_88; WORD field_8A; DWORD field_8C; WORD field_90; WORD field_92; }; void __fastcall anim_decode_hook(anim_struct* thisPtr, void*); typedef void (__thiscall* anim_decode_thiscall)(anim_struct* thisPtr); namespace Hooks { Hook<decltype(&::SetWindowLongA)> SetWindowLong(::SetWindowLongA); Hook<decltype(&::set_first_camera_hook), set_first_camera_thiscall> set_first_camera(0x00401415); Hook<decltype(&::anim_decode_hook), anim_decode_thiscall> anim_decode(0x0040AC90); } LONG WINAPI Hook_SetWindowLongA(HWND hWnd, int nIndex, LONG dwNewLong) { if (nIndex == GWL_STYLE) { dwNewLong = WS_OVERLAPPEDWINDOW | WS_VISIBLE; } return Hooks::SetWindowLong.Real()(hWnd, nIndex, dwNewLong); } static int __fastcall set_first_camera_hook(void *thisPtr, void* , __int16 levelNumber, __int16 pathNumber, __int16 cameraNumber, __int16 screenChangeEffect, __int16 a6, __int16 a7) { // AE Cheat screen, I think we have to fake cheat input or set a bool for this to work :( // cameraNumber = 31; // Setting to Feco lets us go directly in game, with the side effect that pausing will crash // and some other nasties, still its good enough for debugging animations levelNumber = 5; // Abe "hello" screen when levelNumber is left as the intro level cameraNumber = 1; // pathNumber = 4; // 5 = "flash" on // 4 = top to bottom // 8 = door effect/sound screenChangeEffect = 5; return Hooks::set_first_camera.Real()(thisPtr, levelNumber, pathNumber, cameraNumber, screenChangeEffect, a6, a7); } void __fastcall anim_decode_hook(anim_struct* thisPtr, void*) { // TODO Hook int __fastcall get_anim_frame_q(int a1, int a2, __int16 a3) @ 0x004042CD // seems its return value can be used to get the anim data frame pointer OutputDebugString("anim_decode\n"); Hooks::anim_decode.Real()(thisPtr); } void HookMain() { Hooks::SetWindowLong.Install(Hook_SetWindowLongA); Hooks::set_first_camera.Install(set_first_camera_hook); Hooks::anim_decode.Install(anim_decode_hook); SubClassWindow(); PatchWindowTitle(); } // Proxy DLL entry point HRESULT WINAPI NewDirectDrawCreate(GUID* lpGUID, IDirectDraw** lplpDD, IUnknown* pUnkOuter) { const HMODULE hDDrawDll = LoadRealDDrawDll(); const TDirectDrawCreate pRealDirectDrawCreate = GetFunctionPointersToRealDDrawFunctions(hDDrawDll); const HRESULT ret = pRealDirectDrawCreate(lpGUID, lplpDD, pUnkOuter); if (SUCCEEDED(ret)) { *lplpDD = new DirectDraw7Proxy(*lplpDD); HookMain(); } return ret; } extern "C" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID /*lpReserved*/) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { gDllInstance = hModule; } return TRUE; } <|endoftext|>
<commit_before>#include "ProxyHttpClient.hpp" #include "api/Error.hpp" #include "api/HttpMethod.hpp" #include "api/HttpRequest.hpp" #include <api/HttpReadBodyResult.hpp> #include <experimental/filesystem> #include <algorithm> #include <fstream> #include <functional> #include <memory> #include <mutex> #include <gtest/gtest.h> #define HTTP_CACHE_DIR "http_cache" #if defined(UPDATE_HTTP_CACHE) && defined(ALLOW_HTTP_ACCESS) && !defined(LOAD_HTTP_CACHE) #pragma message "ProxyHttpClient is configured to update HTTP cache" #elif !UPDATE_HTTP_CACHE && ALLOW_HTTP_ACCESS && !LOAD_HTTP_CACHE #pragma message "ProxyHttpClient is configured to run tests agains real web services" #elif !UPDATE_HTTP_CACHE && !ALLOW_HTTP_ACCESS && LOAD_HTTP_CACHE #pragma message "ProxyHttpClient is configured to use HTTP cache instead of real web services" #else #error "Incorrect configuration of HTTP caching" #endif namespace fs = std::experimental::filesystem; namespace ledger { namespace core { namespace test { namespace impl { class TrafficLogger { public: TrafficLogger() : _cache_fn(getCacheFileName()) { } ~TrafficLogger() { save(); } void add(const std::string& type, const std::string& url, const std::string& request_body, const std::string& response_body) { std::ostringstream oss; oss << type << " " << url << std::endl; oss << encodeBody(request_body); std::lock_guard<std::mutex> guard(_mutex); _data[oss.str()] = encodeBody(response_body); } static std::string getCacheFileName() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); const std::string cache_fn = std::string(HTTP_CACHE_DIR) + std::string("/") + std::string(test_info->test_suite_name()) + std::string(".") + std::string(test_info->name()); return cache_fn; } protected: typedef std::unordered_map<std::string, std::string> map_type_t; std::string encodeBody(const std::string& body) { std::ostringstream oss; if (body.size() == 0) { oss << 0 << std::endl; } else { oss << std::count(body.begin(), body.end(), '\n') + 1 << std::endl; oss << body << std::endl; } return oss.str(); } void save() { std::lock_guard<std::mutex> guard(_mutex); if (_data.empty()) return; if (!fs::exists(HTTP_CACHE_DIR)) fs::create_directory(HTTP_CACHE_DIR); std::ofstream out(_cache_fn); for (const auto& kv : _data) out << kv.first << kv.second << std::endl; } std::mutex _mutex; map_type_t _data; std::string _cache_fn; }; class LoggingHttpRequest : public api::HttpRequest { public: typedef std::function<void(const std::string& type, const std::string& url, const std::vector<uint8_t>& req_body, const std::string& resp_body)> callback_t; LoggingHttpRequest(const std::shared_ptr<api::HttpRequest>& request, callback_t fn) : _request(request), _callback(fn) {} virtual ~LoggingHttpRequest() {} virtual api::HttpMethod getMethod() { return _request->getMethod(); } virtual std::unordered_map<std::string, std::string> getHeaders() { return _request->getHeaders(); } virtual std::vector<uint8_t> getBody() { return _request->getBody(); } virtual std::string getUrl() { return _request->getUrl(); } virtual void complete(const std::shared_ptr<api::HttpUrlConnection> & response, const std::experimental::optional<api::Error> & error) { const std::string response_body = readResponseBody(response); _callback(to_string(getMethod()), getUrl(), getBody(), response_body); _request->complete(FakeUrlConnection::fromString(response_body), error); } protected: static std::string readResponseBody(const std::shared_ptr<api::HttpUrlConnection> & response) { std::string response_body; while (true) { api::HttpReadBodyResult body = response->readBody(); if (body.error) throw std::runtime_error(body.error->message); if (body.data) { const std::vector<uint8_t>& data = *(body.data); if (data.empty()) break; response_body += std::string(data.begin(), data.end()); continue; } break; } return response_body; } const std::shared_ptr<api::HttpRequest> _request; callback_t _callback; }; } ProxyHttpClient::ProxyHttpClient(std::shared_ptr<api::HttpClient> httpClient) : _httpClient(httpClient) { #ifdef UPDATE_HTTP_CACHE _logger = make_shared<impl::TrafficLogger>(); #endif #ifdef LOAD_HTTP_CACHE if (!_logger) loadCache(impl::TrafficLogger::getCacheFileName()); #endif } void ProxyHttpClient::execute(const std::shared_ptr<api::HttpRequest>& request) { auto vector_uint8_to_string = [](const std::vector<uint8_t>& v) { return std::string(v.begin(), v.end()); }; auto it = _cache.find(request->getUrl() + vector_uint8_to_string(request->getBody())); if (it != _cache.end() && !_logger) { std::cout << "get response from cache : " << request->getUrl() << std::endl; request->complete(it->second, std::experimental::nullopt); return; } #ifndef ALLOW_HTTP_ACCESS throw std::runtime_error("HTTP access isn't allowed."); #endif if (_logger) { std::shared_ptr<impl::LoggingHttpRequest> temp = std::make_shared<impl::LoggingHttpRequest>(request, [this, vector_uint8_to_string](const std::string& type, const std::string& url, const std::vector<uint8_t>& req_body, const std::string& resp_body){ _logger->add(type, url, vector_uint8_to_string(req_body), resp_body); }); #ifdef ALLOW_HTTP_ACCESS _httpClient->execute(temp); #endif } else { #ifdef ALLOW_HTTP_ACCESS _httpClient->execute(request); #endif } } void ProxyHttpClient::loadCache(const std::string& file_name) { // Cache file format: // (GET|POST) URL // request length in lines // request body // response length in lines // response body // empty line auto read_body = [](std::ifstream& file) { std::string s, line; size_t n = 0; file >> n; while (n > 0 && std::getline(file, line)) { if (s.empty() && line.empty()) continue; if (!s.empty()) s += "\n"; s += line; n--; } return s; }; std::ifstream input_file(file_name); if (input_file.is_open()) { std::string line; std::string type, url; while (input_file >> type >> url) { const std::string request_body = read_body(input_file); const std::string response_body = read_body(input_file); url += request_body; addCache(url, response_body); } } } void ProxyHttpClient::addCache(const std::string& url, const std::string& body) { _cache.emplace(url, FakeUrlConnection::fromString(body)); } } } } <commit_msg>Add missing std:: namespace<commit_after>#include "ProxyHttpClient.hpp" #include "api/Error.hpp" #include "api/HttpMethod.hpp" #include "api/HttpRequest.hpp" #include <api/HttpReadBodyResult.hpp> #include <experimental/filesystem> #include <algorithm> #include <fstream> #include <functional> #include <memory> #include <mutex> #include <gtest/gtest.h> #define HTTP_CACHE_DIR "http_cache" #if defined(UPDATE_HTTP_CACHE) && defined(ALLOW_HTTP_ACCESS) && !defined(LOAD_HTTP_CACHE) #pragma message "ProxyHttpClient is configured to update HTTP cache" #elif !UPDATE_HTTP_CACHE && ALLOW_HTTP_ACCESS && !LOAD_HTTP_CACHE #pragma message "ProxyHttpClient is configured to run tests agains real web services" #elif !UPDATE_HTTP_CACHE && !ALLOW_HTTP_ACCESS && LOAD_HTTP_CACHE #pragma message "ProxyHttpClient is configured to use HTTP cache instead of real web services" #else #error "Incorrect configuration of HTTP caching" #endif namespace fs = std::experimental::filesystem; namespace ledger { namespace core { namespace test { namespace impl { class TrafficLogger { public: TrafficLogger() : _cache_fn(getCacheFileName()) { } ~TrafficLogger() { save(); } void add(const std::string& type, const std::string& url, const std::string& request_body, const std::string& response_body) { std::ostringstream oss; oss << type << " " << url << std::endl; oss << encodeBody(request_body); std::lock_guard<std::mutex> guard(_mutex); _data[oss.str()] = encodeBody(response_body); } static std::string getCacheFileName() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); const std::string cache_fn = std::string(HTTP_CACHE_DIR) + std::string("/") + std::string(test_info->test_suite_name()) + std::string(".") + std::string(test_info->name()); return cache_fn; } protected: typedef std::unordered_map<std::string, std::string> map_type_t; std::string encodeBody(const std::string& body) { std::ostringstream oss; if (body.size() == 0) { oss << 0 << std::endl; } else { oss << std::count(body.begin(), body.end(), '\n') + 1 << std::endl; oss << body << std::endl; } return oss.str(); } void save() { std::lock_guard<std::mutex> guard(_mutex); if (_data.empty()) return; if (!fs::exists(HTTP_CACHE_DIR)) fs::create_directory(HTTP_CACHE_DIR); std::ofstream out(_cache_fn); for (const auto& kv : _data) out << kv.first << kv.second << std::endl; } std::mutex _mutex; map_type_t _data; std::string _cache_fn; }; class LoggingHttpRequest : public api::HttpRequest { public: typedef std::function<void(const std::string& type, const std::string& url, const std::vector<uint8_t>& req_body, const std::string& resp_body)> callback_t; LoggingHttpRequest(const std::shared_ptr<api::HttpRequest>& request, callback_t fn) : _request(request), _callback(fn) {} virtual ~LoggingHttpRequest() {} virtual api::HttpMethod getMethod() { return _request->getMethod(); } virtual std::unordered_map<std::string, std::string> getHeaders() { return _request->getHeaders(); } virtual std::vector<uint8_t> getBody() { return _request->getBody(); } virtual std::string getUrl() { return _request->getUrl(); } virtual void complete(const std::shared_ptr<api::HttpUrlConnection> & response, const std::experimental::optional<api::Error> & error) { const std::string response_body = readResponseBody(response); _callback(to_string(getMethod()), getUrl(), getBody(), response_body); _request->complete(FakeUrlConnection::fromString(response_body), error); } protected: static std::string readResponseBody(const std::shared_ptr<api::HttpUrlConnection> & response) { std::string response_body; while (true) { api::HttpReadBodyResult body = response->readBody(); if (body.error) throw std::runtime_error(body.error->message); if (body.data) { const std::vector<uint8_t>& data = *(body.data); if (data.empty()) break; response_body += std::string(data.begin(), data.end()); continue; } break; } return response_body; } const std::shared_ptr<api::HttpRequest> _request; callback_t _callback; }; } ProxyHttpClient::ProxyHttpClient(std::shared_ptr<api::HttpClient> httpClient) : _httpClient(httpClient) { #ifdef UPDATE_HTTP_CACHE _logger = std::make_shared<impl::TrafficLogger>(); #endif #ifdef LOAD_HTTP_CACHE if (!_logger) loadCache(impl::TrafficLogger::getCacheFileName()); #endif } void ProxyHttpClient::execute(const std::shared_ptr<api::HttpRequest>& request) { auto vector_uint8_to_string = [](const std::vector<uint8_t>& v) { return std::string(v.begin(), v.end()); }; auto it = _cache.find(request->getUrl() + vector_uint8_to_string(request->getBody())); if (it != _cache.end() && !_logger) { std::cout << "get response from cache : " << request->getUrl() << std::endl; request->complete(it->second, std::experimental::nullopt); return; } #ifndef ALLOW_HTTP_ACCESS throw std::runtime_error("HTTP access isn't allowed."); #endif if (_logger) { std::shared_ptr<impl::LoggingHttpRequest> temp = std::make_shared<impl::LoggingHttpRequest>(request, [this, vector_uint8_to_string](const std::string& type, const std::string& url, const std::vector<uint8_t>& req_body, const std::string& resp_body){ _logger->add(type, url, vector_uint8_to_string(req_body), resp_body); }); #ifdef ALLOW_HTTP_ACCESS _httpClient->execute(temp); #endif } else { #ifdef ALLOW_HTTP_ACCESS _httpClient->execute(request); #endif } } void ProxyHttpClient::loadCache(const std::string& file_name) { // Cache file format: // (GET|POST) URL // request length in lines // request body // response length in lines // response body // empty line auto read_body = [](std::ifstream& file) { std::string s, line; size_t n = 0; file >> n; while (n > 0 && std::getline(file, line)) { if (s.empty() && line.empty()) continue; if (!s.empty()) s += "\n"; s += line; n--; } return s; }; std::ifstream input_file(file_name); if (input_file.is_open()) { std::string line; std::string type, url; while (input_file >> type >> url) { const std::string request_body = read_body(input_file); const std::string response_body = read_body(input_file); url += request_body; addCache(url, response_body); } } } void ProxyHttpClient::addCache(const std::string& url, const std::string& body) { _cache.emplace(url, FakeUrlConnection::fromString(body)); } } } } <|endoftext|>
<commit_before>// ======================================================================== // // 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 "ospray/ospray_util.h" extern "C" { // OSPData helpers //////////////////////////////////////////////////////////// OSPData ospNewSharedData1D(const void *sharedData, OSPDataType type, uint32_t numItems) { return ospNewSharedData(sharedData, type, numItems, 0, 1, 0, 1, 0); } OSPData ospNewSharedData1DStride(const void *sharedData, OSPDataType type, uint32_t numItems, int64_t byteStride) { return ospNewSharedData(sharedData, type, numItems, byteStride, 1, 0, 1, 0); } OSPData ospNewSharedData2D(const void *sharedData, OSPDataType type, uint32_t numItems1, uint32_t numItems2) { return ospNewSharedData(sharedData, type, numItems1, 0, numItems2, 0, 1, 0); } OSPData ospNewSharedData2DStride(const void *sharedData, OSPDataType type, uint32_t numItems1, int64_t byteStride1, uint32_t numItems2, int64_t byteStride2) { return ospNewSharedData( sharedData, type, numItems1, byteStride1, numItems2, byteStride2, 1, 0); } OSPData ospNewSharedData3D(const void *sharedData, OSPDataType type, uint32_t numItems1, uint32_t numItems2, uint32_t numItems3) { return ospNewSharedData( sharedData, type, numItems1, 0, numItems2, 0, numItems3, 0); } OSPData ospNewData1D(OSPDataType type, uint32_t numItems) { return ospNewData(type, numItems, 1, 1); } OSPData ospNewData2D(OSPDataType type, uint32_t numItems1, uint32_t numItems2) { return ospNewData(type, numItems1, numItems2, 1); } void ospCopyData1D(const OSPData source, OSPData destination, uint32_t destinationIndex) { ospCopyData(source, destination, destinationIndex, 0, 0); } void ospCopyData2D(const OSPData source, OSPData destination, uint32_t destinationIndex1, uint32_t destinationIndex2) { ospCopyData(source, destination, destinationIndex1, destinationIndex2, 0); } // Parameter helpers //////////////////////////////////////////////////////// void ospSetString(OSPObject o, const char *id, const char *s) { ospSetParam(o, id, OSP_STRING, &s); } void ospSetObject(OSPObject o, const char *id, OSPObject other) { ospSetParam(o, id, OSP_OBJECT, &other); } void ospSetBool(OSPObject o, const char *id, int x) { ospSetParam(o, id, OSP_BOOL, &x); } void ospSetFloat(OSPObject o, const char *id, float x) { ospSetParam(o, id, OSP_FLOAT, &x); } void ospSetInt(OSPObject o, const char *id, int x) { ospSetParam(o, id, OSP_INT, &x); } void ospSetVec2f(OSPObject o, const char *id, float x, float y) { float v[] = {x, y}; ospSetParam(o, id, OSP_VEC2F, v); } void ospSetVec3f(OSPObject o, const char *id, float x, float y, float z) { float v[] = {x, y, z}; ospSetParam(o, id, OSP_VEC3F, v); } void ospSetVec4f( OSPObject o, const char *id, float x, float y, float z, float w) { float v[] = {x, y, z, w}; ospSetParam(o, id, OSP_VEC4F, v); } void ospSetVec2i(OSPObject o, const char *id, int x, int y) { int v[] = {x, y}; ospSetParam(o, id, OSP_VEC2I, v); } void ospSetVec3i(OSPObject o, const char *id, int x, int y, int z) { int v[] = {x, y, z}; ospSetParam(o, id, OSP_VEC3I, v); } void ospSetVec4i(OSPObject o, const char *id, int x, int y, int z, int w) { int v[] = {x, y, z, w}; ospSetParam(o, id, OSP_VEC4I, v); } void ospSetObjectAsData(OSPObject o, const char *n, OSPDataType type, OSPObject p) { OSPData data = ospNewData(1, type, &p); ospSetObject(o, n, data); ospRelease(data); } // Rendering helpers ////////////////////////////////////////////////////////// float ospRenderFrameBlocking(OSPFrameBuffer fb, OSPRenderer renderer, OSPCamera camera, OSPWorld world) { OSPFuture f = ospRenderFrame(fb, renderer, camera, world); ospRelease(f); return ospGetVariance(fb); } } // extern "C" // XXX temporary, to maintain backwards compatibility OSPData ospNewData(size_t numItems, OSPDataType type, const void *source, uint32_t dataCreationFlags) { if (dataCreationFlags) return ospNewSharedData(source, type, numItems); else { OSPData src = ospNewSharedData(source, type, numItems); OSPData dst = ospNewData(type, numItems); ospCopyData(src, dst); ospRelease(src); return dst; } } <commit_msg>fix missing ospWait() in ospRenderFrameBlocking()<commit_after>// ======================================================================== // // 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 "ospray/ospray_util.h" extern "C" { // OSPData helpers //////////////////////////////////////////////////////////// OSPData ospNewSharedData1D(const void *sharedData, OSPDataType type, uint32_t numItems) { return ospNewSharedData(sharedData, type, numItems, 0, 1, 0, 1, 0); } OSPData ospNewSharedData1DStride(const void *sharedData, OSPDataType type, uint32_t numItems, int64_t byteStride) { return ospNewSharedData(sharedData, type, numItems, byteStride, 1, 0, 1, 0); } OSPData ospNewSharedData2D(const void *sharedData, OSPDataType type, uint32_t numItems1, uint32_t numItems2) { return ospNewSharedData(sharedData, type, numItems1, 0, numItems2, 0, 1, 0); } OSPData ospNewSharedData2DStride(const void *sharedData, OSPDataType type, uint32_t numItems1, int64_t byteStride1, uint32_t numItems2, int64_t byteStride2) { return ospNewSharedData( sharedData, type, numItems1, byteStride1, numItems2, byteStride2, 1, 0); } OSPData ospNewSharedData3D(const void *sharedData, OSPDataType type, uint32_t numItems1, uint32_t numItems2, uint32_t numItems3) { return ospNewSharedData( sharedData, type, numItems1, 0, numItems2, 0, numItems3, 0); } OSPData ospNewData1D(OSPDataType type, uint32_t numItems) { return ospNewData(type, numItems, 1, 1); } OSPData ospNewData2D(OSPDataType type, uint32_t numItems1, uint32_t numItems2) { return ospNewData(type, numItems1, numItems2, 1); } void ospCopyData1D(const OSPData source, OSPData destination, uint32_t destinationIndex) { ospCopyData(source, destination, destinationIndex, 0, 0); } void ospCopyData2D(const OSPData source, OSPData destination, uint32_t destinationIndex1, uint32_t destinationIndex2) { ospCopyData(source, destination, destinationIndex1, destinationIndex2, 0); } // Parameter helpers //////////////////////////////////////////////////////// void ospSetString(OSPObject o, const char *id, const char *s) { ospSetParam(o, id, OSP_STRING, &s); } void ospSetObject(OSPObject o, const char *id, OSPObject other) { ospSetParam(o, id, OSP_OBJECT, &other); } void ospSetBool(OSPObject o, const char *id, int x) { ospSetParam(o, id, OSP_BOOL, &x); } void ospSetFloat(OSPObject o, const char *id, float x) { ospSetParam(o, id, OSP_FLOAT, &x); } void ospSetInt(OSPObject o, const char *id, int x) { ospSetParam(o, id, OSP_INT, &x); } void ospSetVec2f(OSPObject o, const char *id, float x, float y) { float v[] = {x, y}; ospSetParam(o, id, OSP_VEC2F, v); } void ospSetVec3f(OSPObject o, const char *id, float x, float y, float z) { float v[] = {x, y, z}; ospSetParam(o, id, OSP_VEC3F, v); } void ospSetVec4f( OSPObject o, const char *id, float x, float y, float z, float w) { float v[] = {x, y, z, w}; ospSetParam(o, id, OSP_VEC4F, v); } void ospSetVec2i(OSPObject o, const char *id, int x, int y) { int v[] = {x, y}; ospSetParam(o, id, OSP_VEC2I, v); } void ospSetVec3i(OSPObject o, const char *id, int x, int y, int z) { int v[] = {x, y, z}; ospSetParam(o, id, OSP_VEC3I, v); } void ospSetVec4i(OSPObject o, const char *id, int x, int y, int z, int w) { int v[] = {x, y, z, w}; ospSetParam(o, id, OSP_VEC4I, v); } void ospSetObjectAsData(OSPObject o, const char *n, OSPDataType type, OSPObject p) { OSPData data = ospNewData(1, type, &p); ospSetObject(o, n, data); ospRelease(data); } // Rendering helpers ////////////////////////////////////////////////////////// float ospRenderFrameBlocking(OSPFrameBuffer fb, OSPRenderer renderer, OSPCamera camera, OSPWorld world) { OSPFuture f = ospRenderFrame(fb, renderer, camera, world); ospWait(f, OSP_TASK_FINISHED); ospRelease(f); return ospGetVariance(fb); } } // extern "C" // XXX temporary, to maintain backwards compatibility OSPData ospNewData(size_t numItems, OSPDataType type, const void *source, uint32_t dataCreationFlags) { if (dataCreationFlags) return ospNewSharedData(source, type, numItems); else { OSPData src = ospNewSharedData(source, type, numItems); OSPData dst = ospNewData(type, numItems); ospCopyData(src, dst); ospRelease(src); return dst; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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. */ // Author: Jon Binney #include <Eigen/Core> #include <Eigen/Geometry> #include <tf/transform_listener.h> #include <moveit/plan_execution/plan_execution.h> #include <moveit/kinematics_planner/kinematics_planner.h> #include <moveit/trajectory_processing/trajectory_tools.h> #include <moveit_msgs/PositionConstraint.h> #include <shape_msgs/SolidPrimitive.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/PoseStamped.h> #include <visualization_msgs/Marker.h> static const std::string ROBOT_DESCRIPTION = "robot_description"; // name of the robot description (a param name, so it can be changed externally) static const std::string NODE_NAME = "test_kinematics_planner"; // name of node static const std::string GROUP_NAME = "left_arm"; static const std::string END_EFFECTOR_FRAME_NAME = "l_wrist_roll_link"; static const std::string END_EFFECTOR_LINK_NAME = "l_wrist_roll_link"; static const ros::Duration ALLOWED_PLANNING_TIME(5.0); static const int NUM_PLANNING_ATTEMPTS = 1; static const ros::Duration WAIT_LOOP_DURATION(0.01); static const double INTERPOLATED_IK_PLANNING_TIME = 5.0; void make_grasp_marker(const std::string &ns, const geometry_msgs::PoseStamped &ps, visualization_msgs::Marker &m) { m.action = visualization_msgs::Marker::ADD; m.header = ps.header; m.ns = ns; m.id = 0; m.type = visualization_msgs::Marker::ARROW; m.pose = ps.pose; m.color.r = 1.0; m.color.a = 1.0; m.scale.x = 0.2; m.scale.y = 0.02; m.scale.z = 0.02; } int main(int argc, char **argv) { ros::init(argc, argv, NODE_NAME); ros::NodeHandle nh; ros::AsyncSpinner spinner(4); // Use 4 threads spinner.start(); ROS_INFO("Advertising markers"); ros::Duration(1.0).sleep(); ros::Publisher pub = nh.advertise<visualization_msgs::Marker>("grasp_debug", 5); ROS_INFO("Waiting one second for subscribers"); ros::Duration(1.0).sleep(); ROS_INFO("Creating planning Scene"); boost::shared_ptr<tf::TransformListener> tf(new tf::TransformListener()); planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor(new planning_scene_monitor::PlanningSceneMonitor(ROBOT_DESCRIPTION, tf)); if (planning_scene_monitor->getPlanningScene() && planning_scene_monitor->getPlanningScene()->isConfigured()) { planning_scene_monitor->startWorldGeometryMonitor(); planning_scene_monitor->startSceneMonitor(); planning_scene_monitor->startStateMonitor(); } else { ROS_ERROR("Planning scene not configured"); return -1; } plan_execution::PlanExecution plan_execution(planning_scene_monitor); ROS_INFO("Waiting for robot state"); std::vector<std::string> missing_joints; while(!planning_scene_monitor->getStateMonitor()->haveCompleteState(missing_joints)) { ROS_INFO("Waiting for current joint states"); for(unsigned int joint_i = 0; joint_i < missing_joints.size(); joint_i++) ROS_INFO("Missing joint: %s", missing_joints[joint_i].c_str()); WAIT_LOOP_DURATION.sleep(); } /* get the current gripper pose */ planning_scene_monitor->updateFrameTransforms(); kinematic_state::KinematicState kinematic_state = planning_scene_monitor->getPlanningScene()->getCurrentState(); const Eigen::Affine3d *gripper_pose = kinematic_state.getFrameTransform(END_EFFECTOR_LINK_NAME); ROS_INFO_STREAM("Current gripper pose:" << (gripper_pose->matrix())); Eigen::Vector3d t = gripper_pose->translation(); Eigen::Quaterniond q; q = gripper_pose->rotation(); ROS_INFO("Current gripper trans: %f %f %f", t.x(), t.y(), t.z()); ROS_INFO("Current gripper rot: %f %f %f %f", q.x(), q.y(), q.z(), q.w()); /* start position is current position */ geometry_msgs::PoseStamped ps_start, ps_end; ps_start.header.frame_id = "base_link"; ps_start.header.stamp = ros::Time::now(); ps_start.pose.position.x = t.x(); ps_start.pose.position.y = t.y(); ps_start.pose.position.z = t.z(); ps_start.pose.orientation.x = q.x(); ps_start.pose.orientation.y = q.y(); ps_start.pose.orientation.z = q.z(); ps_start.pose.orientation.w = q.w(); /* end position is start position shifted a bit */ ps_end = ps_start; ps_end.pose.position.x -= 0.1; /* publish rviz markers for the start and end poses */ visualization_msgs::Marker m_start, m_end; make_grasp_marker("iik_start_pose", ps_start, m_start); make_grasp_marker("iik_end_pose", ps_end, m_end); pub.publish(m_start); pub.publish(m_end); /* create an interpolated IK planner */ kinematics_planner::KinematicsPlanner kin_planner; std::vector<std::string> group_names; group_names.push_back(GROUP_NAME); kin_planner.initialize(group_names, planning_scene_monitor->getKinematicModel()); std::map<std::string,geometry_msgs::PoseStamped> start_request; start_request[GROUP_NAME] = ps_start; std::map<std::string,geometry_msgs::PoseStamped> goal_request; goal_request[GROUP_NAME] = ps_end; moveit_msgs::Constraints path_constraints; moveit_msgs::RobotTrajectory robot_trajectory; moveit_msgs::MoveItErrorCodes error_code; /* create plan using interpolated IK planner */ bool r = kin_planner.solve(start_request, goal_request, planning_scene_monitor->getPlanningScene(), path_constraints, INTERPOLATED_IK_PLANNING_TIME, robot_trajectory, error_code); if(r) { ROS_INFO("Got solution from kinematics planner"); ROS_INFO_STREAM("Solution: " << robot_trajectory); } else { ROS_INFO("Unable to solve. Error code: %d", error_code.val); } /* execute the planned trajectory */ ROS_INFO("Executing trajectory"); plan_execution.getTrajectoryExecutionManager().clear(); if(plan_execution.getTrajectoryExecutionManager().push(robot_trajectory)) { plan_execution.getTrajectoryExecutionManager().execute(); /* wait for the trajectory to complete */ moveit_controller_manager::ExecutionStatus es = plan_execution.getTrajectoryExecutionManager().waitForExecution(); if (es == moveit_controller_manager::ExecutionStatus::SUCCEEDED) ROS_INFO("Trajectory execution succeeded"); else if (es == moveit_controller_manager::ExecutionStatus::PREEMPTED) ROS_INFO("Trajectory execution preempted"); else if (es == moveit_controller_manager::ExecutionStatus::TIMED_OUT) ROS_INFO("Trajectory execution timed out"); else ROS_INFO("Trajectory execution control failed"); } else { ROS_INFO("Failed to push trajectory"); return -1; } planning_scene_monitor->stopSceneMonitor(); ros::spin(); return 0; } <commit_msg>forgot to fix this<commit_after>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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. */ // Author: Jon Binney #include <Eigen/Core> #include <Eigen/Geometry> #include <tf/transform_listener.h> #include <moveit/plan_execution/plan_execution.h> #include <moveit/kinematics_planner/kinematics_planner.h> #include <moveit/trajectory_processing/trajectory_tools.h> #include <moveit_msgs/PositionConstraint.h> #include <shape_msgs/SolidPrimitive.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/PoseStamped.h> #include <visualization_msgs/Marker.h> static const std::string ROBOT_DESCRIPTION = "robot_description"; // name of the robot description (a param name, so it can be changed externally) static const std::string NODE_NAME = "test_kinematics_planner"; // name of node static const std::string GROUP_NAME = "left_arm"; static const std::string END_EFFECTOR_FRAME_NAME = "l_wrist_roll_link"; static const std::string END_EFFECTOR_LINK_NAME = "l_wrist_roll_link"; static const ros::Duration ALLOWED_PLANNING_TIME(5.0); static const int NUM_PLANNING_ATTEMPTS = 1; static const ros::Duration WAIT_LOOP_DURATION(0.01); static const double INTERPOLATED_IK_PLANNING_TIME = 5.0; void make_grasp_marker(const std::string &ns, const geometry_msgs::PoseStamped &ps, visualization_msgs::Marker &m) { m.action = visualization_msgs::Marker::ADD; m.header = ps.header; m.ns = ns; m.id = 0; m.type = visualization_msgs::Marker::ARROW; m.pose = ps.pose; m.color.r = 1.0; m.color.a = 1.0; m.scale.x = 0.2; m.scale.y = 0.02; m.scale.z = 0.02; } int main(int argc, char **argv) { ros::init(argc, argv, NODE_NAME); ros::NodeHandle nh; ros::AsyncSpinner spinner(4); // Use 4 threads spinner.start(); ROS_INFO("Advertising markers"); ros::Duration(1.0).sleep(); ros::Publisher pub = nh.advertise<visualization_msgs::Marker>("grasp_debug", 5); ROS_INFO("Waiting one second for subscribers"); ros::Duration(1.0).sleep(); ROS_INFO("Creating planning Scene"); boost::shared_ptr<tf::TransformListener> tf(new tf::TransformListener()); planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor(new planning_scene_monitor::PlanningSceneMonitor(ROBOT_DESCRIPTION, tf)); if (planning_scene_monitor->getPlanningScene() && planning_scene_monitor->getPlanningScene()->isConfigured()) { planning_scene_monitor->startWorldGeometryMonitor(); planning_scene_monitor->startSceneMonitor(); planning_scene_monitor->startStateMonitor(); } else { ROS_ERROR("Planning scene not configured"); return -1; } plan_execution::PlanExecution plan_execution(planning_scene_monitor); ROS_INFO("Waiting for robot state"); std::vector<std::string> missing_joints; while(!planning_scene_monitor->getStateMonitor()->haveCompleteState(missing_joints)) { ROS_INFO("Waiting for current joint states"); for(unsigned int joint_i = 0; joint_i < missing_joints.size(); joint_i++) ROS_INFO("Missing joint: %s", missing_joints[joint_i].c_str()); WAIT_LOOP_DURATION.sleep(); } /* get the current gripper pose */ planning_scene_monitor->updateFrameTransforms(); kinematic_state::KinematicState kinematic_state = planning_scene_monitor->getPlanningScene()->getCurrentState(); const Eigen::Affine3d *gripper_pose = kinematic_state.getFrameTransform(END_EFFECTOR_LINK_NAME); ROS_INFO_STREAM("Current gripper pose:" << (gripper_pose->matrix())); Eigen::Vector3d t = gripper_pose->translation(); Eigen::Quaterniond q; q = gripper_pose->rotation(); ROS_INFO("Current gripper trans: %f %f %f", t.x(), t.y(), t.z()); ROS_INFO("Current gripper rot: %f %f %f %f", q.x(), q.y(), q.z(), q.w()); /* start position is current position */ geometry_msgs::PoseStamped ps_start, ps_end; ps_start.header.frame_id = "base_link"; ps_start.header.stamp = ros::Time::now(); ps_start.pose.position.x = t.x(); ps_start.pose.position.y = t.y(); ps_start.pose.position.z = t.z(); ps_start.pose.orientation.x = q.x(); ps_start.pose.orientation.y = q.y(); ps_start.pose.orientation.z = q.z(); ps_start.pose.orientation.w = q.w(); /* end position is start position shifted a bit */ ps_end = ps_start; ps_end.pose.position.x -= 0.1; /* publish rviz markers for the start and end poses */ visualization_msgs::Marker m_start, m_end; make_grasp_marker("iik_start_pose", ps_start, m_start); make_grasp_marker("iik_end_pose", ps_end, m_end); pub.publish(m_start); pub.publish(m_end); /* create an interpolated IK planner */ kinematics_planner::KinematicsPlanner kin_planner; std::vector<std::string> group_names; group_names.push_back(GROUP_NAME); kin_planner.initialize(group_names, planning_scene_monitor->getKinematicModel()); std::map<std::string,geometry_msgs::PoseStamped> start_request; start_request[GROUP_NAME] = ps_start; std::map<std::string,geometry_msgs::PoseStamped> goal_request; goal_request[GROUP_NAME] = ps_end; moveit_msgs::Constraints path_constraints; moveit_msgs::RobotTrajectory robot_trajectory; moveit_msgs::MoveItErrorCodes error_code; /* create plan using interpolated IK planner */ bool r = kin_planner.solve(start_request, goal_request, planning_scene_monitor->getPlanningScene(), path_constraints, INTERPOLATED_IK_PLANNING_TIME, robot_trajectory, error_code); if(r) { ROS_INFO("Got solution from kinematics planner"); ROS_INFO_STREAM("Solution: " << robot_trajectory); } else { ROS_INFO("Unable to solve. Error code: %d", error_code.val); } /* execute the planned trajectory */ ROS_INFO("Executing trajectory"); plan_execution.getTrajectoryExecutionManager()->clear(); if(plan_execution.getTrajectoryExecutionManager()->push(robot_trajectory)) { plan_execution.getTrajectoryExecutionManager()->execute(); /* wait for the trajectory to complete */ moveit_controller_manager::ExecutionStatus es = plan_execution.getTrajectoryExecutionManager()->waitForExecution(); if (es == moveit_controller_manager::ExecutionStatus::SUCCEEDED) ROS_INFO("Trajectory execution succeeded"); else if (es == moveit_controller_manager::ExecutionStatus::PREEMPTED) ROS_INFO("Trajectory execution preempted"); else if (es == moveit_controller_manager::ExecutionStatus::TIMED_OUT) ROS_INFO("Trajectory execution timed out"); else ROS_INFO("Trajectory execution control failed"); } else { ROS_INFO("Failed to push trajectory"); return -1; } planning_scene_monitor->stopSceneMonitor(); ros::spin(); return 0; } <|endoftext|>
<commit_before>// // redpine_module.cpp // Mono::Redpine // // Created by Kristoffer Andersen on 27/05/15. // // #include "redpine_module.h" #include <consoles.h> #include <mbed.h> #include <application_context_interface.h> using namespace mono::redpine; /** Construct the module */ Module Module::moduleSingleton; Module::Module() { communicationInitialized = false; networkInitialized = false; } /// MARK: STATIC PUBLIC METHODS Module* Module::Instance() { return &Module::moduleSingleton; } bool Module::initialize(ModuleCommunication *commInterface) { if (commInterface == NULL) { debug("Cannot init Redpine Module without comm. interface!\n\r"); return false; } // Assign interface to object Module* self = Module::Instance(); self->comIntf = commInterface; self->comIntf->resetModule(); self->CurrentPowerState = FULL_AWAKE; //debug("Initializing communication interface...\n\r"); // initalize interface bool success = self->comIntf->initializeInterface(); if (!success) { debug("Initialize failed to init communication interface\n\r"); return false; } mono::IApplicationContext::Instance->PowerManager->AppendToPowerAwareQueue(self); //debug("Checking bootloader state...\n\r"); uint16_t regval = self->comIntf->readMemory(HOST_INTF_REG_OUT); debug("HOST_INTF_REG_OUT: 0x%x\n\r", regval); if ((regval & HOST_INTERACT_REG_VALID) == 0xAB00) { //debug("Module is in bootloader, load Image-I...\n\r"); self->comIntf->InterfaceVersion = regval; self->comIntf->writeMemory(HOST_INTF_REG_IN, HOST_INTERACT_REG_VALID | RSI_LOAD_IMAGE_I_FW); } // we need to wait for board ready frame //debug("Waiting for card ready to arrive on input...\n\r"); int timeout = 0; while (!self->comIntf->pollInputQueue() && timeout++ < 50) { //wait a while wait_ms(2); } if (timeout >= 50) { debug("Timeout: Did not receive Card ready!\n\r"); return false; } ManagementFrame frame; success = self->comIntf->readManagementFrame(frame); if (!success) { debug("failed to read card ready!"); return false; } self->comIntf->interruptCallback.attach<mono::redpine::Module>(self, &Module::moduleEventHandler); if (frame.commandId == ModuleFrame::CardReady) { //debug("Card ready received\n\r"); self->communicationInitialized = true; return true; } else { debug("Initialization failed on receiving card ready\n\r"); debug("Initialization got 0x%x, not card ready\n\r",frame.commandId); return false; } } bool Module::setupWifiOnly(String ssid, String passphrase, WifiSecurityModes secMode) { // send "set operating mode command" Module *self = Module::Instance(); if (!self->communicationInitialized) { debug("Module not initialized. You must initialize first!"); return false; } //debug("Setting OperMode...\n\r"); SetOperatingModeFrame *opermode = new SetOperatingModeFrame(SetOperatingModeFrame::WIFI_CLIENT_MODE); opermode->setDefaultConfiguration(); opermode->commitAsync(); //debug("Setting band...\n\r"); BandFrame *band = new BandFrame(); band->commitAsync(); //debug("Initialize module RF and baseband...\n\r"); InitFrame *init = new InitFrame(); init->commitAsync(); //debug("Scanning for networks...\n\r"); ScanFrame *scan = new ScanFrame(); scan->commitAsync(); //debug("Connecting to %s\n\r",ssid); JoinFrame *join = new JoinFrame(ssid, passphrase, secMode); join->commitAsync(); //debug("Getting IP address from DHCP...\n\r"); SetIpParametersFrame *ipparam = new SetIpParametersFrame(); if (self->staticIPHandler) { ipparam->dhcpMode = SetIpParametersFrame::STATIC_IP; StaticIPParams params; self->staticIPHandler.call(&params); memcpy(ipparam->ipAddress, params.ipAddress, 4); memcpy(ipparam->netmask, params.netmask, 4); memcpy(ipparam->gateway, params.gateway, 4); } ipparam->setCompletionCallback<Module>(Module::Instance(), &Module::onNetworkReady); ipparam->commitAsync(); return true; } bool Module::IsNetworkReady() { return Module::Instance()->networkInitialized; } /// MARK: PRIVATE METHODS void Module::moduleEventHandler() { if (CurrentPowerState & (LOW_SLEEP | ULTRA_LOW_SLEEP)) handleSleepWakeUp(); else { if (comIntf->pollInputQueue()) { //handle a response for any pending request ManagementFrame *respFrame = responseFrameQueue.Peek(); if (respFrame == NULL) { debug("nothing on request queue!\n\r"); ManagementFrame frame; bool success = comIntf->readManagementFrame(frame); if (!success) { debug("Failed to read unexcepted mgmt frame\n\r"); } } else { debug("resp frame cmd id: 0x%x\n\r",respFrame->commandId); //memdump(reqFrame, sizeof(mono::redpine::HttpGetFrame)); bool success = this->comIntf->readManagementFrameResponse(*respFrame); if (!success) { responseFrameQueue.Remove(respFrame); debug("failed to handle incoming response for resp queue head\n\r"); respFrame->status = 1; respFrame->triggerCompletionHandler(); } else if (respFrame->lastResponseParsed) { //debug("Frame (0x%x): last response parsed!\n\r",respFrame->commandId); responseFrameQueue.Remove(respFrame); respFrame->triggerCompletionHandler(); if (respFrame->autoReleaseWhenParsed) { //debug("deleting resp frame 0x%x!\n\r",respFrame->commandId); delete respFrame; } else { debug("leaving frame 0x%x\n\r",respFrame->commandId); } } } } // if no response is pending, send new request if (responseFrameQueue.Length() == 0 && requestFrameQueue.Length() > 0) { ManagementFrame *request = requestFrameQueue.Dequeue(); //debug("Sending Mgmt request 0x%x\n\r",request->commandId); bool success = request->writeFrame(); if (!success) { debug("Failed to send MgmtFrame (0x%x) to module\n\r",request->commandId); if (request->autoReleaseWhenParsed) delete request; return; } responseFrameQueue.Enqueue(request); } } } void Module::onNetworkReady(ManagementFrame::FrameCompletionData *data) { if (data->Context->commandId == ModuleFrame::SetIPParameters) { SetIpParametersFrame *ip = (SetIpParametersFrame*) data->Context; memcpy(this->ipAddress, ip->ipAddress, 4); memcpy(this->netmask, ip->netmask, 4); memcpy(this->gateway, ip->gateway, 4); memcpy(this->macAddress, ip->macAddress, 6); debug("Network Ready!\n\r"); networkInitialized = true; if (networkReadyHandler) { networkReadyHandler.call(); } } } void Module::handleSleepWakeUp() { if (!(CurrentPowerState & (ULTRA_LOW_SLEEP | LOW_SLEEP))) { debug("Module not in sleep!\n\r"); return; } // if interface was initialized, we are out of sleep if (comIntf->initializeInterface()) CurrentPowerState = FULL_AWAKE; if (comIntf->pollInputQueue()) { ManagementFrame frame; comIntf->readManagementFrame(frame); if (frame.commandId == ManagementFrame::WakeFromSleep) { debug("putting to sleep again!\n\r"); ManagementFrame sleepAgain(ManagementFrame::PowerSaveACK); sleepAgain.commit(); } else { debug("Unkown commandID for handleSleepWakeUp: 0x%x\n\r",frame.commandId); } } else { debug("nothing in input poll queue\n\r"); } } void Module::onSystemPowerOnReset() { } void Module::onSystemEnterSleep() { //comIntf->resetModule(); } void Module::onSystemWakeFromSleep() { } void Module::OnSystemBatteryLow() { } <commit_msg>Wire module handles failed request<commit_after>// // redpine_module.cpp // Mono::Redpine // // Created by Kristoffer Andersen on 27/05/15. // // #include "redpine_module.h" #include <consoles.h> #include <mbed.h> #include <application_context_interface.h> using namespace mono::redpine; /** Construct the module */ Module Module::moduleSingleton; Module::Module() { communicationInitialized = false; networkInitialized = false; } /// MARK: STATIC PUBLIC METHODS Module* Module::Instance() { return &Module::moduleSingleton; } bool Module::initialize(ModuleCommunication *commInterface) { if (commInterface == NULL) { debug("Cannot init Redpine Module without comm. interface!\n\r"); return false; } // Assign interface to object Module* self = Module::Instance(); self->comIntf = commInterface; self->comIntf->resetModule(); self->CurrentPowerState = FULL_AWAKE; //debug("Initializing communication interface...\n\r"); // initalize interface bool success = self->comIntf->initializeInterface(); if (!success) { debug("Initialize failed to init communication interface\n\r"); return false; } mono::IApplicationContext::Instance->PowerManager->AppendToPowerAwareQueue(self); //debug("Checking bootloader state...\n\r"); uint16_t regval = self->comIntf->readMemory(HOST_INTF_REG_OUT); debug("HOST_INTF_REG_OUT: 0x%x\n\r", regval); if ((regval & HOST_INTERACT_REG_VALID) == 0xAB00) { //debug("Module is in bootloader, load Image-I...\n\r"); self->comIntf->InterfaceVersion = regval; self->comIntf->writeMemory(HOST_INTF_REG_IN, HOST_INTERACT_REG_VALID | RSI_LOAD_IMAGE_I_FW); } // we need to wait for board ready frame //debug("Waiting for card ready to arrive on input...\n\r"); int timeout = 0; while (!self->comIntf->pollInputQueue() && timeout++ < 50) { //wait a while wait_ms(2); } if (timeout >= 50) { debug("Timeout: Did not receive Card ready!\n\r"); return false; } ManagementFrame frame; success = self->comIntf->readManagementFrame(frame); if (!success) { debug("failed to read card ready!"); return false; } self->comIntf->interruptCallback.attach<mono::redpine::Module>(self, &Module::moduleEventHandler); if (frame.commandId == ModuleFrame::CardReady) { //debug("Card ready received\n\r"); self->communicationInitialized = true; return true; } else { debug("Initialization failed on receiving card ready\n\r"); debug("Initialization got 0x%x, not card ready\n\r",frame.commandId); return false; } } bool Module::setupWifiOnly(String ssid, String passphrase, WifiSecurityModes secMode) { // send "set operating mode command" Module *self = Module::Instance(); if (!self->communicationInitialized) { debug("Module not initialized. You must initialize first!"); return false; } //debug("Setting OperMode...\n\r"); SetOperatingModeFrame *opermode = new SetOperatingModeFrame(SetOperatingModeFrame::WIFI_CLIENT_MODE); opermode->setDefaultConfiguration(); opermode->commitAsync(); //debug("Setting band...\n\r"); BandFrame *band = new BandFrame(); band->commitAsync(); //debug("Initialize module RF and baseband...\n\r"); InitFrame *init = new InitFrame(); init->commitAsync(); //debug("Scanning for networks...\n\r"); ScanFrame *scan = new ScanFrame(); scan->commitAsync(); //debug("Connecting to %s\n\r",ssid); JoinFrame *join = new JoinFrame(ssid, passphrase, secMode); join->commitAsync(); //debug("Getting IP address from DHCP...\n\r"); SetIpParametersFrame *ipparam = new SetIpParametersFrame(); if (self->staticIPHandler) { ipparam->dhcpMode = SetIpParametersFrame::STATIC_IP; StaticIPParams params; self->staticIPHandler.call(&params); memcpy(ipparam->ipAddress, params.ipAddress, 4); memcpy(ipparam->netmask, params.netmask, 4); memcpy(ipparam->gateway, params.gateway, 4); } ipparam->setCompletionCallback<Module>(Module::Instance(), &Module::onNetworkReady); ipparam->commitAsync(); return true; } bool Module::IsNetworkReady() { return Module::Instance()->networkInitialized; } /// MARK: PRIVATE METHODS void Module::moduleEventHandler() { if (CurrentPowerState & (LOW_SLEEP | ULTRA_LOW_SLEEP)) handleSleepWakeUp(); else { if (comIntf->pollInputQueue()) { //handle a response for any pending request ManagementFrame *respFrame = responseFrameQueue.Peek(); if (respFrame == NULL) { debug("nothing on request queue!\n\r"); ManagementFrame frame; bool success = comIntf->readManagementFrame(frame); if (!success) { debug("Failed to read unexcepted mgmt frame\n\r"); } } else { debug("resp frame cmd id: 0x%x\n\r",respFrame->commandId); //memdump(reqFrame, sizeof(mono::redpine::HttpGetFrame)); bool success = this->comIntf->readManagementFrameResponse(*respFrame); if (!success) { responseFrameQueue.Remove(respFrame); debug("failed to handle incoming response for resp queue head\n\r"); respFrame->status = 1; respFrame->triggerCompletionHandler(); } else if (respFrame->lastResponseParsed) { //debug("Frame (0x%x): last response parsed!\n\r",respFrame->commandId); responseFrameQueue.Remove(respFrame); respFrame->triggerCompletionHandler(); if (respFrame->autoReleaseWhenParsed) { //debug("deleting resp frame 0x%x!\n\r",respFrame->commandId); delete respFrame; } else { debug("leaving frame 0x%x\n\r",respFrame->commandId); } } } } // if no response is pending, send new request if (responseFrameQueue.Length() == 0 && requestFrameQueue.Length() > 0) { ManagementFrame *request = requestFrameQueue.Dequeue(); //debug("Sending Mgmt request 0x%x\n\r",request->commandId); bool success = request->writeFrame(); if (!success) { debug("Failed to send MgmtFrame (0x%x) to module\n\r",request->commandId); request->status = 1; request->triggerCompletionHandler(); if (request->autoReleaseWhenParsed) delete request; return; } responseFrameQueue.Enqueue(request); } } } void Module::onNetworkReady(ManagementFrame::FrameCompletionData *data) { if (data->Context->commandId == ModuleFrame::SetIPParameters) { SetIpParametersFrame *ip = (SetIpParametersFrame*) data->Context; memcpy(this->ipAddress, ip->ipAddress, 4); memcpy(this->netmask, ip->netmask, 4); memcpy(this->gateway, ip->gateway, 4); memcpy(this->macAddress, ip->macAddress, 6); debug("Network Ready!\n\r"); networkInitialized = true; if (networkReadyHandler) { networkReadyHandler.call(); } } } void Module::handleSleepWakeUp() { if (!(CurrentPowerState & (ULTRA_LOW_SLEEP | LOW_SLEEP))) { debug("Module not in sleep!\n\r"); return; } // if interface was initialized, we are out of sleep if (comIntf->initializeInterface()) CurrentPowerState = FULL_AWAKE; if (comIntf->pollInputQueue()) { ManagementFrame frame; comIntf->readManagementFrame(frame); if (frame.commandId == ManagementFrame::WakeFromSleep) { debug("putting to sleep again!\n\r"); ManagementFrame sleepAgain(ManagementFrame::PowerSaveACK); sleepAgain.commit(); } else { debug("Unkown commandID for handleSleepWakeUp: 0x%x\n\r",frame.commandId); } } else { debug("nothing in input poll queue\n\r"); } } void Module::onSystemPowerOnReset() { } void Module::onSystemEnterSleep() { //comIntf->resetModule(); } void Module::onSystemWakeFromSleep() { } void Module::OnSystemBatteryLow() { } <|endoftext|>
<commit_before>#ifndef ITER_SLIDING_WINDOW_HPP_ #define ITER_SLIDING_WINDOW_HPP_ #include "iterbase.hpp" #include <deque> #include <utility> #include <iterator> namespace iter { template <typename Container> class SlidingWindow; template <typename Container> SlidingWindow<Container> sliding_window(Container&&, std::size_t); template <typename T> SlidingWindow<std::initializer_list<T>> sliding_window( std::initializer_list<T>, std::size_t); template <typename Container> class SlidingWindow { private: Container container; std::size_t window_size; friend SlidingWindow sliding_window<Container>( Container&&, std::size_t); template <typename T> friend SlidingWindow<std::initializer_list<T>> sliding_window( std::initializer_list<T>, std::size_t); SlidingWindow(Container container, std::size_t win_sz) : container(std::forward<Container>(container)), window_size{win_sz} { } using DerefVec = std::deque<collection_item_type<Container>>; public: class Iterator : public std::iterator<std::input_iterator_tag, DerefVec> { private: iterator_type<Container> sub_iter; DerefVec window; public: Iterator(const iterator_type<Container>& in_iter, const iterator_type<Container>& in_end, std::size_t window_sz) : sub_iter(in_iter) { std::size_t i{0}; while (i < window_sz && this->sub_iter != in_end) { this->window.push_back(*this->sub_iter); ++i; if (i != window_sz) ++this->sub_iter; } } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } DerefVec& operator*() { return this->window; } Iterator& operator++() { ++this->sub_iter; this->window.pop_front(); this->window.push_back(*this->sub_iter); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } }; Iterator begin() { return {std::begin(container), std::end(container), window_size}; } Iterator end() { return {std::end(container), std::end(container), window_size}; } }; template <typename Container> SlidingWindow<Container> sliding_window( Container&& container, std::size_t window_size) { return {std::forward<Container>(container), window_size}; } template <typename T> SlidingWindow<std::initializer_list<T>> sliding_window( std::initializer_list<T> il, std::size_t window_size) { return {il, window_size}; } } #endif <commit_msg>handles window size of 0<commit_after>#ifndef ITER_SLIDING_WINDOW_HPP_ #define ITER_SLIDING_WINDOW_HPP_ #include "iterbase.hpp" #include <deque> #include <utility> #include <iterator> namespace iter { template <typename Container> class SlidingWindow; template <typename Container> SlidingWindow<Container> sliding_window(Container&&, std::size_t); template <typename T> SlidingWindow<std::initializer_list<T>> sliding_window( std::initializer_list<T>, std::size_t); template <typename Container> class SlidingWindow { private: Container container; std::size_t window_size; friend SlidingWindow sliding_window<Container>( Container&&, std::size_t); template <typename T> friend SlidingWindow<std::initializer_list<T>> sliding_window( std::initializer_list<T>, std::size_t); SlidingWindow(Container container, std::size_t win_sz) : container(std::forward<Container>(container)), window_size{win_sz} { } using DerefVec = std::deque<collection_item_type<Container>>; public: class Iterator : public std::iterator<std::input_iterator_tag, DerefVec> { private: iterator_type<Container> sub_iter; DerefVec window; public: Iterator(const iterator_type<Container>& in_iter, const iterator_type<Container>& in_end, std::size_t window_sz) : sub_iter(in_iter) { std::size_t i{0}; while (i < window_sz && this->sub_iter != in_end) { this->window.push_back(*this->sub_iter); ++i; if (i != window_sz) ++this->sub_iter; } } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } DerefVec& operator*() { return this->window; } Iterator& operator++() { ++this->sub_iter; this->window.pop_front(); this->window.push_back(*this->sub_iter); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } }; Iterator begin() { return { (this->window_size != 0 ? std::begin(this->container) : std::end(this->container)), std::end(this->container), this->window_size}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->window_size}; } }; template <typename Container> SlidingWindow<Container> sliding_window( Container&& container, std::size_t window_size) { return {std::forward<Container>(container), window_size}; } template <typename T> SlidingWindow<std::initializer_list<T>> sliding_window( std::initializer_list<T> il, std::size_t window_size) { return {il, window_size}; } } #endif <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <limits> using namespace std; int main() { string userInput; int trackNumber = 0; do { cout << "Pls enter track number: "; //getline (cin, userInput); cin >> trackNumber; if (cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); trackNumber = 0; continue; } cout << "You entered: " << trackNumber << endl; cin.ignore(); } while (trackNumber < 1 || trackNumber > 4); return 0; } <commit_msg>fixed stuff<commit_after>#include <iostream> #include <string> #include <limits> using namespace std; int main() { int trackNumber = 0; do { cout << "Pls enter track number: "; cin >> noskipws >> trackNumber; if (cin.fail()) { cout << "What a load of rubbish\n"; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); trackNumber = 0; continue; } cout << "You entered: " << trackNumber << endl; cin.ignore(); } while (trackNumber < 1 || trackNumber > 4); return 0; } <|endoftext|>
<commit_before>//===-- UriParser.cpp -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Utility/UriParser.h" #include <string> #include <stdint.h> #include <tuple> using namespace lldb_private; //---------------------------------------------------------------------- // UriParser::Parse //---------------------------------------------------------------------- bool UriParser::Parse(llvm::StringRef uri, llvm::StringRef &scheme, llvm::StringRef &hostname, int &port, llvm::StringRef &path) { llvm::StringRef tmp_scheme, tmp_hostname, tmp_port, tmp_path; const llvm::StringRef kSchemeSep("://"); auto pos = uri.find(kSchemeSep); if (pos == std::string::npos) return false; // Extract path. tmp_scheme = uri.substr(0, pos); auto host_pos = pos + kSchemeSep.size(); auto path_pos = uri.find('/', host_pos); if (path_pos != std::string::npos) tmp_path = uri.substr(path_pos); else tmp_path = "/"; auto host_port = uri.substr( host_pos, ((path_pos != std::string::npos) ? path_pos : uri.size()) - host_pos); // Extract hostname if (host_port[0] == '[') { // hostname is enclosed with square brackets. pos = host_port.find(']'); if (pos == std::string::npos) return false; tmp_hostname = host_port.substr(1, pos - 1); host_port = host_port.drop_front(pos + 1); if (!host_port.empty() && !host_port.consume_front(":")) return false; } else { std::tie(tmp_hostname, host_port) = host_port.split(':'); } // Extract port if (!host_port.empty()) { uint16_t port_value = 0; if (host_port.getAsInteger(0, port_value)) return false; port = port_value; } else port = -1; scheme = tmp_scheme; hostname = tmp_hostname; path = tmp_path; return true; } <commit_msg>Don't crash when hostname is empty. StringRef will assert and kill your program.<commit_after>//===-- UriParser.cpp -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Utility/UriParser.h" #include <string> #include <stdint.h> #include <tuple> using namespace lldb_private; //---------------------------------------------------------------------- // UriParser::Parse //---------------------------------------------------------------------- bool UriParser::Parse(llvm::StringRef uri, llvm::StringRef &scheme, llvm::StringRef &hostname, int &port, llvm::StringRef &path) { llvm::StringRef tmp_scheme, tmp_hostname, tmp_port, tmp_path; const llvm::StringRef kSchemeSep("://"); auto pos = uri.find(kSchemeSep); if (pos == std::string::npos) return false; // Extract path. tmp_scheme = uri.substr(0, pos); auto host_pos = pos + kSchemeSep.size(); auto path_pos = uri.find('/', host_pos); if (path_pos != std::string::npos) tmp_path = uri.substr(path_pos); else tmp_path = "/"; auto host_port = uri.substr( host_pos, ((path_pos != std::string::npos) ? path_pos : uri.size()) - host_pos); // Extract hostname if (!host_port.empty() && host_port[0] == '[') { // hostname is enclosed with square brackets. pos = host_port.find(']'); if (pos == std::string::npos) return false; tmp_hostname = host_port.substr(1, pos - 1); host_port = host_port.drop_front(pos + 1); if (!host_port.empty() && !host_port.consume_front(":")) return false; } else { std::tie(tmp_hostname, host_port) = host_port.split(':'); } // Extract port if (!host_port.empty()) { uint16_t port_value = 0; if (host_port.getAsInteger(0, port_value)) return false; port = port_value; } else port = -1; scheme = tmp_scheme; hostname = tmp_hostname; path = tmp_path; return true; } <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: threads.C,v 1.41.16.2 2007/05/10 20:15:09 amoll Exp $ // #include <BALL/VIEW/KERNEL/threads.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/KERNEL/message.h> #include <BALL/VIEW/KERNEL/representation.h> #include <BALL/VIEW/DIALOGS/FDPBDialog.h> #include <BALL/VIEW/DATATYPE/standardDatasets.h> #include <BALL/MOLMEC/COMMON/forceField.h> #include <BALL/MOLMEC/MINIMIZATION/energyMinimizer.h> #include <BALL/MOLMEC/MDSIMULATION/molecularDynamics.h> #include <BALL/MOLMEC/COMMON/snapShotManager.h> #include <BALL/STRUCTURE/DOCKING/dockingAlgorithm.h> #include <BALL/FORMAT/DCDFile.h> #include <QtGui/qapplication.h> namespace BALL { namespace VIEW { BALLThread::BALLThread() : QThread(), main_control_(0), composite_(0) { } void BALLThread::output_(const String& string, bool important) { LogEvent* su = new LogEvent; su->setMessage(string + String("\n")); su->setImportant(important); qApp->postEvent(main_control_, su); // Qt will delete it when done } void BALLThread::waitForUpdateOfRepresentations_() { RepresentationManager& pm = main_control_->getRepresentationManager(); while (!main_control_->stopedSimulation() && (pm.still_to_notify_ || pm.updateRunning())) { msleep(10); } } void BALLThread::updateStructure_() { RepresentationManager& pm = main_control_->getRepresentationManager(); pm.still_to_notify_ = true; // notify MainControl to update all Representations for the Composite sendMessage_(new CompositeMessage(*composite_, CompositeMessage::CHANGED_COMPOSITE, true)); } void BALLThread::sendMessage_(Message* msg) { // Qt will delete the MessageEvent when done qApp->postEvent(main_control_, new MessageEvent(msg)); } // ================================== FetchHTMLThread =============================== FetchHTMLThread::FetchHTMLThread() throw() : BALLThread(), file_name_("") { } void FetchHTMLThread::setURL(const String& url) throw() { url_ = url; } void FetchHTMLThread::run() { if (main_control_ == 0) return; if (url_ == "") { output_("Invalid Address " + url_ + " in " + String(__FILE__) + ":" + String(__LINE__), true); return; } if (main_control_ != 0) { tcp_.setProxy(main_control_->getProxy(), main_control_->getProxyPort()); } try { if (file_name_ != "") { File f(file_name_, std::ios::out); if (!f.isOpen()) { output_(String("Could not open file ") + file_name_ + " for output!"); return; } tcp_.set(f, url_); // dont move the transfer() call away from here! tcp_.transfer(); } else { char c; stream_.get(c); while (stream_.gcount() > 0) { stream_.get(c); } stream_.clear(); tcp_.set(stream_, url_); // dont move the transfer() call away from here! tcp_.transfer(); } } catch(...) { output_(String("Exception in ") + String(__FILE__) + ": " + String(__LINE__), true); } } // ========================================== UpdateRepresentationThread::UpdateRepresentationThread() throw() : BALLThread(), rep_(0) { setTerminationEnabled(true); } void UpdateRepresentationThread::run() { if (main_control_ == 0) return; RepresentationManager& pm = main_control_->getRepresentationManager(); Representation* rep = 0; while (!main_control_->isAboutToQuit()) { if (!main_control_->useMultithreading()) { msleep(50); continue; } rep = pm.popRepresentationToUpdate(); if (rep == 0) { msleep(10); continue; } rep->update_(); sendMessage_(new RepresentationMessage(*rep, RepresentationMessage::FINISHED_UPDATE)); } } // ========================================== SimulationThread::SimulationThread() : BALLThread(), steps_between_updates_(0), dcd_file_(0) { setTerminationEnabled(true); } void SimulationThread::exportSceneToPNG_() { if (main_control_->stopedSimulation()) return; sendMessage_(new SceneMessage(SceneMessage::EXPORT_PNG)); } void SimulationThread::finish_() { if (dcd_file_ != 0) { dcd_file_->close(); String filename = dcd_file_->getName(); delete dcd_file_; dcd_file_ = 0; // we will reopen the file to prevent problems when a user runs an other sim SnapShotManagerDataset* set = new SnapShotManagerDataset; set->setName(filename); set->setType(TrajectoryController::type); set->setComposite(getComposite()); SnapShotManager* manager = new SnapShotManager((System*)getComposite(), 0, new DCDFile(filename, std::ios::in)); set->setData(manager); sendMessage_(new DatasetMessage(set, DatasetMessage::ADD)); } sendMessage_(new FinishedSimulationMessage); } // ===================================================================== void EnergyMinimizerThread::run() { if (main_control_ == 0) return; try { if (minimizer_ == 0 || minimizer_->getForceField() == 0 || minimizer_->getForceField()->getSystem() == 0 || main_control_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } ForceField& ff = *minimizer_->getForceField(); bool ok = true; bool converged = false; // iterate until done and refresh the screen every "steps" iterations while (!main_control_->stopedSimulation() && minimizer_->getNumberOfIterations() < minimizer_->getMaxNumberOfIterations() && !converged && ok) { converged = minimizer_->minimize(steps_between_updates_, true); ok = !minimizer_->wasAborted(); updateStructure_(); waitForUpdateOfRepresentations_(); QString message; message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A", minimizer_->getNumberOfIterations(), ff.getEnergy(), ff.getRMSGradient()); output_(ascii(message)); } updateStructure_(); output_(ff.getResults()); output_("final RMS gradient : " + String(ff.getRMSGradient()) + " kJ/(mol A) after " + String(minimizer_->getNumberOfIterations()) + " iterations\n", true); if (converged) output_("converged!"); if (!ok) output_("aborted!"); if (minimizer_->getNumberOfIterations() == minimizer_->getMaxNumberOfIterations()) output_("max number of iterations reached!"); finish_(); if (!ok) { output_("Aborted minimization because convergence could not be reached. Try to restart the minimization.", true); return; } } catch(Exception::GeneralException e) { delete dcd_file_; dcd_file_ = 0; String txt = String("Exception was thrown during minimization: ") + __FILE__ + ": " + String(__LINE__) + " :\n" + e.getMessage(); output_(txt, true); finish_(); } } EnergyMinimizerThread::EnergyMinimizerThread() : SimulationThread(), minimizer_(0) { } EnergyMinimizerThread::~EnergyMinimizerThread() { if (minimizer_ != 0) { delete minimizer_; } } void EnergyMinimizerThread::setEnergyMinimizer(EnergyMinimizer* minimizer) { if (minimizer_ != 0) { delete minimizer_; } minimizer_ = minimizer; } // ===================================================== void MDSimulationThread::run() throw(Exception::NullPointer) { if (main_control_ == 0) return; try { if (md_ == 0 || md_->getForceField() == 0 || md_->getForceField()->getSystem() == 0 || main_control_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } ForceField& ff = *md_->getForceField(); SnapShotManager manager(ff.getSystem(), &ff, dcd_file_); manager.setFlushToDiskFrequency(10); bool ok = true; // iterate until done and refresh the screen every "steps" iterations while (ok && md_->getNumberOfIterations() < steps_ && !main_control_->stopedSimulation()) { ok = md_->simulateIterations(steps_between_updates_, true); updateStructure_(); waitForUpdateOfRepresentations_(); QString message; message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A", md_->getNumberOfIterations(), ff.getEnergy(), ff.getRMSGradient()); output_(ascii(message)); if (save_images_) exportSceneToPNG_(); if (dcd_file_) manager.takeSnapShot(); } if (dcd_file_) manager.flushToDisk(); output_(ff.getResults()); output_("final RMS gradient : " + String(ff.getRMSGradient()) + " kJ/(mol A) after " + String(md_->getNumberOfIterations()) + " iterations\n", true); if (!ok) { output_("Simulation aborted to to strange energy values.", true); } finish_(); } catch(Exception::GeneralException e) { String txt = String("Exception was thrown during MD simulation: ") + __FILE__ + ": " + String(__LINE__) + " \n" + e.getMessage(); output_(txt, true); if (dcd_file_ != 0) { dcd_file_->close(); delete dcd_file_; dcd_file_ = 0; } finish_(); } } MDSimulationThread::MDSimulationThread() : SimulationThread(), md_(0), save_images_(false) { } MDSimulationThread::~MDSimulationThread() { if (md_ != 0) delete md_; } void MDSimulationThread::setMolecularDynamics(MolecularDynamics* md) { if (md_ != 0) delete md_; md_ = md; } // =================================================0 CalculateFDPBThread::CalculateFDPBThread() throw() : BALLThread(), dialog_(0) {} void CalculateFDPBThread::run() { if (dialog_ == 0) return; dialog_->calculate_(); } // =========================== implementation of class DockingThread ================ /// DockingThread::DockingThread() throw() : BALLThread(), dock_alg_(0) {} // Copy constructor. DockingThread::DockingThread(const DockingThread& dock_thread) throw() : BALLThread(), dock_alg_(dock_thread.dock_alg_) {} /// DockingThread::~DockingThread() throw() { output_("delete thread", true); // docking algorithm is deleted in DockingController } // Assignment operator const DockingThread& DockingThread::operator =(const DockingThread& dock_thread) throw() { if (&dock_thread != this) { dock_alg_ = dock_thread.dock_alg_; } return *this; } // void DockingThread::setDockingAlgorithm(DockingAlgorithm* dock_alg) throw() { dock_alg_ = dock_alg; } /// void DockingThread::run() throw(Exception::NullPointer) { if (dock_alg_ == 0 || main_control_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } output_("starting docking...", true); dock_alg_->start(); DockingFinishedMessage* msg = new DockingFinishedMessage(dock_alg_->wasAborted()); // conformation set is deleted in DockResult msg->setConformationSet(new ConformationSet(dock_alg_->getConformationSet())); sendMessage_(msg); output_("Docking finished.", true); } // =================================================0 } // namespace VIEW } // namespace BALL <commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: threads.C,v 1.41.16.3 2007/05/28 13:35:28 amoll Exp $ // #include <BALL/VIEW/KERNEL/threads.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/KERNEL/message.h> #include <BALL/VIEW/KERNEL/representation.h> #include <BALL/VIEW/DIALOGS/FDPBDialog.h> #include <BALL/VIEW/DATATYPE/standardDatasets.h> #include <BALL/MOLMEC/COMMON/forceField.h> #include <BALL/MOLMEC/MINIMIZATION/energyMinimizer.h> #include <BALL/MOLMEC/MDSIMULATION/molecularDynamics.h> #include <BALL/MOLMEC/COMMON/snapShotManager.h> #include <BALL/STRUCTURE/DOCKING/dockingAlgorithm.h> #include <BALL/FORMAT/DCDFile.h> #include <QtGui/qapplication.h> namespace BALL { namespace VIEW { BALLThread::BALLThread() : QThread(), main_control_(0), composite_(0) { } void BALLThread::output_(const String& string, bool important) { LogEvent* su = new LogEvent; su->setMessage(string + String("\n")); su->setImportant(important); qApp->postEvent(main_control_, su); // Qt will delete it when done } void BALLThread::waitForUpdateOfRepresentations_() { RepresentationManager& pm = main_control_->getRepresentationManager(); while (!main_control_->stopedSimulation() && (pm.still_to_notify_ || pm.updateRunning())) { msleep(10); } } void BALLThread::updateStructure_() { RepresentationManager& pm = main_control_->getRepresentationManager(); pm.still_to_notify_ = true; // notify MainControl to update all Representations for the Composite sendMessage_(new CompositeMessage(*composite_, CompositeMessage::CHANGED_COMPOSITE, true)); } void BALLThread::sendMessage_(Message* msg) { if (main_control_ == 0) return; // Qt will delete the MessageEvent when done qApp->postEvent(main_control_, new MessageEvent(msg)); } // ================================== FetchHTMLThread =============================== FetchHTMLThread::FetchHTMLThread() throw() : BALLThread(), file_name_("") { } void FetchHTMLThread::setURL(const String& url) throw() { url_ = url; } void FetchHTMLThread::run() { if (main_control_ == 0) return; if (url_ == "") { output_("Invalid Address " + url_ + " in " + String(__FILE__) + ":" + String(__LINE__), true); return; } if (main_control_ != 0) { tcp_.setProxy(main_control_->getProxy(), main_control_->getProxyPort()); } try { if (file_name_ != "") { File f(file_name_, std::ios::out); if (!f.isOpen()) { output_(String("Could not open file ") + file_name_ + " for output!"); return; } tcp_.set(f, url_); // dont move the transfer() call away from here! tcp_.transfer(); } else { char c; stream_.get(c); while (stream_.gcount() > 0) { stream_.get(c); } stream_.clear(); tcp_.set(stream_, url_); // dont move the transfer() call away from here! tcp_.transfer(); } } catch(...) { output_(String("Exception in ") + String(__FILE__) + ": " + String(__LINE__), true); } } // ========================================== UpdateRepresentationThread::UpdateRepresentationThread() throw() : BALLThread(), rep_(0) { setTerminationEnabled(true); } void UpdateRepresentationThread::run() { if (main_control_ == 0) return; RepresentationManager& pm = main_control_->getRepresentationManager(); Representation* rep = 0; while (!main_control_->isAboutToQuit()) { if (!main_control_->useMultithreading()) { msleep(50); continue; } rep = pm.popRepresentationToUpdate(); if (rep == 0) { msleep(10); continue; } rep->update_(); sendMessage_(new RepresentationMessage(*rep, RepresentationMessage::FINISHED_UPDATE)); } } // ========================================== SimulationThread::SimulationThread() : BALLThread(), steps_between_updates_(0), dcd_file_(0) { setTerminationEnabled(true); } void SimulationThread::exportSceneToPNG_() { if (main_control_->stopedSimulation()) return; sendMessage_(new SceneMessage(SceneMessage::EXPORT_PNG)); } void SimulationThread::finish_() { if (dcd_file_ != 0) { dcd_file_->close(); String filename = dcd_file_->getName(); delete dcd_file_; dcd_file_ = 0; // we will reopen the file to prevent problems when a user runs an other sim SnapShotManagerDataset* set = new SnapShotManagerDataset; set->setName(filename); set->setType(TrajectoryController::type); set->setComposite(getComposite()); SnapShotManager* manager = new SnapShotManager((System*)getComposite(), 0, new DCDFile(filename, std::ios::in)); set->setData(manager); sendMessage_(new DatasetMessage(set, DatasetMessage::ADD)); } sendMessage_(new FinishedSimulationMessage); } // ===================================================================== void EnergyMinimizerThread::run() { if (main_control_ == 0) return; try { if (minimizer_ == 0 || minimizer_->getForceField() == 0 || minimizer_->getForceField()->getSystem() == 0 || main_control_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } ForceField& ff = *minimizer_->getForceField(); bool ok = true; bool converged = false; // iterate until done and refresh the screen every "steps" iterations while (!main_control_->stopedSimulation() && minimizer_->getNumberOfIterations() < minimizer_->getMaxNumberOfIterations() && !converged && ok) { converged = minimizer_->minimize(steps_between_updates_, true); ok = !minimizer_->wasAborted(); updateStructure_(); waitForUpdateOfRepresentations_(); QString message; message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A", minimizer_->getNumberOfIterations(), ff.getEnergy(), ff.getRMSGradient()); output_(ascii(message)); } updateStructure_(); output_(ff.getResults()); output_("final RMS gradient : " + String(ff.getRMSGradient()) + " kJ/(mol A) after " + String(minimizer_->getNumberOfIterations()) + " iterations\n", true); if (converged) output_("converged!"); if (!ok) output_("aborted!"); if (minimizer_->getNumberOfIterations() == minimizer_->getMaxNumberOfIterations()) output_("max number of iterations reached!"); finish_(); if (!ok) { output_("Aborted minimization because convergence could not be reached. Try to restart the minimization.", true); return; } } catch(Exception::GeneralException e) { delete dcd_file_; dcd_file_ = 0; String txt = String("Exception was thrown during minimization: ") + __FILE__ + ": " + String(__LINE__) + " :\n" + e.getMessage(); output_(txt, true); finish_(); } } EnergyMinimizerThread::EnergyMinimizerThread() : SimulationThread(), minimizer_(0) { } EnergyMinimizerThread::~EnergyMinimizerThread() { if (minimizer_ != 0) { delete minimizer_; } } void EnergyMinimizerThread::setEnergyMinimizer(EnergyMinimizer* minimizer) { if (minimizer_ != 0) { delete minimizer_; } minimizer_ = minimizer; } // ===================================================== void MDSimulationThread::run() throw(Exception::NullPointer) { if (main_control_ == 0) return; try { if (md_ == 0 || md_->getForceField() == 0 || md_->getForceField()->getSystem() == 0 || main_control_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } ForceField& ff = *md_->getForceField(); SnapShotManager manager(ff.getSystem(), &ff, dcd_file_); manager.setFlushToDiskFrequency(10); bool ok = true; // iterate until done and refresh the screen every "steps" iterations while (ok && md_->getNumberOfIterations() < steps_ && !main_control_->stopedSimulation()) { ok = md_->simulateIterations(steps_between_updates_, true); updateStructure_(); waitForUpdateOfRepresentations_(); QString message; message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A", md_->getNumberOfIterations(), ff.getEnergy(), ff.getRMSGradient()); output_(ascii(message)); if (save_images_) exportSceneToPNG_(); if (dcd_file_) manager.takeSnapShot(); } if (dcd_file_) manager.flushToDisk(); output_(ff.getResults()); output_("final RMS gradient : " + String(ff.getRMSGradient()) + " kJ/(mol A) after " + String(md_->getNumberOfIterations()) + " iterations\n", true); if (!ok) { output_("Simulation aborted to to strange energy values.", true); } finish_(); } catch(Exception::GeneralException e) { String txt = String("Exception was thrown during MD simulation: ") + __FILE__ + ": " + String(__LINE__) + " \n" + e.getMessage(); output_(txt, true); if (dcd_file_ != 0) { dcd_file_->close(); delete dcd_file_; dcd_file_ = 0; } finish_(); } } MDSimulationThread::MDSimulationThread() : SimulationThread(), md_(0), save_images_(false) { } MDSimulationThread::~MDSimulationThread() { if (md_ != 0) delete md_; } void MDSimulationThread::setMolecularDynamics(MolecularDynamics* md) { if (md_ != 0) delete md_; md_ = md; } // =================================================0 CalculateFDPBThread::CalculateFDPBThread() throw() : BALLThread(), dialog_(0) {} void CalculateFDPBThread::run() { if (dialog_ == 0) return; dialog_->calculate_(); } // =========================== implementation of class DockingThread ================ /// DockingThread::DockingThread() throw() : BALLThread(), dock_alg_(0) {} // Copy constructor. DockingThread::DockingThread(const DockingThread& dock_thread) throw() : BALLThread(), dock_alg_(dock_thread.dock_alg_) {} /// DockingThread::~DockingThread() throw() { output_("delete thread", true); // docking algorithm is deleted in DockingController } // Assignment operator const DockingThread& DockingThread::operator =(const DockingThread& dock_thread) throw() { if (&dock_thread != this) { dock_alg_ = dock_thread.dock_alg_; } return *this; } // void DockingThread::setDockingAlgorithm(DockingAlgorithm* dock_alg) throw() { dock_alg_ = dock_alg; } /// void DockingThread::run() throw(Exception::NullPointer) { if (dock_alg_ == 0 || main_control_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } output_("starting docking...", true); dock_alg_->start(); DockingFinishedMessage* msg = new DockingFinishedMessage(dock_alg_->wasAborted()); // conformation set is deleted in DockResult msg->setConformationSet(new ConformationSet(dock_alg_->getConformationSet())); sendMessage_(msg); output_("Docking finished.", true); } // =================================================0 } // namespace VIEW } // namespace BALL <|endoftext|>
<commit_before>// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2011, Knut Reinert, FU Berlin // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Enrico Siragusa <[email protected]> // ========================================================================== // This file contains the masai_mapper application. // ========================================================================== #include <seqan/basic.h> #include <seqan/sequence.h> #include "options.h" #include "mapper.h" using namespace seqan; // ============================================================================ // Tags, Classes, Enums // ============================================================================ // ---------------------------------------------------------------------------- // Class Options // ---------------------------------------------------------------------------- struct Options : public MasaiOptions { CharString genomeFile; CharString genomeIndexFile; IndexType genomeIndexType; CharString readsFile; CharString mappedReadsFile; OutputFormat outputFormat; bool outputCigar; MappingMode mappingMode; unsigned errorsPerRead; unsigned errorsLossy; unsigned seedLength; bool mismatchesOnly; bool verifyHits; bool dumpResults; bool multipleBacktracking; Options() : MasaiOptions(), genomeIndexType(INDEX_SA), outputFormat(RAW), outputCigar(true), mappingMode(ANY_BEST), errorsPerRead(5), errorsLossy(0), seedLength(33), mismatchesOnly(false), verifyHits(true), dumpResults(true), multipleBacktracking(true) {} }; // ============================================================================ void setupArgumentParser(ArgumentParser & parser, Options const & options) { setAppName(parser, "masai_mapper"); setShortDescription(parser, "Masai Mapper"); setCategory(parser, "Read Mapping"); setDateAndVersion(parser); setDescription(parser); addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIGENOME FILE\\fP> <\\fIREADS FILE\\fP>"); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE)); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE)); setValidValues(parser, 0, "fasta"); setValidValues(parser, 1, "fastq"); addSection(parser, "Mapping Options"); addOption(parser, ArgParseOption("mm", "mapping-mode", "Select mapping mode.", ArgParseOption::STRING)); setValidValues(parser, "mapping-mode", options.mappingModeList); setDefaultValue(parser, "mapping-mode", options.mappingModeList[options.mappingMode]); addOption(parser, ArgParseOption("e", "errors", "Maximum number of errors per read.", ArgParseOption::INTEGER)); setMinValue(parser, "errors", "0"); setMaxValue(parser, "errors", "32"); setDefaultValue(parser, "errors", options.errorsPerRead); // addOption(parser, ArgParseOption("el", "errors-lossy", // "Maximum number of errors per read to report. For any-best mode only.", // ArgParseOption::INTEGER)); // setMinValue(parser, "errors-lossy", "0"); // setMaxValue(parser, "errors-lossy", "32"); // setDefaultValue(parser, "errors-lossy", options.errorsLossy); addOption(parser, ArgParseOption("sl", "seed-length", "Minimum seed length.", ArgParseOption::INTEGER)); setMinValue(parser, "seed-length", "10"); setMaxValue(parser, "seed-length", "100"); setDefaultValue(parser, "seed-length", options.seedLength); addOption(parser, ArgParseOption("ng", "no-gaps", "Do not align reads with gaps.")); addSection(parser, "Genome Index Options"); setIndexType(parser, options); setIndexPrefix(parser); addSection(parser, "Output Options"); setOutputFile(parser); setOutputFormat(parser, options); addSection(parser, "Debug Options"); addOption(parser, ArgParseOption("nv", "no-verify", "Do not verify seed hits.")); addOption(parser, ArgParseOption("nd", "no-dump", "Do not dump results.")); addOption(parser, ArgParseOption("nm", "no-multiple", "Disable multiple backtracking.")); } ArgumentParser::ParseResult parseCommandLine(Options & options, ArgumentParser & parser, int argc, char const ** argv) { ArgumentParser::ParseResult res = parse(parser, argc, argv); if (res != seqan::ArgumentParser::PARSE_OK) return res; // Parse genome input file. getArgumentValue(options.genomeFile, parser, 0); // Parse reads input file. getArgumentValue(options.readsFile, parser, 1); // Parse mapping mode. getOptionValue(options.mappingMode, parser, "mapping-mode", options.mappingModeList); // Parse mapping options. getOptionValue(options.errorsPerRead, parser, "errors"); // getOptionValue(options.errorsLossy, parser, "errors-lossy"); options.errorsLossy = std::max(options.errorsLossy, options.errorsPerRead); getOptionValue(options.seedLength, parser, "seed-length"); options.mismatchesOnly = isSet(parser, "no-gaps"); // Parse genome index prefix. getIndexPrefix(options, parser); // Parse genome index type. getIndexType(options, parser); // Parse output format. getOutputFormat(options, parser); // Parse output format. getOutputFormat(options, parser); // Parse output file. getOutputFile(options.mappedReadsFile, options, parser, options.readsFile, ""); // Parse debug options. options.verifyHits = !isSet(parser, "no-verify"); options.dumpResults = !isSet(parser, "no-dump"); options.multipleBacktracking = !isSet(parser, "no-multiple"); return seqan::ArgumentParser::PARSE_OK; } // ============================================================================ template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking, typename TIndex> int runMapper(Options & options) { // TODO(esiragusa): Use typename TGenomeIndex instead of TSpec. typedef Mapper<TIndex> TMapper; // TODO(esiragusa): Remove writeCigar from Mapper members. TMapper mapper(options.seedLength, options.outputCigar, options.verifyHits, options.dumpResults); double start, finish; // Loading genome. std::cout << "Loading genome:\t\t\t" << std::flush; start = sysTime(); if (!loadGenome(mapper.indexer, options.genomeFile)) { std::cerr << "Error while loading genome" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; // std::cout << "Contigs count:\t\t\t" << mapper.indexer.contigsCount << std::endl; // Loading genome index. std::cout << "Loading genome index:\t\t" << std::flush; start = sysTime(); if (!loadGenomeIndex(mapper.indexer, options.genomeIndexFile)) { std::cout << "Error while loading genome index" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; // Loading reads. std::cout << "Loading reads:\t\t\t" << std::flush; start = sysTime(); if (!loadReads(mapper, options.readsFile, TFormat())) { std::cerr << "Error while loading reads" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; std::cout << "Reads count:\t\t\t" << mapper.readsCount << std::endl; // Mapping reads. start = sysTime(); if (!mapReads(mapper, options.mappedReadsFile, options.errorsPerRead, options.errorsLossy, TDistance(), TStrategy(), TBacktracking(), TFormat())) { std::cerr << "Error while writing results" << std::endl; return 1; } finish = sysTime(); std::cout << "Mapping time:\t\t\t" << std::flush; std::cout << finish - start << " sec" << std::endl; return 0; } // ============================================================================ template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking> int configureGenomeIndex(Options & options) { switch (options.genomeIndexType) { case Options::INDEX_ESA: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeEsa>(options); case Options::INDEX_SA: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeSa>(options); case Options::INDEX_QGRAM: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeQGram>(options); case Options::INDEX_FM: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeFM>(options); default: return 1; } } template <typename TStrategy, typename TDistance, typename TFormat> int configureBacktracking(Options & options) { if (options.multipleBacktracking) return configureGenomeIndex<TStrategy, TDistance, TFormat, MultipleBacktracking>(options); else return configureGenomeIndex<TStrategy, TDistance, TFormat, SingleBacktracking>(options); } template <typename TStrategy, typename TDistance> int configureOutputFormat(Options & options) { switch (options.outputFormat) { case Options::RAW: return configureBacktracking<TStrategy, TDistance, Raw>(options); case Options::SAM: return configureBacktracking<TStrategy, TDistance, Sam>(options); case Options::SAM_NO_CIGAR: options.outputCigar = false; return configureBacktracking<TStrategy, TDistance, Sam>(options); default: return 1; } } template <typename TStrategy> int configureDistance(Options & options) { if (options.mismatchesOnly) return configureOutputFormat<TStrategy, HammingDistance>(options); else return configureOutputFormat<TStrategy, EditDistance>(options); } int mainWithOptions(Options & options) { switch (options.mappingMode) { case Options::ANY_BEST: return configureDistance<AnyBest>(options); case Options::ALL_BEST: return configureDistance<AllBest>(options); case Options::ALL: return configureDistance<All>(options); default: return 1; } } int main(int argc, char const ** argv) { ArgumentParser parser; Options options; setupArgumentParser(parser, options); ArgumentParser::ParseResult res = parseCommandLine(options, parser, argc, argv); if (res == seqan::ArgumentParser::PARSE_OK) return mainWithOptions(options); else return res; } <commit_msg>[CLI] masai: disabling qgram index option again :|<commit_after>// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2011, Knut Reinert, FU Berlin // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Enrico Siragusa <[email protected]> // ========================================================================== // This file contains the masai_mapper application. // ========================================================================== #include <seqan/basic.h> #include <seqan/sequence.h> #include "options.h" #include "mapper.h" using namespace seqan; // ============================================================================ // Tags, Classes, Enums // ============================================================================ // ---------------------------------------------------------------------------- // Class Options // ---------------------------------------------------------------------------- struct Options : public MasaiOptions { CharString genomeFile; CharString genomeIndexFile; IndexType genomeIndexType; CharString readsFile; CharString mappedReadsFile; OutputFormat outputFormat; bool outputCigar; MappingMode mappingMode; unsigned errorsPerRead; unsigned errorsLossy; unsigned seedLength; bool mismatchesOnly; bool verifyHits; bool dumpResults; bool multipleBacktracking; Options() : MasaiOptions(), genomeIndexType(INDEX_SA), outputFormat(RAW), outputCigar(true), mappingMode(ANY_BEST), errorsPerRead(5), errorsLossy(0), seedLength(33), mismatchesOnly(false), verifyHits(true), dumpResults(true), multipleBacktracking(true) {} }; // ============================================================================ void setupArgumentParser(ArgumentParser & parser, Options const & options) { setAppName(parser, "masai_mapper"); setShortDescription(parser, "Masai Mapper"); setCategory(parser, "Read Mapping"); setDateAndVersion(parser); setDescription(parser); addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIGENOME FILE\\fP> <\\fIREADS FILE\\fP>"); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE)); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE)); setValidValues(parser, 0, "fasta"); setValidValues(parser, 1, "fastq"); addSection(parser, "Mapping Options"); addOption(parser, ArgParseOption("mm", "mapping-mode", "Select mapping mode.", ArgParseOption::STRING)); setValidValues(parser, "mapping-mode", options.mappingModeList); setDefaultValue(parser, "mapping-mode", options.mappingModeList[options.mappingMode]); addOption(parser, ArgParseOption("e", "errors", "Maximum number of errors per read.", ArgParseOption::INTEGER)); setMinValue(parser, "errors", "0"); setMaxValue(parser, "errors", "32"); setDefaultValue(parser, "errors", options.errorsPerRead); // addOption(parser, ArgParseOption("el", "errors-lossy", // "Maximum number of errors per read to report. For any-best mode only.", // ArgParseOption::INTEGER)); // setMinValue(parser, "errors-lossy", "0"); // setMaxValue(parser, "errors-lossy", "32"); // setDefaultValue(parser, "errors-lossy", options.errorsLossy); addOption(parser, ArgParseOption("sl", "seed-length", "Minimum seed length.", ArgParseOption::INTEGER)); setMinValue(parser, "seed-length", "10"); setMaxValue(parser, "seed-length", "100"); setDefaultValue(parser, "seed-length", options.seedLength); addOption(parser, ArgParseOption("ng", "no-gaps", "Do not align reads with gaps.")); addSection(parser, "Genome Index Options"); setIndexType(parser, options); setIndexPrefix(parser); addSection(parser, "Output Options"); setOutputFile(parser); setOutputFormat(parser, options); addSection(parser, "Debug Options"); addOption(parser, ArgParseOption("nv", "no-verify", "Do not verify seed hits.")); addOption(parser, ArgParseOption("nd", "no-dump", "Do not dump results.")); addOption(parser, ArgParseOption("nm", "no-multiple", "Disable multiple backtracking.")); } ArgumentParser::ParseResult parseCommandLine(Options & options, ArgumentParser & parser, int argc, char const ** argv) { ArgumentParser::ParseResult res = parse(parser, argc, argv); if (res != seqan::ArgumentParser::PARSE_OK) return res; // Parse genome input file. getArgumentValue(options.genomeFile, parser, 0); // Parse reads input file. getArgumentValue(options.readsFile, parser, 1); // Parse mapping mode. getOptionValue(options.mappingMode, parser, "mapping-mode", options.mappingModeList); // Parse mapping options. getOptionValue(options.errorsPerRead, parser, "errors"); // getOptionValue(options.errorsLossy, parser, "errors-lossy"); options.errorsLossy = std::max(options.errorsLossy, options.errorsPerRead); getOptionValue(options.seedLength, parser, "seed-length"); options.mismatchesOnly = isSet(parser, "no-gaps"); // Parse genome index prefix. getIndexPrefix(options, parser); // Parse genome index type. getIndexType(options, parser); // Parse output format. getOutputFormat(options, parser); // Parse output format. getOutputFormat(options, parser); // Parse output file. getOutputFile(options.mappedReadsFile, options, parser, options.readsFile, ""); // Parse debug options. options.verifyHits = !isSet(parser, "no-verify"); options.dumpResults = !isSet(parser, "no-dump"); options.multipleBacktracking = !isSet(parser, "no-multiple"); return seqan::ArgumentParser::PARSE_OK; } // ============================================================================ template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking, typename TIndex> int runMapper(Options & options) { // TODO(esiragusa): Use typename TGenomeIndex instead of TSpec. typedef Mapper<TIndex> TMapper; // TODO(esiragusa): Remove writeCigar from Mapper members. TMapper mapper(options.seedLength, options.outputCigar, options.verifyHits, options.dumpResults); double start, finish; // Loading genome. std::cout << "Loading genome:\t\t\t" << std::flush; start = sysTime(); if (!loadGenome(mapper.indexer, options.genomeFile)) { std::cerr << "Error while loading genome" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; // std::cout << "Contigs count:\t\t\t" << mapper.indexer.contigsCount << std::endl; // Loading genome index. std::cout << "Loading genome index:\t\t" << std::flush; start = sysTime(); if (!loadGenomeIndex(mapper.indexer, options.genomeIndexFile)) { std::cout << "Error while loading genome index" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; // Loading reads. std::cout << "Loading reads:\t\t\t" << std::flush; start = sysTime(); if (!loadReads(mapper, options.readsFile, TFormat())) { std::cerr << "Error while loading reads" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; std::cout << "Reads count:\t\t\t" << mapper.readsCount << std::endl; // Mapping reads. start = sysTime(); if (!mapReads(mapper, options.mappedReadsFile, options.errorsPerRead, options.errorsLossy, TDistance(), TStrategy(), TBacktracking(), TFormat())) { std::cerr << "Error while writing results" << std::endl; return 1; } finish = sysTime(); std::cout << "Mapping time:\t\t\t" << std::flush; std::cout << finish - start << " sec" << std::endl; return 0; } // ============================================================================ template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking> int configureGenomeIndex(Options & options) { switch (options.genomeIndexType) { case Options::INDEX_ESA: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeEsa>(options); case Options::INDEX_SA: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeSa>(options); // case Options::INDEX_QGRAM: // return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeQGram>(options); case Options::INDEX_FM: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeFM>(options); default: return 1; } } template <typename TStrategy, typename TDistance, typename TFormat> int configureBacktracking(Options & options) { if (options.multipleBacktracking) return configureGenomeIndex<TStrategy, TDistance, TFormat, MultipleBacktracking>(options); else return configureGenomeIndex<TStrategy, TDistance, TFormat, SingleBacktracking>(options); } template <typename TStrategy, typename TDistance> int configureOutputFormat(Options & options) { switch (options.outputFormat) { case Options::RAW: return configureBacktracking<TStrategy, TDistance, Raw>(options); case Options::SAM: return configureBacktracking<TStrategy, TDistance, Sam>(options); case Options::SAM_NO_CIGAR: options.outputCigar = false; return configureBacktracking<TStrategy, TDistance, Sam>(options); default: return 1; } } template <typename TStrategy> int configureDistance(Options & options) { if (options.mismatchesOnly) return configureOutputFormat<TStrategy, HammingDistance>(options); else return configureOutputFormat<TStrategy, EditDistance>(options); } int mainWithOptions(Options & options) { switch (options.mappingMode) { case Options::ANY_BEST: return configureDistance<AnyBest>(options); case Options::ALL_BEST: return configureDistance<AllBest>(options); case Options::ALL: return configureDistance<All>(options); default: return 1; } } int main(int argc, char const ** argv) { ArgumentParser parser; Options options; setupArgumentParser(parser, options); ArgumentParser::ParseResult res = parseCommandLine(options, parser, argc, argv); if (res == seqan::ArgumentParser::PARSE_OK) return mainWithOptions(options); else return res; } <|endoftext|>
<commit_before>#pragma once #include <port.hpp> template <class USI_t, class CSn> class CC1101 { public: typedef USI_t USI; enum ConfReg { IOCFG2 = 0x00, IOCFG1 = 0x01, IOCFG0 = 0x02, FIFOTHR = 0x03, SYNC1 = 0x04, SYNC0 = 0x05, PKTLEN = 0x06, PKTCTRL1 = 0x07, PKTCTRL0 = 0x08, ADDR = 0x09, CHANNR = 0x0A, FSCTRL1 = 0x0B, FSCTRL0 = 0x0C, FREQ2 = 0x0D, FREQ1 = 0x0E, FREQ0 = 0x0F, MDMCFG4 = 0x10, MDMCFG3 = 0x11, MDMCFG2 = 0x12, MDMCFG1 = 0x13, MDMCFG0 = 0x14, DEVIATN = 0x15, MCSM2 = 0x16, MCSM1 = 0x17, MCSM0 = 0x18, FOCCFG = 0x19, BSCFG = 0x1A, AGCCTRL2 = 0x1B, AGCCTRL1 = 0x1C, AGCCTRL0 = 0x1D, WOREVT1 = 0x1E, WOREVT0 = 0x1F, WORCTRL = 0x20, FREND1 = 0x21, FREND0 = 0x22, FSCAL3 = 0x23, FSCAL2 = 0x24, FSCAL1 = 0x25, FSCAL0 = 0x26, RCCTRL1 = 0x27, RCCTRL0 = 0x28, FSTEST = 0x29, PTEST = 0x2A, AGCTEST = 0x2B, TEST2 = 0x2C, TEST1 = 0x2D, TEST0 = 0x2E, PATABLE = 0x3E, }; enum CommandStrobe { SRES = 0x30, SFSTXON = 0x31, SXOFF = 0x32, SCAL = 0x33, SRX = 0x34, STX = 0x35, SIDLE = 0x36, SWOR = 0x38, SPWD = 0x39, SFRX = 0x3A, SFTX = 0x3B, SWORRST = 0x3C, SNOP = 0x3D, }; enum StatusReg { PARTNUM = 0x30, VERSION = 0x31, FREQEST = 0x32, LQI = 0x33, RSSI = 0x34, MARCSTATE = 0x35, WORTIME1 = 0x36, WORTIME0 = 0x37, PKTSTATUS = 0x38, VCO_VC_DAC = 0x39, TXBYTES = 0x3A, RXBYTES = 0x3B, RCCTRL1_STATUS = 0x3C, RCCTRL0_STATUS = 0x3D, }; static void setup() { USI::setup(); CSn::mode(OUTPUT); CSn::set(); } template <ConfReg Reg> static void set(unsigned char value) { USI::xmit(Reg); USI::xmit(value); } template <ConfReg Reg> static unsigned char get() { USI::xmit(Reg | 0x80); return USI::xmit(0); } template <CommandStrobe Cmd> static unsigned char rcmd() { return USI::xmit(Cmd | 0x80); } template <CommandStrobe Cmd> static unsigned char wcmd() { return USI::xmit(Cmd); } template <StatusReg Reg> static unsigned char status() { USI::xmit(Reg | 0xc0); return USI::xmit(0); } static bool select() { CSn::clear(); return USI::DI::loop_until_clear(200); } static void release() { CSn::set(); } static void write_txfifo(unsigned char* values, int len) { USI::xmit(0x7f); while(len-- > 0) { USI::xmit(*values++); } release(); } static void read_rxfifo(unsigned char* values, int len) { USI::xmit(0xff); while(len-- > 0) { *values++ = USI::xmit(0); } release(); } static void reset() { // reset select(); wcmd<SRES>(); release(); select(); // disable GDOx pins set<IOCFG2>(0x2f); set<IOCFG1>(0x2f); set<IOCFG0>(0x2f); // max packet length set<PKTLEN>(32); // packet automation set<PKTCTRL1>(0x0c); set<PKTCTRL0>(0x45); // frequency configuration set<FREQ2>(0x10); set<FREQ1>(0xa7); set<FREQ0>(0x63); // modem configuration set<MDMCFG2>(0x1e); // main radio control state machine configuration set<MCSM1>(0x3c); set<MCSM0>(0x34); // AGC control set<AGCCTRL1>(0x60); // patable set<PATABLE>(0xc0); wcmd<SCAL>(); release(); } }; <commit_msg>cc1101: variables applied from rf studio<commit_after>#pragma once #include <port.hpp> template <class USI_t, class CSn> class CC1101 { public: typedef USI_t USI; enum ConfReg { IOCFG2 = 0x00, IOCFG1 = 0x01, IOCFG0 = 0x02, FIFOTHR = 0x03, SYNC1 = 0x04, SYNC0 = 0x05, PKTLEN = 0x06, PKTCTRL1 = 0x07, PKTCTRL0 = 0x08, ADDR = 0x09, CHANNR = 0x0A, FSCTRL1 = 0x0B, FSCTRL0 = 0x0C, FREQ2 = 0x0D, FREQ1 = 0x0E, FREQ0 = 0x0F, MDMCFG4 = 0x10, MDMCFG3 = 0x11, MDMCFG2 = 0x12, MDMCFG1 = 0x13, MDMCFG0 = 0x14, DEVIATN = 0x15, MCSM2 = 0x16, MCSM1 = 0x17, MCSM0 = 0x18, FOCCFG = 0x19, BSCFG = 0x1A, AGCCTRL2 = 0x1B, AGCCTRL1 = 0x1C, AGCCTRL0 = 0x1D, WOREVT1 = 0x1E, WOREVT0 = 0x1F, WORCTRL = 0x20, FREND1 = 0x21, FREND0 = 0x22, FSCAL3 = 0x23, FSCAL2 = 0x24, FSCAL1 = 0x25, FSCAL0 = 0x26, RCCTRL1 = 0x27, RCCTRL0 = 0x28, FSTEST = 0x29, PTEST = 0x2A, AGCTEST = 0x2B, TEST2 = 0x2C, TEST1 = 0x2D, TEST0 = 0x2E, PATABLE = 0x3E, }; enum CommandStrobe { SRES = 0x30, SFSTXON = 0x31, SXOFF = 0x32, SCAL = 0x33, SRX = 0x34, STX = 0x35, SIDLE = 0x36, SWOR = 0x38, SPWD = 0x39, SFRX = 0x3A, SFTX = 0x3B, SWORRST = 0x3C, SNOP = 0x3D, }; enum StatusReg { PARTNUM = 0x30, VERSION = 0x31, FREQEST = 0x32, LQI = 0x33, RSSI = 0x34, MARCSTATE = 0x35, WORTIME1 = 0x36, WORTIME0 = 0x37, PKTSTATUS = 0x38, VCO_VC_DAC = 0x39, TXBYTES = 0x3A, RXBYTES = 0x3B, RCCTRL1_STATUS = 0x3C, RCCTRL0_STATUS = 0x3D, }; static void setup() { USI::setup(); CSn::mode(OUTPUT); CSn::set(); } template <ConfReg Reg> static void set(unsigned char value) { USI::xmit(Reg); USI::xmit(value); } template <ConfReg Reg> static unsigned char get() { USI::xmit(Reg | 0x80); return USI::xmit(0); } template <CommandStrobe Cmd> static unsigned char rcmd() { return USI::xmit(Cmd | 0x80); } template <CommandStrobe Cmd> static unsigned char wcmd() { return USI::xmit(Cmd); } template <StatusReg Reg> static unsigned char status() { USI::xmit(Reg | 0xc0); return USI::xmit(0); } static bool select() { CSn::clear(); return USI::DI::loop_until_clear(200); } static void release() { CSn::set(); } static void write_txfifo(unsigned char* values, int len) { USI::xmit(0x7f); while(len-- > 0) { USI::xmit(*values++); } release(); } static void read_rxfifo(unsigned char* values, int len) { USI::xmit(0xff); while(len-- > 0) { *values++ = USI::xmit(0); } release(); } static void reset() { // reset select(); wcmd<SRES>(); release(); select(); // disable GDOx pins set<IOCFG2>(0x2f); set<IOCFG1>(0x2f); set<IOCFG0>(0x2f); // max packet length set<PKTLEN>(32); // packet automation set<PKTCTRL1>(0x0c); set<PKTCTRL0>(0x45); // frequency configuration set<FREQ2>(0x10); set<FREQ1>(0xa7); set<FREQ0>(0x63); // modem configuration set<MDMCFG2>(0x1a); // main radio control state machine configuration set<MCSM1>(0x3c); set<MCSM0>(0x34); // frequency synthesizer calibration set<FSCAL3>(0xea); set<FSCAL2>(0x2a); set<FSCAL1>(0x00); set<FSCAL0>(0x1f); // Various test settings set<TEST2>(0x81); set<TEST1>(0x35); set<TEST0>(0x09); wcmd<SCAL>(); release(); } }; <|endoftext|>
<commit_before>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2008 Steven Noonan. * Licensed under the New BSD License. * */ #ifndef __included_cc_darray_h #error "This file shouldn't be compiled directly." #endif #include <crisscross/debug.h> #include <crisscross/darray.h> #include <crisscross/dstack.h> namespace CrissCross { namespace Data { template <class T> DArray <T>::DArray() { m_stepSize = -1; m_numUsed = m_arraySize = 0; m_shadow = NULL; m_array = NULL; m_emptyNodes = new DStack<size_t>; m_emptyNodes->push((size_t)-1); m_encapsulated = true; } template <class T> DArray <T>::DArray(T *_array, size_t _indices, bool _encapsulate) { m_encapsulated = _encapsulate; if ( _encapsulate ) { m_array = new T[_indices]; memcpy(m_array, _array, _indices * sizeof(T)); } else { m_array = _array; } m_shadow = new char[_indices]; memset(m_shadow, 0, _indices * sizeof(char)); m_numUsed = 0; for (size_t i = 0; i < _indices; i++) { m_shadow[i] = m_array[i] != NULL ? 1 : 0; if ( m_shadow[i] ) { m_numUsed++; } } m_numUsed = m_numUsed; m_arraySize = _indices; m_stepSize = -1; m_emptyNodes = new DStack<size_t>; rebuildStack(); } template <class T> DArray <T>::DArray(DArray const &_array, bool _encapsulate) { m_encapsulated = _encapsulate; if ( _encapsulate ) { m_array = new T[_array.m_arraySize]; memcpy(m_array, _array.m_array, _array.m_arraySize * sizeof(T)); } else { m_array = _array.m_array; } m_shadow = new char[_array.m_arraySize]; memset(m_shadow, 0, _array.m_arraySize * sizeof(char)); m_numUsed = 0; for (size_t i = 0; i < _array.m_arraySize; i++) { m_shadow[i] = m_array[i] != NULL ? 1 : 0; if ( m_shadow[i] ) { m_numUsed++; } } m_arraySize = _array.m_arraySize; m_stepSize = _array.m_stepSize; m_emptyNodes = new DStack<size_t>; rebuildStack(); } template <class T> DArray <T>::DArray(int _newStepSize) { if (_newStepSize < 1) m_stepSize = -1; else m_stepSize = _newStepSize; m_numUsed = m_arraySize = 0; m_shadow = NULL; m_array = NULL; m_emptyNodes = new DStack<size_t> (_newStepSize + 1); m_emptyNodes->push((size_t)-1); m_encapsulated = true; } template <class T> DArray <T>::~DArray() { empty(); delete m_emptyNodes; m_emptyNodes = NULL; } template <class T> size_t DArray <T>::pop() { CoreAssert ( m_encapsulated ); size_t freeslot = getNextFree(); if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> void DArray <T>::rebuildStack() { if ( !m_encapsulated ) return; /* Reset free list */ m_emptyNodes->empty(); m_emptyNodes->push((size_t)-1); /* Step through, rebuilding */ for (size_t i = m_arraySize - 1; (int)i >= 0; i--) if (m_shadow[i] == 0) m_emptyNodes->push(i); } template <class T> void DArray <T>::recount() { if ( !m_encapsulated ) return; m_numUsed = 0; for (size_t i = 0; i < m_arraySize; i++) if (m_shadow[i] == 1) m_numUsed++; } template <class T> void DArray <T>::setSize(size_t newsize) { if ( !m_encapsulated ) return; if (newsize > m_arraySize) { size_t oldarraysize = m_arraySize; m_arraySize = newsize; T *temparray = new T[m_arraySize]; char *tempshadow = new char[m_arraySize]; if (m_array && m_shadow) { memcpy(&temparray[0], &m_array[0], sizeof(temparray[0]) * oldarraysize); memcpy(&tempshadow[0], &m_shadow[0], sizeof(tempshadow[0]) * oldarraysize); } memset(&temparray[oldarraysize], 0, sizeof(temparray[0]) * (m_arraySize - oldarraysize)); memset(&tempshadow[oldarraysize], 0, sizeof(tempshadow[0]) * (m_arraySize - oldarraysize)); for (size_t a = m_arraySize - 1; (int)a >= (int)oldarraysize; a--) { m_emptyNodes->push(a); } delete [] m_array; delete [] m_shadow; m_array = temparray; m_shadow = tempshadow; } else if (newsize < m_arraySize) { m_arraySize = newsize; T *temparray = new T[m_arraySize]; char *tempshadow = new char[m_arraySize]; if (m_array && m_shadow) { memcpy(&temparray[0], &m_array[0], sizeof(temparray[0]) * m_arraySize); memcpy(&tempshadow[0], &m_shadow[0], sizeof(tempshadow[0]) * m_arraySize); } /* We may have lost more than one node. It's worth rebuilding over. */ rebuildStack(); recount(); delete [] m_array; delete [] m_shadow; m_array = temparray; m_shadow = tempshadow; } else if (newsize == m_arraySize) { /* Do nothing */ } } template <class T> void DArray <T>::grow() { CoreAssert ( m_encapsulated ); if (m_stepSize == -1) { /* Double array size */ if (m_arraySize == 0) { setSize(64); } else { setSize(m_arraySize * 2); } } else { /* Increase array size by fixed amount */ setSize(m_arraySize + m_stepSize); } } template <class T> void DArray <T>::setStepSize(int _stepSize) { m_stepSize = _stepSize; } template <class T> void DArray <T>::setStepDouble() { m_stepSize = -1; } template <class T> size_t DArray <T>::insert(T const & newdata) { CoreAssert ( m_encapsulated ); size_t freeslot = getNextFree(); m_array[freeslot] = newdata; if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> void DArray <T>::insert(T const & newdata, size_t index) { CoreAssert ( m_encapsulated ); while (index >= m_arraySize) grow(); m_array[index] = newdata; if (m_shadow[index] == 0) m_numUsed++; m_shadow[index] = 1; } template <class T> void DArray <T>::empty() { if ( m_encapsulated ) { delete [] m_array; m_array = NULL; } m_array = NULL; delete [] m_shadow; m_shadow = NULL; m_emptyNodes->empty(); m_emptyNodes->push((size_t)-1); m_arraySize = 0; m_numUsed = 0; m_encapsulated = true; } template <class T> size_t DArray <T>::getNextFree() { if ( !m_encapsulated ) return -1; /* WARNING: This function assumes the node returned */ /* will be used by the calling function. */ if (!m_shadow) grow(); size_t freeslot = (size_t)-2; while ((freeslot = m_emptyNodes->pop()) != (size_t)-1) { if (m_shadow[freeslot] == 0) break; } if (freeslot == (size_t)-1) { m_emptyNodes->push((size_t)-1); freeslot = m_arraySize; grow(); } if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> T DArray <T>::get(size_t index) const { CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> T & DArray <T>::operator [](size_t index) { /* Ugh. Messy. Don't run into this. >.< */ if ( !m_encapsulated ) throw; CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> const T &DArray <T>::operator [](size_t index) const { /* Ugh. Messy. Don't run into this. >.< */ if ( !m_encapsulated ) throw; CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> size_t DArray<T>::mem_usage() const { size_t ret = sizeof(*this); ret += m_arraySize * sizeof(T); ret += m_arraySize * sizeof(char); return ret; } template <class T> void DArray <T>::remove(size_t index) { if ( !m_encapsulated ) return; CoreAssert(m_shadow[index] != 0); CoreAssert(index < m_arraySize); m_emptyNodes->push(index); if (m_shadow[index] == 1) m_numUsed--; m_shadow[index] = 0; } template <class T> size_t DArray <T>::find(T const & newdata) { for (size_t a = 0; a < m_arraySize; ++a) if (m_shadow[a]) if (Compare(m_array[a], newdata) == 0) return a; return -1; } #ifdef ENABLE_SORTS template <class T> int DArray <T>::sort(Sorter<T> *_sortMethod) { if ( !m_encapsulated ) return -1; int ret; T *temp_array = new T[m_numUsed]; T *temp_ptr = temp_array; memset(temp_array, 0, m_numUsed * sizeof(T)); for (size_t i = 0; i < m_arraySize; i++) { if (valid(i)) { *temp_ptr = m_array[i]; temp_ptr++; } } ret = _sortMethod->Sort(temp_array, m_numUsed); delete [] m_shadow; m_shadow = new char[m_numUsed]; memset(m_shadow, 1, m_numUsed); delete [] m_array; m_array = temp_array; m_arraySize = m_numUsed; rebuildStack(); recount(); return ret; } template <class T> int DArray <T>::sort(Sorter<T> &_sortMethod) { if ( !m_encapsulated ) return -1; return sort(&_sortMethod); } #endif template <class T> void DArray<T>::flush() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete m_array[i]; } } } empty(); } template <class T> void DArray<T>::flushArray() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete [] m_array[i]; } } } empty(); } /* BELOW ARE DEPRECATED FUNCTIONS */ #if !defined(DISABLE_DEPRECATED_CODE) template <class T> void DArray<T>::EmptyAndDelete() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete m_array[i]; } } } empty(); } template <class T> void DArray<T>::EmptyAndDeleteArray() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete [] m_array[i]; } } } empty(); } template <class T> void DArray<T>::ChangeData(T const & _rec, size_t index) { if ( !m_encapsulated ) return; CoreAssert(m_shadow[index] == 1); m_array[index] = _rec; } #endif } } <commit_msg>darray: no throw because we don't have C++ exceptions by policy<commit_after>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2008 Steven Noonan. * Licensed under the New BSD License. * */ #ifndef __included_cc_darray_h #error "This file shouldn't be compiled directly." #endif #include <crisscross/debug.h> #include <crisscross/darray.h> #include <crisscross/dstack.h> namespace CrissCross { namespace Data { template <class T> DArray <T>::DArray() { m_stepSize = -1; m_numUsed = m_arraySize = 0; m_shadow = NULL; m_array = NULL; m_emptyNodes = new DStack<size_t>; m_emptyNodes->push((size_t)-1); m_encapsulated = true; } template <class T> DArray <T>::DArray(T *_array, size_t _indices, bool _encapsulate) { m_encapsulated = _encapsulate; if ( _encapsulate ) { m_array = new T[_indices]; memcpy(m_array, _array, _indices * sizeof(T)); } else { m_array = _array; } m_shadow = new char[_indices]; memset(m_shadow, 0, _indices * sizeof(char)); m_numUsed = 0; for (size_t i = 0; i < _indices; i++) { m_shadow[i] = m_array[i] != NULL ? 1 : 0; if ( m_shadow[i] ) { m_numUsed++; } } m_numUsed = m_numUsed; m_arraySize = _indices; m_stepSize = -1; m_emptyNodes = new DStack<size_t>; rebuildStack(); } template <class T> DArray <T>::DArray(DArray const &_array, bool _encapsulate) { m_encapsulated = _encapsulate; if ( _encapsulate ) { m_array = new T[_array.m_arraySize]; memcpy(m_array, _array.m_array, _array.m_arraySize * sizeof(T)); } else { m_array = _array.m_array; } m_shadow = new char[_array.m_arraySize]; memset(m_shadow, 0, _array.m_arraySize * sizeof(char)); m_numUsed = 0; for (size_t i = 0; i < _array.m_arraySize; i++) { m_shadow[i] = m_array[i] != NULL ? 1 : 0; if ( m_shadow[i] ) { m_numUsed++; } } m_arraySize = _array.m_arraySize; m_stepSize = _array.m_stepSize; m_emptyNodes = new DStack<size_t>; rebuildStack(); } template <class T> DArray <T>::DArray(int _newStepSize) { if (_newStepSize < 1) m_stepSize = -1; else m_stepSize = _newStepSize; m_numUsed = m_arraySize = 0; m_shadow = NULL; m_array = NULL; m_emptyNodes = new DStack<size_t> (_newStepSize + 1); m_emptyNodes->push((size_t)-1); m_encapsulated = true; } template <class T> DArray <T>::~DArray() { empty(); delete m_emptyNodes; m_emptyNodes = NULL; } template <class T> size_t DArray <T>::pop() { CoreAssert ( m_encapsulated ); size_t freeslot = getNextFree(); if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> void DArray <T>::rebuildStack() { if ( !m_encapsulated ) return; /* Reset free list */ m_emptyNodes->empty(); m_emptyNodes->push((size_t)-1); /* Step through, rebuilding */ for (size_t i = m_arraySize - 1; (int)i >= 0; i--) if (m_shadow[i] == 0) m_emptyNodes->push(i); } template <class T> void DArray <T>::recount() { if ( !m_encapsulated ) return; m_numUsed = 0; for (size_t i = 0; i < m_arraySize; i++) if (m_shadow[i] == 1) m_numUsed++; } template <class T> void DArray <T>::setSize(size_t newsize) { if ( !m_encapsulated ) return; if (newsize > m_arraySize) { size_t oldarraysize = m_arraySize; m_arraySize = newsize; T *temparray = new T[m_arraySize]; char *tempshadow = new char[m_arraySize]; if (m_array && m_shadow) { memcpy(&temparray[0], &m_array[0], sizeof(temparray[0]) * oldarraysize); memcpy(&tempshadow[0], &m_shadow[0], sizeof(tempshadow[0]) * oldarraysize); } memset(&temparray[oldarraysize], 0, sizeof(temparray[0]) * (m_arraySize - oldarraysize)); memset(&tempshadow[oldarraysize], 0, sizeof(tempshadow[0]) * (m_arraySize - oldarraysize)); for (size_t a = m_arraySize - 1; (int)a >= (int)oldarraysize; a--) { m_emptyNodes->push(a); } delete [] m_array; delete [] m_shadow; m_array = temparray; m_shadow = tempshadow; } else if (newsize < m_arraySize) { m_arraySize = newsize; T *temparray = new T[m_arraySize]; char *tempshadow = new char[m_arraySize]; if (m_array && m_shadow) { memcpy(&temparray[0], &m_array[0], sizeof(temparray[0]) * m_arraySize); memcpy(&tempshadow[0], &m_shadow[0], sizeof(tempshadow[0]) * m_arraySize); } /* We may have lost more than one node. It's worth rebuilding over. */ rebuildStack(); recount(); delete [] m_array; delete [] m_shadow; m_array = temparray; m_shadow = tempshadow; } else if (newsize == m_arraySize) { /* Do nothing */ } } template <class T> void DArray <T>::grow() { CoreAssert ( m_encapsulated ); if (m_stepSize == -1) { /* Double array size */ if (m_arraySize == 0) { setSize(64); } else { setSize(m_arraySize * 2); } } else { /* Increase array size by fixed amount */ setSize(m_arraySize + m_stepSize); } } template <class T> void DArray <T>::setStepSize(int _stepSize) { m_stepSize = _stepSize; } template <class T> void DArray <T>::setStepDouble() { m_stepSize = -1; } template <class T> size_t DArray <T>::insert(T const & newdata) { CoreAssert ( m_encapsulated ); size_t freeslot = getNextFree(); m_array[freeslot] = newdata; if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> void DArray <T>::insert(T const & newdata, size_t index) { CoreAssert ( m_encapsulated ); while (index >= m_arraySize) grow(); m_array[index] = newdata; if (m_shadow[index] == 0) m_numUsed++; m_shadow[index] = 1; } template <class T> void DArray <T>::empty() { if ( m_encapsulated ) { delete [] m_array; m_array = NULL; } m_array = NULL; delete [] m_shadow; m_shadow = NULL; m_emptyNodes->empty(); m_emptyNodes->push((size_t)-1); m_arraySize = 0; m_numUsed = 0; m_encapsulated = true; } template <class T> size_t DArray <T>::getNextFree() { if ( !m_encapsulated ) return -1; /* WARNING: This function assumes the node returned */ /* will be used by the calling function. */ if (!m_shadow) grow(); size_t freeslot = (size_t)-2; while ((freeslot = m_emptyNodes->pop()) != (size_t)-1) { if (m_shadow[freeslot] == 0) break; } if (freeslot == (size_t)-1) { m_emptyNodes->push((size_t)-1); freeslot = m_arraySize; grow(); } if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> T DArray <T>::get(size_t index) const { CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> T & DArray <T>::operator [](size_t index) { /* Ugh. Messy. Don't run into this. >.< */ CoreAssert ( m_encapsulated ); CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> const T &DArray <T>::operator [](size_t index) const { /* Ugh. Messy. Don't run into this. >.< */ CoreAssert ( m_encapsulated ); CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> size_t DArray<T>::mem_usage() const { size_t ret = sizeof(*this); ret += m_arraySize * sizeof(T); ret += m_arraySize * sizeof(char); return ret; } template <class T> void DArray <T>::remove(size_t index) { if ( !m_encapsulated ) return; CoreAssert(m_shadow[index] != 0); CoreAssert(index < m_arraySize); m_emptyNodes->push(index); if (m_shadow[index] == 1) m_numUsed--; m_shadow[index] = 0; } template <class T> size_t DArray <T>::find(T const & newdata) { for (size_t a = 0; a < m_arraySize; ++a) if (m_shadow[a]) if (Compare(m_array[a], newdata) == 0) return a; return -1; } #ifdef ENABLE_SORTS template <class T> int DArray <T>::sort(Sorter<T> *_sortMethod) { if ( !m_encapsulated ) return -1; int ret; T *temp_array = new T[m_numUsed]; T *temp_ptr = temp_array; memset(temp_array, 0, m_numUsed * sizeof(T)); for (size_t i = 0; i < m_arraySize; i++) { if (valid(i)) { *temp_ptr = m_array[i]; temp_ptr++; } } ret = _sortMethod->Sort(temp_array, m_numUsed); delete [] m_shadow; m_shadow = new char[m_numUsed]; memset(m_shadow, 1, m_numUsed); delete [] m_array; m_array = temp_array; m_arraySize = m_numUsed; rebuildStack(); recount(); return ret; } template <class T> int DArray <T>::sort(Sorter<T> &_sortMethod) { if ( !m_encapsulated ) return -1; return sort(&_sortMethod); } #endif template <class T> void DArray<T>::flush() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete m_array[i]; } } } empty(); } template <class T> void DArray<T>::flushArray() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete [] m_array[i]; } } } empty(); } /* BELOW ARE DEPRECATED FUNCTIONS */ #if !defined(DISABLE_DEPRECATED_CODE) template <class T> void DArray<T>::EmptyAndDelete() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete m_array[i]; } } } empty(); } template <class T> void DArray<T>::EmptyAndDeleteArray() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete [] m_array[i]; } } } empty(); } template <class T> void DArray<T>::ChangeData(T const & _rec, size_t index) { if ( !m_encapsulated ) return; CoreAssert(m_shadow[index] == 1); m_array[index] = _rec; } #endif } } <|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geomgraph.h> namespace geos { NodeMap::NodeMap(NodeFactory *newNodeFact) { nodeFact=newNodeFact; nodeMap=new map<Coordinate,Node*,CoordLT>(); } NodeMap::~NodeMap() { map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; delete node; } delete nodeMap; delete nodeFact; } Node* NodeMap::addNode(const Coordinate& coord) { Node *node=find(coord); if (node==NULL) { node=nodeFact->createNode(coord); (*nodeMap)[coord]=node; } return node; } // first arg cannot be const because // it is liable to label-merging ... --strk; Node* NodeMap::addNode(Node *n) { Node *node=find(n->getCoordinate()); if (node==NULL) { (*nodeMap)[n->getCoordinate()]=n; return n; } node->mergeLabel(n); return node; } void NodeMap::add(EdgeEnd *e) { Coordinate& p=e->getCoordinate(); Node *n=addNode(p); n->add(e); } /* * @return the node if found; null otherwise */ Node* NodeMap::find(const Coordinate& coord) const { map<Coordinate,Node*,CoordLT>::iterator found=nodeMap->find(coord); if (found==nodeMap->end()) return NULL; else return found->second; } map<Coordinate,Node*,CoordLT>::iterator NodeMap::iterator() const { return nodeMap->begin(); } //Doesn't work yet. Use iterator. //public Collection NodeMap::values(){ // return nodeMap.values(); //} vector<Node*>* NodeMap::getBoundaryNodes(int geomIndex) const { vector<Node*>* bdyNodes=new vector<Node*>(); map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; if (node->getLabel()->getLocation(geomIndex)==Location::BOUNDARY) bdyNodes->push_back(node); } return bdyNodes; } string NodeMap::print() const { string out=""; map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; out+=node->print(); } return out; } } /********************************************************************** * $Log$ * Revision 1.3 2004/10/21 22:29:54 strk * Indentation changes and some more COMPUTE_Z rules * * Revision 1.2 2004/07/02 13:28:26 strk * Fixed all #include lines to reflect headers layout change. * Added client application build tips in README. * * Revision 1.1 2004/03/19 09:48:45 ybychkov * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4 * * Revision 1.12 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * **********************************************************************/ <commit_msg>Added Z merging in ::addNode<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geomgraph.h> #define DEBUG 0 namespace geos { NodeMap::NodeMap(NodeFactory *newNodeFact) { #if DEBUG cerr<<"["<<this<<"] NodeMap::NodeMap"<<endl; #endif nodeFact=newNodeFact; nodeMap=new map<Coordinate,Node*,CoordLT>(); } NodeMap::~NodeMap() { map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; delete node; } delete nodeMap; delete nodeFact; } Node* NodeMap::addNode(const Coordinate& coord) { #if DEBUG cerr<<"["<<this<<"] NodeMap::addNode("<<coord.toString()<<")"; #endif Node *node=find(coord); if (node==NULL) { #if DEBUG cerr<<" is new"<<endl; #endif node=nodeFact->createNode(coord); (*nodeMap)[coord]=node; } else { #if DEBUG cerr<<" already found ("<<node->getCoordinate().toString()<<") - adding Z"<<endl; #endif node->addZ(coord.z); } return node; } // first arg cannot be const because // it is liable to label-merging ... --strk; Node* NodeMap::addNode(Node *n) { #if DEBUG cerr<<"["<<this<<"] NodeMap::addNode("<<n->print()<<")"; #endif Node *node=find(n->getCoordinate()); if (node==NULL) { #if DEBUG cerr<<" is new"<<endl; #endif (*nodeMap)[n->getCoordinate()]=n; return n; } #if DEBUG else { cerr<<" found already, merging label"<<endl; } #endif // DEBUG node->mergeLabel(n); return node; } void NodeMap::add(EdgeEnd *e) { Coordinate& p=e->getCoordinate(); Node *n=addNode(p); n->add(e); } /* * @return the node if found; null otherwise */ Node* NodeMap::find(const Coordinate& coord) const { map<Coordinate,Node*,CoordLT>::iterator found=nodeMap->find(coord); if (found==nodeMap->end()) return NULL; else return found->second; } map<Coordinate,Node*,CoordLT>::iterator NodeMap::iterator() const { return nodeMap->begin(); } //Doesn't work yet. Use iterator. //public Collection NodeMap::values(){ // return nodeMap.values(); //} vector<Node*>* NodeMap::getBoundaryNodes(int geomIndex) const { vector<Node*>* bdyNodes=new vector<Node*>(); map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; if (node->getLabel()->getLocation(geomIndex)==Location::BOUNDARY) bdyNodes->push_back(node); } return bdyNodes; } string NodeMap::print() const { string out=""; map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; out+=node->print(); } return out; } } /********************************************************************** * $Log$ * Revision 1.4 2004/11/20 15:41:41 strk * Added Z merging in ::addNode * * Revision 1.3 2004/10/21 22:29:54 strk * Indentation changes and some more COMPUTE_Z rules * * Revision 1.2 2004/07/02 13:28:26 strk * Fixed all #include lines to reflect headers layout change. * Added client application build tips in README. * * Revision 1.1 2004/03/19 09:48:45 ybychkov * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4 * * Revision 1.12 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * **********************************************************************/ <|endoftext|>
<commit_before>/** The Opensource Compiler CKX -- for my honey ChenKX Copyright (C) 2017 CousinZe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef CKX_AST_NODE_HPP #define CKX_AST_NODE_HPP #include "defs.hpp" #include "memory.hpp" #include "string.hpp" #include "vector.hpp" #include "list.hpp" #include "ckx_type.hpp" #include "ckx_env_table.hpp" #include "ckx_token.hpp" #include "ckx_ast_node_fwd.hpp" namespace ckx { using saber::saber_ptr; class ckx_ast_node { public: explicit ckx_ast_node(saber_ptr<ckx_token> _at_token); ~ckx_ast_node() = default; saber_ptr<ckx_token> get_at_token(); private: saber_ptr<ckx_token> at_token; }; class ckx_ast_translation_unit make_use_of ckx_ast_node { public: explicit ckx_ast_translation_unit(saber_ptr<ckx_token> _at_token); ~ckx_ast_translation_unit(); void add_new_stmt(ckx_ast_stmt *_stmt); private: explicit saber::vector<ckx_ast_stmt*> stmts; ckx_env_table *global_table; }; interface ckx_ast_stmt make_use_of ckx_ast_node { public: explicit ckx_ast_stmt(saber_ptr<ckx_token> _at_token); virtual ~ckx_ast_stmt() = 0; // SKTT1Faker // This function will be finished after we get a proper intermediate // representation and start to write syntax-directed translation Q_ON_HOLD(virtual void translate(saber::list<ckx_ir_instance>& ret) = 0;) }; class ckx_ast_compound_stmt final implements ckx_ast_stmt { public: ckx_ast_compound_stmt(saber_ptr<ckx_token> _at_token, ckx_env_table *_parent_scope_table); ~ckx_ast_compound_stmt() override final; void add_new_stmt(ckx_ast_stmt *_stmt); private: saber::vector<ckx_ast_stmt*> stmts; ckx_env_table *local_table; }; class ckx_ast_if_stmt final implements ckx_ast_stmt { public: ckx_ast_if_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr* _condition, ckx_ast_stmt* _then_clause, ckx_ast_stmt* _else_clause); ~ckx_ast_if_stmt() override final; private: ckx_ast_expr *condition; ckx_ast_stmt *then_clause; ckx_ast_stmt *else_clause; }; class ckx_ast_while_stmt final implements ckx_ast_stmt { public: ckx_ast_while_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr *_condition, ckx_ast_stmt *_clause); ~ckx_ast_while_stmt() override final; private: ckx_ast_expr *condition; ckx_ast_stmt *clause; }; class ckx_ast_do_while_stmt final implements ckx_ast_stmt { public: ckx_ast_do_while_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr *_condition, ckx_ast_stmt *_clause); ~ckx_ast_do_while_stmt() override final; private: ckx_ast_expr *condition; ckx_ast_stmt *clause; }; class ckx_ast_break_stmt final implements ckx_ast_stmt { public: explicit ckx_ast_break_stmt(saber_ptr<ckx_token> _at_token); ~ckx_ast_break_stmt() override final = default; }; class ckx_ast_continue_stmt final implements ckx_ast_stmt { public: explicit ckx_ast_continue_stmt(saber_ptr<ckx_token> _at_token); ~ckx_ast_continue_stmt() override final = default; }; class ckx_ast_return_stmt final implements ckx_ast_stmt { public: ckx_ast_return_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr* _return_expr); ~ckx_ast_return_stmt() override final = default; private: ckx_ast_expr *return_expr; }; class ckx_ast_decl_stmt final implements ckx_ast_stmt { public: explicit ckx_ast_decl_stmt(saber_ptr<ckx_token> _at_token); ~ckx_ast_decl_stmt() override final; void add_decl(ckx_ast_init_decl* _decl); private: saber::vector<ckx_ast_init_decl*> decls; }; class ckx_ast_expr_stmt final implements ckx_ast_stmt { public: ckx_ast_expr_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr* _expr); ~ckx_ast_expr_stmt() override final; private: ckx_ast_expr *expr; }; class ckx_ast_expr make_use_of ckx_ast_node { Q_ON_HOLD(...) }; class ckx_ast_func_stmt make_use_of ckx_ast_node { public: ckx_ast_func_stmt(saber_ptr<ckx_token> _at_token, ckx_func_entry *_entry, ckx_env_table *_param_env_table); ~ckx_ast_func_stmt(); bool is_defined() const; ckx_env_table* get_param_env_table(); void define(ckx_ast_compound_stmt* _fnbody) const; private: ckx_func_entry *entry; ckx_env_table *param_env_table; }; class ckx_ast_init_decl make_use_of ckx_ast_node { public: ckx_ast_init_decl(saber_ptr<ckx_token> _at_token, ckx_var_entry* _entry, ckx_ast_expr* _init); ~ckx_ast_init_decl(); private: ckx_var_entry *entry; ckx_ast_expr *init; }; class ckx_ast_param_decl make_use_of ckx_ast_node { public: ckx_ast_param_decl(saber_ptr<ckx_token> _at_token, ckx_var_entry* _entry); ~ckx_ast_param_decl() = default; private: ckx_var_entry *entry; }; class ckx_ast_struct_stmt make_use_of ckx_ast_node { public: ckx_ast_struct_stmt(saber_ptr<ckx_token> _at_token, ckx_type_entry* _entry); ~ckx_ast_struct_stmt(); private: ckx_type_entry *entry; }; class ckx_ast_variant_stmt make_use_of ckx_ast_node { public: ckx_ast_variant_stmt(saber_ptr<ckx_token> _at_token, ckx_type_entry* _entry); ~ckx_ast_variant_stmt(); private: ckx_type_entry *entry; }; class ckx_ast_enum_stmt make_use_of ckx_ast_node { public: ckx_ast_enum_stmt(saber_ptr<ckx_token> _at_token, ckx_type_entry* _entry); ~ckx_ast_enum_stmt(); private: ckx_type_entry *entry; }; } // namespace ckx #endif // CKX_AST_NODE_HPP <commit_msg>[(UTF +8:00) 2017-9-1 22:46] Small bugfix.<commit_after>/** The Opensource Compiler CKX -- for my honey ChenKX Copyright (C) 2017 CousinZe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef CKX_AST_NODE_HPP #define CKX_AST_NODE_HPP #include "defs.hpp" #include "memory.hpp" #include "string.hpp" #include "vector.hpp" #include "list.hpp" #include "ckx_type.hpp" #include "ckx_env_table.hpp" #include "ckx_token.hpp" #include "ckx_ast_node_fwd.hpp" namespace ckx { using saber::saber_ptr; class ckx_ast_node { public: explicit ckx_ast_node(saber_ptr<ckx_token> _at_token); ~ckx_ast_node() = default; saber_ptr<ckx_token> get_at_token(); private: saber_ptr<ckx_token> at_token; }; class ckx_ast_translation_unit make_use_of ckx_ast_node { public: explicit ckx_ast_translation_unit(saber_ptr<ckx_token> _at_token); ~ckx_ast_translation_unit(); void add_new_stmt(ckx_ast_stmt *_stmt); private: saber::vector<ckx_ast_stmt*> stmts; ckx_env_table *global_table; }; interface ckx_ast_stmt make_use_of ckx_ast_node { public: explicit ckx_ast_stmt(saber_ptr<ckx_token> _at_token); virtual ~ckx_ast_stmt() = 0; // SKTT1Faker // This function will be finished after we get a proper intermediate // representation and start to write syntax-directed translation Q_ON_HOLD(virtual void translate(saber::list<ckx_ir_instance>& ret) = 0;) }; class ckx_ast_compound_stmt final implements ckx_ast_stmt { public: ckx_ast_compound_stmt(saber_ptr<ckx_token> _at_token, ckx_env_table *_parent_scope_table); ~ckx_ast_compound_stmt() override final; void add_new_stmt(ckx_ast_stmt *_stmt); private: saber::vector<ckx_ast_stmt*> stmts; ckx_env_table *local_table; }; class ckx_ast_if_stmt final implements ckx_ast_stmt { public: ckx_ast_if_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr* _condition, ckx_ast_stmt* _then_clause, ckx_ast_stmt* _else_clause); ~ckx_ast_if_stmt() override final; private: ckx_ast_expr *condition; ckx_ast_stmt *then_clause; ckx_ast_stmt *else_clause; }; class ckx_ast_while_stmt final implements ckx_ast_stmt { public: ckx_ast_while_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr *_condition, ckx_ast_stmt *_clause); ~ckx_ast_while_stmt() override final; private: ckx_ast_expr *condition; ckx_ast_stmt *clause; }; class ckx_ast_do_while_stmt final implements ckx_ast_stmt { public: ckx_ast_do_while_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr *_condition, ckx_ast_stmt *_clause); ~ckx_ast_do_while_stmt() override final; private: ckx_ast_expr *condition; ckx_ast_stmt *clause; }; class ckx_ast_break_stmt final implements ckx_ast_stmt { public: explicit ckx_ast_break_stmt(saber_ptr<ckx_token> _at_token); ~ckx_ast_break_stmt() override final = default; }; class ckx_ast_continue_stmt final implements ckx_ast_stmt { public: explicit ckx_ast_continue_stmt(saber_ptr<ckx_token> _at_token); ~ckx_ast_continue_stmt() override final = default; }; class ckx_ast_return_stmt final implements ckx_ast_stmt { public: ckx_ast_return_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr* _return_expr); ~ckx_ast_return_stmt() override final = default; private: ckx_ast_expr *return_expr; }; class ckx_ast_decl_stmt final implements ckx_ast_stmt { public: explicit ckx_ast_decl_stmt(saber_ptr<ckx_token> _at_token); ~ckx_ast_decl_stmt() override final; void add_decl(ckx_ast_init_decl* _decl); private: saber::vector<ckx_ast_init_decl*> decls; }; class ckx_ast_expr_stmt final implements ckx_ast_stmt { public: ckx_ast_expr_stmt(saber_ptr<ckx_token> _at_token, ckx_ast_expr* _expr); ~ckx_ast_expr_stmt() override final; private: ckx_ast_expr *expr; }; class ckx_ast_expr make_use_of ckx_ast_node { Q_ON_HOLD(...) }; class ckx_ast_func_stmt make_use_of ckx_ast_node { public: ckx_ast_func_stmt(saber_ptr<ckx_token> _at_token, ckx_func_entry *_entry, ckx_env_table *_param_env_table); ~ckx_ast_func_stmt(); bool is_defined() const; ckx_env_table* get_param_env_table(); void define(ckx_ast_compound_stmt* _fnbody) const; private: ckx_func_entry *entry; ckx_env_table *param_env_table; }; class ckx_ast_init_decl make_use_of ckx_ast_node { public: ckx_ast_init_decl(saber_ptr<ckx_token> _at_token, ckx_var_entry* _entry, ckx_ast_expr* _init); ~ckx_ast_init_decl(); private: ckx_var_entry *entry; ckx_ast_expr *init; }; class ckx_ast_param_decl make_use_of ckx_ast_node { public: ckx_ast_param_decl(saber_ptr<ckx_token> _at_token, ckx_var_entry* _entry); ~ckx_ast_param_decl() = default; private: ckx_var_entry *entry; }; class ckx_ast_struct_stmt make_use_of ckx_ast_node { public: ckx_ast_struct_stmt(saber_ptr<ckx_token> _at_token, ckx_type_entry* _entry); ~ckx_ast_struct_stmt(); private: ckx_type_entry *entry; }; class ckx_ast_variant_stmt make_use_of ckx_ast_node { public: ckx_ast_variant_stmt(saber_ptr<ckx_token> _at_token, ckx_type_entry* _entry); ~ckx_ast_variant_stmt(); private: ckx_type_entry *entry; }; class ckx_ast_enum_stmt make_use_of ckx_ast_node { public: ckx_ast_enum_stmt(saber_ptr<ckx_token> _at_token, ckx_type_entry* _entry); ~ckx_ast_enum_stmt(); private: ckx_type_entry *entry; }; } // namespace ckx #endif // CKX_AST_NODE_HPP <|endoftext|>
<commit_before>#include "xchainer/array.h" #include <initializer_list> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/backend.h" #include "xchainer/context.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_backend.h" #include "xchainer/cuda/cuda_device.h" #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/device.h" #include "xchainer/memory.h" #include "xchainer/native_backend.h" #include "xchainer/native_device.h" #include "xchainer/testing/context_session.h" namespace xchainer { namespace { class ArrayDeviceTest : public ::testing::Test { protected: void SetUp() override { context_session_.emplace(); } void TearDown() override { context_session_.reset(); } private: nonstd::optional<testing::ContextSession> context_session_; }; // Check that Array data exists on the specified device void ExpectDataExistsOnDevice(const Device& expected_device, const Array& array) { // Check device member of the Array EXPECT_EQ(&expected_device, &array.device()); // Check device of data pointee if (expected_device.backend().GetName() == "native") { EXPECT_FALSE(internal::IsPointerCudaMemory(array.data().get())); } else if (expected_device.backend().GetName() == "cuda") { EXPECT_TRUE(internal::IsPointerCudaMemory(array.data().get())); } else { FAIL() << "invalid device"; } } // Check that Arrays are created on the default device if no other devices are specified void CheckDeviceFallback(const std::function<Array()>& create_array_func) { // Fallback to default device which is CPU { Context& ctx = GetDefaultContext(); NativeBackend native_backend{ctx}; NativeDevice cpu_device{native_backend, 0}; auto scope = std::make_unique<DeviceScope>(cpu_device); Array array = create_array_func(); ExpectDataExistsOnDevice(cpu_device, array); } #ifdef XCHAINER_ENABLE_CUDA // Fallback to default device which is GPU { Context& ctx = GetDefaultContext(); cuda::CudaBackend cuda_backend{ctx}; cuda::CudaDevice cuda_device{cuda_backend, 0}; auto scope = std::make_unique<DeviceScope>(cuda_device); Array array = create_array_func(); ExpectDataExistsOnDevice(cuda_device, array); } #endif } // Check that Arrays are created on the specified device, if specified, without taking into account the default device void CheckDeviceExplicit(const std::function<Array(Device& device)>& create_array_func) { Context& ctx = GetDefaultContext(); NativeBackend native_backend{ctx}; NativeDevice cpu_device{native_backend, 0}; // Explicitly create on CPU { Array array = create_array_func(cpu_device); ExpectDataExistsOnDevice(cpu_device, array); } { auto scope = std::make_unique<DeviceScope>(cpu_device); Array array = create_array_func(cpu_device); ExpectDataExistsOnDevice(cpu_device, array); } #ifdef XCHAINER_ENABLE_CUDA cuda::CudaBackend cuda_backend{ctx}; cuda::CudaDevice cuda_device{cuda_backend, 0}; { auto scope = std::make_unique<DeviceScope>(cuda_device); Array array = create_array_func(cpu_device); ExpectDataExistsOnDevice(cpu_device, array); } // Explicitly create on GPU { Array array = create_array_func(cuda_device); ExpectDataExistsOnDevice(cuda_device, array); } { auto scope = std::make_unique<DeviceScope>(cpu_device); Array array = create_array_func(cuda_device); ExpectDataExistsOnDevice(cuda_device, array); } { auto scope = std::make_unique<DeviceScope>(cuda_device); Array array = create_array_func(cuda_device); ExpectDataExistsOnDevice(cuda_device, array); } #endif // XCHAINER_ENABLE_CUDA } TEST_F(ArrayDeviceTest, FromBuffer) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; float raw_data[] = {0.f, 1.f, 2.f, 3.f, 4.f, 5.f}; std::shared_ptr<void> data(raw_data, [](float* ptr) { (void)ptr; // unused }); CheckDeviceFallback([&]() { return Array::FromBuffer(shape, dtype, data); }); CheckDeviceExplicit([&](Device& device) { return Array::FromBuffer(shape, dtype, data, device); }); } TEST_F(ArrayDeviceTest, Empty) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { return Array::Empty(shape, dtype); }); CheckDeviceExplicit([&](Device& device) { return Array::Empty(shape, dtype, device); }); } TEST_F(ArrayDeviceTest, Full) { Shape shape({2, 3}); Scalar scalar{2.f}; Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { return Array::Full(shape, scalar, dtype); }); CheckDeviceFallback([&]() { return Array::Full(shape, scalar); }); CheckDeviceExplicit([&](Device& device) { return Array::Full(shape, scalar, dtype, device); }); CheckDeviceExplicit([&](Device& device) { return Array::Full(shape, scalar, device); }); } TEST_F(ArrayDeviceTest, Zeros) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { return Array::Zeros(shape, dtype); }); CheckDeviceExplicit([&](Device& device) { return Array::Zeros(shape, dtype, device); }); } TEST_F(ArrayDeviceTest, Ones) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { return Array::Ones(shape, dtype); }); CheckDeviceExplicit([&](Device& device) { return Array::Ones(shape, dtype, device); }); } TEST_F(ArrayDeviceTest, EmptyLike) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { Array array_orig = Array::Empty(shape, dtype); return Array::EmptyLike(array_orig); }); CheckDeviceExplicit([&](Device& device) { NativeBackend native_backend{device.context()}; NativeDevice cpu_device{native_backend, 0}; Array array_orig = Array::Empty(shape, dtype, cpu_device); return Array::EmptyLike(array_orig, device); }); } TEST_F(ArrayDeviceTest, FullLike) { Shape shape({2, 3}); Scalar scalar{2.f}; Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { Array array_orig = Array::Empty(shape, dtype); return Array::FullLike(array_orig, scalar); }); CheckDeviceExplicit([&](Device& device) { NativeBackend native_backend{device.context()}; NativeDevice cpu_device{native_backend, 0}; Array array_orig = Array::Empty(shape, dtype, cpu_device); return Array::FullLike(array_orig, scalar, device); }); } TEST_F(ArrayDeviceTest, ZerosLike) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { Array array_orig = Array::Empty(shape, dtype); return Array::ZerosLike(array_orig); }); CheckDeviceExplicit([&](Device& device) { NativeBackend native_backend{device.context()}; NativeDevice cpu_device{native_backend, 0}; Array array_orig = Array::Empty(shape, dtype, cpu_device); return Array::ZerosLike(array_orig, device); }); } TEST_F(ArrayDeviceTest, OnesLike) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { Array array_orig = Array::Empty(shape, dtype); return Array::OnesLike(array_orig); }); CheckDeviceExplicit([&](Device& device) { NativeBackend native_backend{device.context()}; NativeDevice cpu_device{native_backend, 0}; Array array_orig = Array::Empty(shape, dtype, cpu_device); return Array::OnesLike(array_orig, device); }); } TEST_F(ArrayDeviceTest, CheckDevicesCompatibleInvalidArguments) { EXPECT_THROW(CheckDevicesCompatible({}), DeviceError); } TEST_F(ArrayDeviceTest, CheckDevicesCompatibleMultipleDevices) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; Context& ctx = GetDefaultContext(); NativeBackend native_backend{ctx}; NativeDevice cpu_device_0{native_backend, 0}; NativeDevice cpu_device_1{native_backend, 1}; auto scope = std::make_unique<DeviceScope>(cpu_device_0); Array a = Array::Empty(shape, dtype, cpu_device_0); Array b = Array::Empty(shape, dtype, cpu_device_0); Array c = Array::Empty(shape, dtype, cpu_device_1); EXPECT_NO_THROW(CheckDevicesCompatible({a})); EXPECT_NO_THROW(CheckDevicesCompatible({a, b})); EXPECT_THROW(CheckDevicesCompatible({a, c}), DeviceError); } TEST_F(ArrayDeviceTest, CheckDevicesCompatibleBasicArithmetics) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; Context& ctx = GetDefaultContext(); NativeBackend native_backend{ctx}; NativeDevice cpu_device_0{native_backend, 0}; NativeDevice cpu_device_1{native_backend, 1}; auto scope = std::make_unique<DeviceScope>(cpu_device_0); Array a = Array::Empty(shape, dtype, cpu_device_0); Array b = Array::Empty(shape, dtype, cpu_device_0); Array c = Array::Empty(shape, dtype, cpu_device_1); { // Asserts no throw, and similarly for the following three cases Array d = a + b; EXPECT_EQ(&cpu_device_0, &d.device()); } { Array d = a * b; EXPECT_EQ(&cpu_device_0, &d.device()); } { a += b; EXPECT_EQ(&cpu_device_0, &a.device()); } { a *= b; EXPECT_EQ(&cpu_device_0, &a.device()); } { EXPECT_THROW(a + c, DeviceError); } { EXPECT_THROW(a += c, DeviceError); } { EXPECT_THROW(a * c, DeviceError); } { EXPECT_THROW(a *= c, DeviceError); } } } // namespace } // namespace xchainer <commit_msg>Better test variable names<commit_after>#include "xchainer/array.h" #include <initializer_list> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/backend.h" #include "xchainer/context.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_backend.h" #include "xchainer/cuda/cuda_device.h" #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/device.h" #include "xchainer/memory.h" #include "xchainer/native_backend.h" #include "xchainer/native_device.h" #include "xchainer/testing/context_session.h" namespace xchainer { namespace { class ArrayDeviceTest : public ::testing::Test { protected: void SetUp() override { context_session_.emplace(); } void TearDown() override { context_session_.reset(); } private: nonstd::optional<testing::ContextSession> context_session_; }; // Check that Array data exists on the specified device void ExpectDataExistsOnDevice(const Device& expected_device, const Array& array) { // Check device member of the Array EXPECT_EQ(&expected_device, &array.device()); // Check device of data pointee if (expected_device.backend().GetName() == "native") { EXPECT_FALSE(internal::IsPointerCudaMemory(array.data().get())); } else if (expected_device.backend().GetName() == "cuda") { EXPECT_TRUE(internal::IsPointerCudaMemory(array.data().get())); } else { FAIL() << "invalid device"; } } // Check that Arrays are created on the default device if no other devices are specified void CheckDeviceFallback(const std::function<Array()>& create_array_func) { // Fallback to default device which is CPU { Context& ctx = GetDefaultContext(); NativeBackend native_backend{ctx}; NativeDevice cpu_device{native_backend, 0}; auto scope = std::make_unique<DeviceScope>(cpu_device); Array array = create_array_func(); ExpectDataExistsOnDevice(cpu_device, array); } #ifdef XCHAINER_ENABLE_CUDA // Fallback to default device which is GPU { Context& ctx = GetDefaultContext(); cuda::CudaBackend cuda_backend{ctx}; cuda::CudaDevice cuda_device{cuda_backend, 0}; auto scope = std::make_unique<DeviceScope>(cuda_device); Array array = create_array_func(); ExpectDataExistsOnDevice(cuda_device, array); } #endif } // Check that Arrays are created on the specified device, if specified, without taking into account the default device void CheckDeviceExplicit(const std::function<Array(Device& device)>& create_array_func) { Context& ctx = GetDefaultContext(); NativeBackend native_backend{ctx}; NativeDevice cpu_device{native_backend, 0}; // Explicitly create on CPU { Array array = create_array_func(cpu_device); ExpectDataExistsOnDevice(cpu_device, array); } { auto scope = std::make_unique<DeviceScope>(cpu_device); Array array = create_array_func(cpu_device); ExpectDataExistsOnDevice(cpu_device, array); } #ifdef XCHAINER_ENABLE_CUDA cuda::CudaBackend cuda_backend{ctx}; cuda::CudaDevice cuda_device{cuda_backend, 0}; { auto scope = std::make_unique<DeviceScope>(cuda_device); Array array = create_array_func(cpu_device); ExpectDataExistsOnDevice(cpu_device, array); } // Explicitly create on GPU { Array array = create_array_func(cuda_device); ExpectDataExistsOnDevice(cuda_device, array); } { auto scope = std::make_unique<DeviceScope>(cpu_device); Array array = create_array_func(cuda_device); ExpectDataExistsOnDevice(cuda_device, array); } { auto scope = std::make_unique<DeviceScope>(cuda_device); Array array = create_array_func(cuda_device); ExpectDataExistsOnDevice(cuda_device, array); } #endif // XCHAINER_ENABLE_CUDA } TEST_F(ArrayDeviceTest, FromBuffer) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; float raw_data[] = {0.f, 1.f, 2.f, 3.f, 4.f, 5.f}; std::shared_ptr<void> data(raw_data, [](float* ptr) { (void)ptr; // unused }); CheckDeviceFallback([&]() { return Array::FromBuffer(shape, dtype, data); }); CheckDeviceExplicit([&](Device& device) { return Array::FromBuffer(shape, dtype, data, device); }); } TEST_F(ArrayDeviceTest, Empty) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { return Array::Empty(shape, dtype); }); CheckDeviceExplicit([&](Device& device) { return Array::Empty(shape, dtype, device); }); } TEST_F(ArrayDeviceTest, Full) { Shape shape({2, 3}); Scalar scalar{2.f}; Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { return Array::Full(shape, scalar, dtype); }); CheckDeviceFallback([&]() { return Array::Full(shape, scalar); }); CheckDeviceExplicit([&](Device& device) { return Array::Full(shape, scalar, dtype, device); }); CheckDeviceExplicit([&](Device& device) { return Array::Full(shape, scalar, device); }); } TEST_F(ArrayDeviceTest, Zeros) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { return Array::Zeros(shape, dtype); }); CheckDeviceExplicit([&](Device& device) { return Array::Zeros(shape, dtype, device); }); } TEST_F(ArrayDeviceTest, Ones) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { return Array::Ones(shape, dtype); }); CheckDeviceExplicit([&](Device& device) { return Array::Ones(shape, dtype, device); }); } TEST_F(ArrayDeviceTest, EmptyLike) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { Array array_orig = Array::Empty(shape, dtype); return Array::EmptyLike(array_orig); }); CheckDeviceExplicit([&](Device& device) { NativeBackend native_backend{device.context()}; NativeDevice cpu_device{native_backend, 0}; Array array_orig = Array::Empty(shape, dtype, cpu_device); return Array::EmptyLike(array_orig, device); }); } TEST_F(ArrayDeviceTest, FullLike) { Shape shape({2, 3}); Scalar scalar{2.f}; Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { Array array_orig = Array::Empty(shape, dtype); return Array::FullLike(array_orig, scalar); }); CheckDeviceExplicit([&](Device& device) { NativeBackend native_backend{device.context()}; NativeDevice cpu_device{native_backend, 0}; Array array_orig = Array::Empty(shape, dtype, cpu_device); return Array::FullLike(array_orig, scalar, device); }); } TEST_F(ArrayDeviceTest, ZerosLike) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { Array array_orig = Array::Empty(shape, dtype); return Array::ZerosLike(array_orig); }); CheckDeviceExplicit([&](Device& device) { NativeBackend native_backend{device.context()}; NativeDevice cpu_device{native_backend, 0}; Array array_orig = Array::Empty(shape, dtype, cpu_device); return Array::ZerosLike(array_orig, device); }); } TEST_F(ArrayDeviceTest, OnesLike) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; CheckDeviceFallback([&]() { Array array_orig = Array::Empty(shape, dtype); return Array::OnesLike(array_orig); }); CheckDeviceExplicit([&](Device& device) { NativeBackend native_backend{device.context()}; NativeDevice cpu_device{native_backend, 0}; Array array_orig = Array::Empty(shape, dtype, cpu_device); return Array::OnesLike(array_orig, device); }); } TEST_F(ArrayDeviceTest, CheckDevicesCompatibleInvalidArguments) { EXPECT_THROW(CheckDevicesCompatible({}), DeviceError); } TEST_F(ArrayDeviceTest, CheckDevicesCompatibleMultipleDevices) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; Context& ctx = GetDefaultContext(); NativeBackend native_backend{ctx}; NativeDevice cpu_device_0{native_backend, 0}; NativeDevice cpu_device_1{native_backend, 1}; auto scope = std::make_unique<DeviceScope>(cpu_device_0); Array a_device_0 = Array::Empty(shape, dtype, cpu_device_0); Array b_device_0 = Array::Empty(shape, dtype, cpu_device_0); Array c_device_1 = Array::Empty(shape, dtype, cpu_device_1); EXPECT_NO_THROW(CheckDevicesCompatible({a_device_0})); EXPECT_NO_THROW(CheckDevicesCompatible({a_device_0, b_device_0})); EXPECT_THROW(CheckDevicesCompatible({a_device_0, c_device_1}), DeviceError); } TEST_F(ArrayDeviceTest, CheckDevicesCompatibleBasicArithmetics) { Shape shape({2, 3}); Dtype dtype = Dtype::kFloat32; Context& ctx = GetDefaultContext(); NativeBackend native_backend{ctx}; NativeDevice cpu_device_0{native_backend, 0}; NativeDevice cpu_device_1{native_backend, 1}; auto scope = std::make_unique<DeviceScope>(cpu_device_0); Array a_device_0 = Array::Empty(shape, dtype, cpu_device_0); Array b_device_0 = Array::Empty(shape, dtype, cpu_device_0); Array c_device_1 = Array::Empty(shape, dtype, cpu_device_1); { // Asserts no throw, and similarly for the following three cases Array d_device_0 = a_device_0 + b_device_0; EXPECT_EQ(&cpu_device_0, &d_device_0.device()); } { Array d_device_0 = a_device_0 * b_device_0; EXPECT_EQ(&cpu_device_0, &d_device_0.device()); } { a_device_0 += b_device_0; EXPECT_EQ(&cpu_device_0, &a_device_0.device()); } { a_device_0 *= b_device_0; EXPECT_EQ(&cpu_device_0, &a_device_0.device()); } { EXPECT_THROW(a_device_0 + c_device_1, DeviceError); } { EXPECT_THROW(a_device_0 += c_device_1, DeviceError); } { EXPECT_THROW(a_device_0 * c_device_1, DeviceError); } { EXPECT_THROW(a_device_0 *= c_device_1, DeviceError); } } } // namespace } // namespace xchainer <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <util/timer.h> #include <httpclient/httpclient.h> #include <util/filereader.h> #include "client.h" Client::Client(ClientArguments *args) : _args(args), _status(new ClientStatus()), _reqTimer(new Timer()), _cycleTimer(new Timer()), _masterTimer(new Timer()), _http(new HTTPClient(_args->_hostname, _args->_port, _args->_keepAlive, _args->_headerBenchmarkdataCoverage, _args->_extraHeaders, _args->_authority)), _reader(new FileReader()), _output(), _linebufsize(args->_maxLineSize), _linebuf(new char[_linebufsize]), _contentbufsize(16 * args->_maxLineSize), _contentbuf(NULL), _stop(false), _done(false), _thread() { assert(args != NULL); _cycleTimer->SetMax(_args->_cycle); } Client::~Client() { delete [] _contentbuf; delete [] _linebuf; } void Client::runMe(Client * me) { me->run(); } class UrlReader { FileReader &_reader; const ClientArguments &_args; int _restarts; char *_leftOvers; int _leftOversLen; public: UrlReader(FileReader& reader, const ClientArguments &args) : _reader(reader), _args(args), _restarts(args._restartLimit), _leftOvers(NULL), _leftOversLen(0) {} int nextUrl(char *buf, int bufLen); int getContent(char *buf, int bufLen); ~UrlReader() {} }; int UrlReader::nextUrl(char *buf, int buflen) { if (_leftOvers) { if (_leftOversLen < buflen) { strncpy(buf, _leftOvers, _leftOversLen); buf[_leftOversLen] = '\0'; } else { strncpy(buf, _leftOvers, buflen); buf[buflen-1] = '\0'; } _leftOvers = NULL; return _leftOversLen; } // Read maximum to _queryfileOffsetEnd if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) { _reader.SetFilePos(_args._queryfileOffset); if (_restarts == 0) { return 0; } else if (_restarts > 0) { _restarts--; } } int ll = _reader.ReadLine(buf, buflen); while (ll > 0 && _args._usePostMode && buf[0] != '/') { ll = _reader.ReadLine(buf, buflen); } if (ll > 0 && (buf[0] == '/' || !_args._usePostMode)) { return ll; } if (_restarts == 0) { return 0; } else if (_restarts > 0) { _restarts--; } if (ll < 0) { _reader.Reset(); // Start reading from offset if (_args._singleQueryFile) { _reader.SetFilePos(_args._queryfileOffset); } } ll = _reader.ReadLine(buf, buflen); while (ll > 0 && _args._usePostMode && buf[0] != '/') { ll = _reader.ReadLine(buf, buflen); } if (ll > 0 && (buf[0] == '/' || !_args._usePostMode)) { return ll; } return 0; } int UrlReader::getContent(char *buf, int bufLen) { int totLen = 0; while (totLen < bufLen) { int len = _reader.ReadLine(buf, bufLen); if (len > 0) { if (buf[0] == '/') { _leftOvers = buf; _leftOversLen = len; return totLen; } buf += len; bufLen -= len; totLen += len; } else { return totLen; } } return totLen; } void Client::run() { char inputFilename[1024]; char outputFilename[1024]; char timestr[64]; int linelen; /// int reslen; if (_args->_usePostMode) { _contentbuf = new char[_contentbufsize]; } std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay)); // open query file snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum); if (!_reader->Open(inputFilename)) { printf("Client %d: ERROR: could not open file '%s' [read mode]\n", _args->_myNum, inputFilename); _status->SetError("Could not open query file."); return; } if (_args->_outputPattern != NULL) { snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum); _output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary); if (_output->fail()) { printf("Client %d: ERROR: could not open file '%s' [write mode]\n", _args->_myNum, outputFilename); _status->SetError("Could not open output file."); return; } } if (_output) _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); if (_args->_ignoreCount == 0) _masterTimer->Start(); // Start reading from offset if ( _args->_singleQueryFile ) _reader->SetFilePos(_args->_queryfileOffset); UrlReader urlSource(*_reader, *_args); size_t urlNumber = 0; // run queries while (!_stop) { _cycleTimer->Start(); linelen = urlSource.nextUrl(_linebuf, _linebufsize); if (linelen > 0) { ++urlNumber; } else { if (urlNumber == 0) { fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n", _args->_myNum, inputFilename); _status->SetError("Could not read any lines from query file."); } break; } if (linelen < _linebufsize) { if (_output) { _output->write("URL: ", strlen("URL: ")); _output->write(_linebuf, linelen); _output->write("\n\n", 2); } if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) { strcat(_linebuf, _args->_queryStringToAppend.c_str()); } int cLen = _args->_usePostMode ? urlSource.getContent(_contentbuf, _contentbufsize) : 0; _reqTimer->Start(); auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, _contentbuf, cLen); _reqTimer->Stop(); _status->AddRequestStatus(fetch_status.RequestStatus()); if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0) ++_status->_zeroHitQueries; if (_output) { if (!fetch_status.Ok()) { _output->write("\nFBENCH: URL FETCH FAILED!\n", strlen("\nFBENCH: URL FETCH FAILED!\n")); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } else { sprintf(timestr, "\nTIME USED: %0.4f s\n", _reqTimer->GetTimespan() / 1000.0); _output->write(timestr, strlen(timestr)); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } } if (fetch_status.ResultSize() >= _args->_byteLimit) { if (_args->_ignoreCount == 0) _status->ResponseTime(_reqTimer->GetTimespan()); } else { if (_args->_ignoreCount == 0) _status->RequestFailed(); } } else { if (_args->_ignoreCount == 0) _status->SkippedRequest(); } _cycleTimer->Stop(); if (_args->_cycle < 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan()))); } else { if (_cycleTimer->GetRemaining() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining()))); } else { if (_args->_ignoreCount == 0) _status->OverTime(); } } if (_args->_ignoreCount > 0) { _args->_ignoreCount--; if (_args->_ignoreCount == 0) _masterTimer->Start(); } // Update current time span to calculate Q/s _status->SetRealTime(_masterTimer->GetCurrent()); } _masterTimer->Stop(); _status->SetRealTime(_masterTimer->GetTimespan()); _status->SetReuseCount(_http->GetReuseCount()); printf("."); fflush(stdout); _done = true; } void Client::stop() { _stop = true; } bool Client::done() { return _done; } void Client::start() { _thread = std::thread(Client::runMe, this); } void Client::join() { _thread.join(); } <commit_msg>make _restarts count upwards<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <util/timer.h> #include <httpclient/httpclient.h> #include <util/filereader.h> #include "client.h" Client::Client(ClientArguments *args) : _args(args), _status(new ClientStatus()), _reqTimer(new Timer()), _cycleTimer(new Timer()), _masterTimer(new Timer()), _http(new HTTPClient(_args->_hostname, _args->_port, _args->_keepAlive, _args->_headerBenchmarkdataCoverage, _args->_extraHeaders, _args->_authority)), _reader(new FileReader()), _output(), _linebufsize(args->_maxLineSize), _linebuf(new char[_linebufsize]), _contentbufsize(16 * args->_maxLineSize), _contentbuf(NULL), _stop(false), _done(false), _thread() { assert(args != NULL); _cycleTimer->SetMax(_args->_cycle); } Client::~Client() { delete [] _contentbuf; delete [] _linebuf; } void Client::runMe(Client * me) { me->run(); } class UrlReader { FileReader &_reader; const ClientArguments &_args; int _restarts; char *_leftOvers; int _leftOversLen; public: UrlReader(FileReader& reader, const ClientArguments &args) : _reader(reader), _args(args), _restarts(0), _leftOvers(NULL), _leftOversLen(0) {} int nextUrl(char *buf, int bufLen); int getContent(char *buf, int bufLen); ~UrlReader() {} }; int UrlReader::nextUrl(char *buf, int buflen) { if (_leftOvers) { if (_leftOversLen < buflen) { strncpy(buf, _leftOvers, _leftOversLen); buf[_leftOversLen] = '\0'; } else { strncpy(buf, _leftOvers, buflen); buf[buflen-1] = '\0'; } _leftOvers = NULL; return _leftOversLen; } // Read maximum to _queryfileOffsetEnd if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) { _reader.SetFilePos(_args._queryfileOffset); if (_restarts == _args._restartLimit) { return 0; } else if (_args._restartLimit > 0) { _restarts++; } } int ll = _reader.ReadLine(buf, buflen); while (ll > 0 && _args._usePostMode && buf[0] != '/') { ll = _reader.ReadLine(buf, buflen); } if (ll > 0 && (buf[0] == '/' || !_args._usePostMode)) { return ll; } if (_restarts == _args._restartLimit) { return 0; } else if (_args._restartLimit > 0) { _restarts++; } if (ll < 0) { _reader.Reset(); // Start reading from offset if (_args._singleQueryFile) { _reader.SetFilePos(_args._queryfileOffset); } } ll = _reader.ReadLine(buf, buflen); while (ll > 0 && _args._usePostMode && buf[0] != '/') { ll = _reader.ReadLine(buf, buflen); } if (ll > 0 && (buf[0] == '/' || !_args._usePostMode)) { return ll; } return 0; } int UrlReader::getContent(char *buf, int bufLen) { int totLen = 0; while (totLen < bufLen) { int len = _reader.ReadLine(buf, bufLen); if (len > 0) { if (buf[0] == '/') { _leftOvers = buf; _leftOversLen = len; return totLen; } buf += len; bufLen -= len; totLen += len; } else { return totLen; } } return totLen; } void Client::run() { char inputFilename[1024]; char outputFilename[1024]; char timestr[64]; int linelen; /// int reslen; if (_args->_usePostMode) { _contentbuf = new char[_contentbufsize]; } std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay)); // open query file snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum); if (!_reader->Open(inputFilename)) { printf("Client %d: ERROR: could not open file '%s' [read mode]\n", _args->_myNum, inputFilename); _status->SetError("Could not open query file."); return; } if (_args->_outputPattern != NULL) { snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum); _output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary); if (_output->fail()) { printf("Client %d: ERROR: could not open file '%s' [write mode]\n", _args->_myNum, outputFilename); _status->SetError("Could not open output file."); return; } } if (_output) _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); if (_args->_ignoreCount == 0) _masterTimer->Start(); // Start reading from offset if ( _args->_singleQueryFile ) _reader->SetFilePos(_args->_queryfileOffset); UrlReader urlSource(*_reader, *_args); size_t urlNumber = 0; // run queries while (!_stop) { _cycleTimer->Start(); linelen = urlSource.nextUrl(_linebuf, _linebufsize); if (linelen > 0) { ++urlNumber; } else { if (urlNumber == 0) { fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n", _args->_myNum, inputFilename); _status->SetError("Could not read any lines from query file."); } break; } if (linelen < _linebufsize) { if (_output) { _output->write("URL: ", strlen("URL: ")); _output->write(_linebuf, linelen); _output->write("\n\n", 2); } if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) { strcat(_linebuf, _args->_queryStringToAppend.c_str()); } int cLen = _args->_usePostMode ? urlSource.getContent(_contentbuf, _contentbufsize) : 0; _reqTimer->Start(); auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, _contentbuf, cLen); _reqTimer->Stop(); _status->AddRequestStatus(fetch_status.RequestStatus()); if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0) ++_status->_zeroHitQueries; if (_output) { if (!fetch_status.Ok()) { _output->write("\nFBENCH: URL FETCH FAILED!\n", strlen("\nFBENCH: URL FETCH FAILED!\n")); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } else { sprintf(timestr, "\nTIME USED: %0.4f s\n", _reqTimer->GetTimespan() / 1000.0); _output->write(timestr, strlen(timestr)); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } } if (fetch_status.ResultSize() >= _args->_byteLimit) { if (_args->_ignoreCount == 0) _status->ResponseTime(_reqTimer->GetTimespan()); } else { if (_args->_ignoreCount == 0) _status->RequestFailed(); } } else { if (_args->_ignoreCount == 0) _status->SkippedRequest(); } _cycleTimer->Stop(); if (_args->_cycle < 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan()))); } else { if (_cycleTimer->GetRemaining() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining()))); } else { if (_args->_ignoreCount == 0) _status->OverTime(); } } if (_args->_ignoreCount > 0) { _args->_ignoreCount--; if (_args->_ignoreCount == 0) _masterTimer->Start(); } // Update current time span to calculate Q/s _status->SetRealTime(_masterTimer->GetCurrent()); } _masterTimer->Stop(); _status->SetRealTime(_masterTimer->GetTimespan()); _status->SetReuseCount(_http->GetReuseCount()); printf("."); fflush(stdout); _done = true; } void Client::stop() { _stop = true; } bool Client::done() { return _done; } void Client::start() { _thread = std::thread(Client::runMe, this); } void Client::join() { _thread.join(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/pipeline_integration_test_base.h" #include "base/bind.h" #include "media/base/test_data_util.h" #include "media/filters/chunk_demuxer_client.h" namespace media { // Helper class that emulates calls made on the ChunkDemuxer by the // Media Source API. class MockMediaSource : public ChunkDemuxerClient { public: MockMediaSource(const std::string& filename, int initial_append_size) : url_(GetTestDataURL(filename)), current_position_(0), initial_append_size_(initial_append_size) { ReadTestDataFile(filename, &file_data_, &file_data_size_); DCHECK_GT(initial_append_size_, 0); DCHECK_LE(initial_append_size_, file_data_size_); } virtual ~MockMediaSource() {} const std::string& url() { return url_; } void Seek(int new_position, int seek_append_size) { chunk_demuxer_->FlushData(); DCHECK_GE(new_position, 0); DCHECK_LT(new_position, file_data_size_); current_position_ = new_position; AppendData(seek_append_size); } void AppendData(int size) { DCHECK(chunk_demuxer_.get()); DCHECK_LT(current_position_, file_data_size_); DCHECK_LE(current_position_ + size, file_data_size_); chunk_demuxer_->AppendData(file_data_.get() + current_position_, size); current_position_ += size; } void EndOfStream() { chunk_demuxer_->EndOfStream(PIPELINE_OK); } void Abort() { if (!chunk_demuxer_.get()) return; chunk_demuxer_->Shutdown(); } // ChunkDemuxerClient methods. virtual void DemuxerOpened(ChunkDemuxer* demuxer) { chunk_demuxer_ = demuxer; AppendData(initial_append_size_); } virtual void DemuxerClosed() { chunk_demuxer_ = NULL; } private: std::string url_; scoped_array<uint8> file_data_; int file_data_size_; int current_position_; int initial_append_size_; scoped_refptr<ChunkDemuxer> chunk_demuxer_; }; class PipelineIntegrationTest : public testing::Test, public PipelineIntegrationTestBase { public: void StartPipelineWithMediaSource(MockMediaSource& source) { pipeline_->Start( CreateFilterCollection(&source), source.url(), base::Bind(&PipelineIntegrationTest::OnEnded, base::Unretained(this)), base::Bind(&PipelineIntegrationTest::OnError, base::Unretained(this)), NetworkEventCB(), QuitOnStatusCB(PIPELINE_OK)); message_loop_.Run(); } // Verifies that seeking works properly for ChunkDemuxer when the // seek happens while there is a pending read on the ChunkDemuxer // and no data is available. bool TestSeekDuringRead(const std::string& filename, int initial_append_size, base::TimeDelta start_seek_time, base::TimeDelta seek_time, int seek_file_position, int seek_append_size) { MockMediaSource source(filename, initial_append_size); StartPipelineWithMediaSource(source); if (pipeline_status_ != PIPELINE_OK) return false; Play(); if (!WaitUntilCurrentTimeIsAfter(start_seek_time)) return false; source.Seek(seek_file_position, seek_append_size); if (!Seek(seek_time)) return false; source.EndOfStream(); source.Abort(); Stop(); return true; } }; TEST_F(PipelineIntegrationTest, BasicPlayback) { ASSERT_TRUE(Start(GetTestDataURL("bear-320x240.webm"), PIPELINE_OK)); Play(); ASSERT_TRUE(WaitUntilOnEnded()); // TODO(dalecurtis): Due to threading issues in FFmpeg, frames are not always // decoded exactly, see http://crbug.com/93932 and http://crbug.com/109875. // ASSERT_EQ(GetVideoHash(), "f0be120a90a811506777c99a2cdf7cc1"); } // TODO(xhwang): Enable this test when AddKey is integrated into pipeline. TEST_F(PipelineIntegrationTest, DISABLED_EncryptedPlayback) { MockMediaSource source("bear-320x240-encrypted.webm", 219726); StartPipelineWithMediaSource(source); source.EndOfStream(); ASSERT_EQ(PIPELINE_OK, pipeline_status_); Play(); ASSERT_TRUE(WaitUntilOnEnded()); source.Abort(); Stop(); } // TODO(acolwell): Fix flakiness http://crbug.com/117921 TEST_F(PipelineIntegrationTest, DISABLED_SeekWhilePaused) { ASSERT_TRUE(Start(GetTestDataURL("bear-320x240.webm"), PIPELINE_OK)); base::TimeDelta duration(pipeline_->GetMediaDuration()); base::TimeDelta start_seek_time(duration / 4); base::TimeDelta seek_time(duration * 3 / 4); Play(); ASSERT_TRUE(WaitUntilCurrentTimeIsAfter(start_seek_time)); Pause(); ASSERT_TRUE(Seek(seek_time)); EXPECT_EQ(pipeline_->GetCurrentTime(), seek_time); Play(); ASSERT_TRUE(WaitUntilOnEnded()); // Make sure seeking after reaching the end works as expected. Pause(); ASSERT_TRUE(Seek(seek_time)); EXPECT_EQ(pipeline_->GetCurrentTime(), seek_time); Play(); ASSERT_TRUE(WaitUntilOnEnded()); } // TODO(acolwell): Fix flakiness http://crbug.com/117921 TEST_F(PipelineIntegrationTest, DISABLED_SeekWhilePlaying) { ASSERT_TRUE(Start(GetTestDataURL("bear-320x240.webm"), PIPELINE_OK)); base::TimeDelta duration(pipeline_->GetMediaDuration()); base::TimeDelta start_seek_time(duration / 4); base::TimeDelta seek_time(duration * 3 / 4); Play(); ASSERT_TRUE(WaitUntilCurrentTimeIsAfter(start_seek_time)); ASSERT_TRUE(Seek(seek_time)); EXPECT_GE(pipeline_->GetCurrentTime(), seek_time); ASSERT_TRUE(WaitUntilOnEnded()); // Make sure seeking after reaching the end works as expected. ASSERT_TRUE(Seek(seek_time)); EXPECT_GE(pipeline_->GetCurrentTime(), seek_time); ASSERT_TRUE(WaitUntilOnEnded()); } // Verify audio decoder & renderer can handle aborted demuxer reads. TEST_F(PipelineIntegrationTest, ChunkDemuxerAbortRead_AudioOnly) { ASSERT_TRUE(TestSeekDuringRead("bear-320x240-audio-only.webm", 8192, base::TimeDelta::FromMilliseconds(477), base::TimeDelta::FromMilliseconds(617), 0x10CA, 19730)); } // Verify video decoder & renderer can handle aborted demuxer reads. TEST_F(PipelineIntegrationTest, ChunkDemuxerAbortRead_VideoOnly) { ASSERT_TRUE(TestSeekDuringRead("bear-320x240-video-only.webm", 32768, base::TimeDelta::FromMilliseconds(200), base::TimeDelta::FromMilliseconds(1668), 0x1C896, 65536)); } } // namespace media <commit_msg>Renable hashing for the basic playback test.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/pipeline_integration_test_base.h" #include "base/bind.h" #include "media/base/test_data_util.h" #include "media/filters/chunk_demuxer_client.h" namespace media { // Helper class that emulates calls made on the ChunkDemuxer by the // Media Source API. class MockMediaSource : public ChunkDemuxerClient { public: MockMediaSource(const std::string& filename, int initial_append_size) : url_(GetTestDataURL(filename)), current_position_(0), initial_append_size_(initial_append_size) { ReadTestDataFile(filename, &file_data_, &file_data_size_); DCHECK_GT(initial_append_size_, 0); DCHECK_LE(initial_append_size_, file_data_size_); } virtual ~MockMediaSource() {} const std::string& url() { return url_; } void Seek(int new_position, int seek_append_size) { chunk_demuxer_->FlushData(); DCHECK_GE(new_position, 0); DCHECK_LT(new_position, file_data_size_); current_position_ = new_position; AppendData(seek_append_size); } void AppendData(int size) { DCHECK(chunk_demuxer_.get()); DCHECK_LT(current_position_, file_data_size_); DCHECK_LE(current_position_ + size, file_data_size_); chunk_demuxer_->AppendData(file_data_.get() + current_position_, size); current_position_ += size; } void EndOfStream() { chunk_demuxer_->EndOfStream(PIPELINE_OK); } void Abort() { if (!chunk_demuxer_.get()) return; chunk_demuxer_->Shutdown(); } // ChunkDemuxerClient methods. virtual void DemuxerOpened(ChunkDemuxer* demuxer) { chunk_demuxer_ = demuxer; AppendData(initial_append_size_); } virtual void DemuxerClosed() { chunk_demuxer_ = NULL; } private: std::string url_; scoped_array<uint8> file_data_; int file_data_size_; int current_position_; int initial_append_size_; scoped_refptr<ChunkDemuxer> chunk_demuxer_; }; class PipelineIntegrationTest : public testing::Test, public PipelineIntegrationTestBase { public: void StartPipelineWithMediaSource(MockMediaSource& source) { pipeline_->Start( CreateFilterCollection(&source), source.url(), base::Bind(&PipelineIntegrationTest::OnEnded, base::Unretained(this)), base::Bind(&PipelineIntegrationTest::OnError, base::Unretained(this)), NetworkEventCB(), QuitOnStatusCB(PIPELINE_OK)); message_loop_.Run(); } // Verifies that seeking works properly for ChunkDemuxer when the // seek happens while there is a pending read on the ChunkDemuxer // and no data is available. bool TestSeekDuringRead(const std::string& filename, int initial_append_size, base::TimeDelta start_seek_time, base::TimeDelta seek_time, int seek_file_position, int seek_append_size) { MockMediaSource source(filename, initial_append_size); StartPipelineWithMediaSource(source); if (pipeline_status_ != PIPELINE_OK) return false; Play(); if (!WaitUntilCurrentTimeIsAfter(start_seek_time)) return false; source.Seek(seek_file_position, seek_append_size); if (!Seek(seek_time)) return false; source.EndOfStream(); source.Abort(); Stop(); return true; } }; TEST_F(PipelineIntegrationTest, BasicPlayback) { ASSERT_TRUE(Start(GetTestDataURL("bear-320x240.webm"), PIPELINE_OK)); Play(); ASSERT_TRUE(WaitUntilOnEnded()); ASSERT_EQ(GetVideoHash(), "f0be120a90a811506777c99a2cdf7cc1"); } // TODO(xhwang): Enable this test when AddKey is integrated into pipeline. TEST_F(PipelineIntegrationTest, DISABLED_EncryptedPlayback) { MockMediaSource source("bear-320x240-encrypted.webm", 219726); StartPipelineWithMediaSource(source); source.EndOfStream(); ASSERT_EQ(PIPELINE_OK, pipeline_status_); Play(); ASSERT_TRUE(WaitUntilOnEnded()); source.Abort(); Stop(); } // TODO(acolwell): Fix flakiness http://crbug.com/117921 TEST_F(PipelineIntegrationTest, DISABLED_SeekWhilePaused) { ASSERT_TRUE(Start(GetTestDataURL("bear-320x240.webm"), PIPELINE_OK)); base::TimeDelta duration(pipeline_->GetMediaDuration()); base::TimeDelta start_seek_time(duration / 4); base::TimeDelta seek_time(duration * 3 / 4); Play(); ASSERT_TRUE(WaitUntilCurrentTimeIsAfter(start_seek_time)); Pause(); ASSERT_TRUE(Seek(seek_time)); EXPECT_EQ(pipeline_->GetCurrentTime(), seek_time); Play(); ASSERT_TRUE(WaitUntilOnEnded()); // Make sure seeking after reaching the end works as expected. Pause(); ASSERT_TRUE(Seek(seek_time)); EXPECT_EQ(pipeline_->GetCurrentTime(), seek_time); Play(); ASSERT_TRUE(WaitUntilOnEnded()); } // TODO(acolwell): Fix flakiness http://crbug.com/117921 TEST_F(PipelineIntegrationTest, DISABLED_SeekWhilePlaying) { ASSERT_TRUE(Start(GetTestDataURL("bear-320x240.webm"), PIPELINE_OK)); base::TimeDelta duration(pipeline_->GetMediaDuration()); base::TimeDelta start_seek_time(duration / 4); base::TimeDelta seek_time(duration * 3 / 4); Play(); ASSERT_TRUE(WaitUntilCurrentTimeIsAfter(start_seek_time)); ASSERT_TRUE(Seek(seek_time)); EXPECT_GE(pipeline_->GetCurrentTime(), seek_time); ASSERT_TRUE(WaitUntilOnEnded()); // Make sure seeking after reaching the end works as expected. ASSERT_TRUE(Seek(seek_time)); EXPECT_GE(pipeline_->GetCurrentTime(), seek_time); ASSERT_TRUE(WaitUntilOnEnded()); } // Verify audio decoder & renderer can handle aborted demuxer reads. TEST_F(PipelineIntegrationTest, ChunkDemuxerAbortRead_AudioOnly) { ASSERT_TRUE(TestSeekDuringRead("bear-320x240-audio-only.webm", 8192, base::TimeDelta::FromMilliseconds(477), base::TimeDelta::FromMilliseconds(617), 0x10CA, 19730)); } // Verify video decoder & renderer can handle aborted demuxer reads. TEST_F(PipelineIntegrationTest, ChunkDemuxerAbortRead_VideoOnly) { ASSERT_TRUE(TestSeekDuringRead("bear-320x240-video-only.webm", 32768, base::TimeDelta::FromMilliseconds(200), base::TimeDelta::FromMilliseconds(1668), 0x1C896, 65536)); } } // namespace media <|endoftext|>
<commit_before>#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/ImageIo.h" #include "cinder/gl/gl.h" using namespace ci; using namespace ci::app; using namespace std; struct Satellite { vec3 mPos; Colorf mColor; }; class DynamicCubeMappingApp : public App { public: void setup() override; void resize() override; void update() override; void keyDown( KeyEvent event ) override; void drawSatellites(); void drawSkyBox(); void draw(); gl::TextureCubeMapRef mSkyBoxCubeMap; gl::BatchRef mTeapotBatch, mSkyBoxBatch; mat4 mObjectRotation; CameraPersp mCam; gl::FboCubeMapRef mDynamicCubeMapFbo; bool mDrawCubeMap; std::vector<Satellite> mSatellites; gl::BatchRef mSatelliteBatch; }; const int SKY_BOX_SIZE = 500; void DynamicCubeMappingApp::setup() { mSkyBoxCubeMap = gl::TextureCubeMap::create( loadImage( loadAsset( "env_map.jpg" ) ), gl::TextureCubeMap::Format().mipmap() ); #if defined( CINDER_GL_ES ) auto envMapGlsl = gl::GlslProg::create( loadAsset( "env_map_es2.vert" ), loadAsset( "env_map_es2.frag" ) ); auto skyBoxGlsl = gl::GlslProg::create( loadAsset( "sky_box_es2.vert" ), loadAsset( "sky_box_es2.frag" ) ); #else auto envMapGlsl = gl::GlslProg::create( loadAsset( "env_map.vert" ), loadAsset( "env_map.frag" ) ); auto skyBoxGlsl = gl::GlslProg::create( loadAsset( "sky_box.vert" ), loadAsset( "sky_box.frag" ) ); #endif mTeapotBatch = gl::Batch::create( geom::Teapot().subdivisions( 7 ), envMapGlsl ); mTeapotBatch->getGlslProg()->uniform( "uCubeMapTex", 0 ); mSkyBoxBatch = gl::Batch::create( geom::Cube(), skyBoxGlsl ); mSkyBoxBatch->getGlslProg()->uniform( "uCubeMapTex", 0 ); // build our dynamic CubeMap mDynamicCubeMapFbo = gl::FboCubeMap::create( 1024, 1024 ); // setup satellites (orbiting spheres ) for( int i = 0; i < 33; ++i ) { mSatellites.push_back( Satellite() ); float angle = i / 33.0f; mSatellites.back().mColor = Colorf( CM_HSV, angle, 1.0f, 1.0f ); mSatellites.back().mPos = vec3( cos( angle * 2 * M_PI ) * 7, 0, sin( angle * 2 * M_PI ) * 7 ); } mSatelliteBatch = gl::Batch::create( geom::Sphere(), getStockShader( gl::ShaderDef().color() ) ); mDrawCubeMap = false; gl::enableDepthRead(); gl::enableDepthWrite(); } void DynamicCubeMappingApp::resize() { mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 ); } void DynamicCubeMappingApp::update() { // move the camera semi-randomly around based on time mCam.lookAt( vec3( 8 * sin( getElapsedSeconds() / 1 + 10 ), 7 * sin( getElapsedSeconds() / 2 ), 8 * cos( getElapsedSeconds() / 4 + 11 ) ), vec3( 0 ) ); // rotate the object (teapot) a bit each frame mObjectRotation *= rotate( 0.04f, normalize( vec3( 0.1f, 1, 0.1f ) ) ); // move the satellites for( int i = 0; i < 33; ++i ) { float angle = i / 33.0f; mSatellites[i].mPos = vec3( cos( angle * 2 * M_PI ) * 7, 6 * sin( getElapsedSeconds() * 2 + angle * 4 * M_PI ), sin( angle * 2 * M_PI ) * 7 ); } } void DynamicCubeMappingApp::keyDown( KeyEvent event ) { if( event.getChar() == 'd' ) mDrawCubeMap = ! mDrawCubeMap; } void DynamicCubeMappingApp::drawSatellites() { for( const auto &satellite : mSatellites ) { gl::pushModelMatrix(); gl::translate( satellite.mPos ); gl::color( satellite.mColor ); mSatelliteBatch->draw(); gl::popModelMatrix(); } } void DynamicCubeMappingApp::drawSkyBox() { mSkyBoxCubeMap->bind(); gl::pushMatrices(); gl::scale( SKY_BOX_SIZE, SKY_BOX_SIZE, SKY_BOX_SIZE ); mSkyBoxBatch->draw(); gl::popMatrices(); } void DynamicCubeMappingApp::draw() { gl::clear( Color( 1, 0, 0 ) ); gl::pushViewport( ivec2( 0, 0 ), mDynamicCubeMapFbo->getSize() ); // we need to save the current FBO because we'll be calling bindFramebufferFace() below gl::context()->pushFramebuffer(); for( uint8_t dir = 0; dir < 6; ++dir ) { gl::setProjectionMatrix( ci::CameraPersp( mDynamicCubeMapFbo->getWidth(), mDynamicCubeMapFbo->getHeight(), 90.0f, 1, 1000 ).getProjectionMatrix() ); gl::setViewMatrix( mDynamicCubeMapFbo->calcViewMatrix( GL_TEXTURE_CUBE_MAP_POSITIVE_X + dir, vec3( 0 ) ) ); mDynamicCubeMapFbo->bindFramebufferFace( GL_TEXTURE_CUBE_MAP_POSITIVE_X + dir ); gl::clear(); drawSatellites(); drawSkyBox(); } // restore the FBO before we bound the various faces of the CubeMapFbo gl::context()->popFramebuffer(); gl::popViewport(); gl::setMatrices( mCam ); // now draw the full scene drawSatellites(); drawSkyBox(); mDynamicCubeMapFbo->bindTexture( 0 ); gl::pushMatrices(); gl::multModelMatrix( mObjectRotation ); gl::scale( vec3( 4 ) ); mTeapotBatch->draw(); gl::popMatrices(); if( mDrawCubeMap ) { gl::setMatricesWindow( getWindowSize() ); gl::ScopedDepth d( false ); //gl::drawHorizontalCross( mDynamicCubeMapFbo->getTextureCubeMap(), Rectf( 0, 0, 400, 200 ) ); gl::drawEquirectangular( mDynamicCubeMapFbo->getTextureCubeMap(), Rectf( 0, getWindowHeight() - 200, 400, getWindowHeight() ) ); // try this alternative } } CINDER_APP( DynamicCubeMappingApp, RendererGl( RendererGl::Options().msaa( 16 ) ) )<commit_msg>Minor tweak to DynamicCubeMapping; drawing horizontal cross by default<commit_after>#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/ImageIo.h" #include "cinder/gl/gl.h" using namespace ci; using namespace ci::app; using namespace std; struct Satellite { vec3 mPos; Colorf mColor; }; class DynamicCubeMappingApp : public App { public: void setup() override; void resize() override; void update() override; void keyDown( KeyEvent event ) override; void drawSatellites(); void drawSkyBox(); void draw(); gl::TextureCubeMapRef mSkyBoxCubeMap; gl::BatchRef mTeapotBatch, mSkyBoxBatch; mat4 mObjectRotation; CameraPersp mCam; gl::FboCubeMapRef mDynamicCubeMapFbo; bool mDrawCubeMap; std::vector<Satellite> mSatellites; gl::BatchRef mSatelliteBatch; }; const int SKY_BOX_SIZE = 500; void DynamicCubeMappingApp::setup() { mSkyBoxCubeMap = gl::TextureCubeMap::create( loadImage( loadAsset( "env_map.jpg" ) ), gl::TextureCubeMap::Format().mipmap() ); #if defined( CINDER_GL_ES ) auto envMapGlsl = gl::GlslProg::create( loadAsset( "env_map_es2.vert" ), loadAsset( "env_map_es2.frag" ) ); auto skyBoxGlsl = gl::GlslProg::create( loadAsset( "sky_box_es2.vert" ), loadAsset( "sky_box_es2.frag" ) ); #else auto envMapGlsl = gl::GlslProg::create( loadAsset( "env_map.vert" ), loadAsset( "env_map.frag" ) ); auto skyBoxGlsl = gl::GlslProg::create( loadAsset( "sky_box.vert" ), loadAsset( "sky_box.frag" ) ); #endif mTeapotBatch = gl::Batch::create( geom::Teapot().subdivisions( 7 ), envMapGlsl ); mTeapotBatch->getGlslProg()->uniform( "uCubeMapTex", 0 ); mSkyBoxBatch = gl::Batch::create( geom::Cube(), skyBoxGlsl ); mSkyBoxBatch->getGlslProg()->uniform( "uCubeMapTex", 0 ); // build our dynamic CubeMap mDynamicCubeMapFbo = gl::FboCubeMap::create( 1024, 1024 ); // setup satellites (orbiting spheres ) for( int i = 0; i < 33; ++i ) { mSatellites.push_back( Satellite() ); float angle = i / 33.0f; mSatellites.back().mColor = Colorf( CM_HSV, angle, 1.0f, 1.0f ); mSatellites.back().mPos = vec3( cos( angle * 2 * M_PI ) * 7, 0, sin( angle * 2 * M_PI ) * 7 ); } mSatelliteBatch = gl::Batch::create( geom::Sphere(), getStockShader( gl::ShaderDef().color() ) ); mDrawCubeMap = true; gl::enableDepthRead(); gl::enableDepthWrite(); } void DynamicCubeMappingApp::resize() { mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 ); } void DynamicCubeMappingApp::update() { // move the camera semi-randomly around based on time mCam.lookAt( vec3( 8 * sin( getElapsedSeconds() / 1 + 10 ), 7 * sin( getElapsedSeconds() / 2 ), 8 * cos( getElapsedSeconds() / 4 + 11 ) ), vec3( 0 ) ); // rotate the object (teapot) a bit each frame mObjectRotation *= rotate( 0.04f, normalize( vec3( 0.1f, 1, 0.1f ) ) ); // move the satellites for( int i = 0; i < 33; ++i ) { float angle = i / 33.0f; mSatellites[i].mPos = vec3( cos( angle * 2 * M_PI ) * 7, 6 * sin( getElapsedSeconds() * 2 + angle * 4 * M_PI ), sin( angle * 2 * M_PI ) * 7 ); } } void DynamicCubeMappingApp::keyDown( KeyEvent event ) { if( event.getChar() == 'd' ) mDrawCubeMap = ! mDrawCubeMap; } void DynamicCubeMappingApp::drawSatellites() { for( const auto &satellite : mSatellites ) { gl::pushModelMatrix(); gl::translate( satellite.mPos ); gl::color( satellite.mColor ); mSatelliteBatch->draw(); gl::popModelMatrix(); } } void DynamicCubeMappingApp::drawSkyBox() { mSkyBoxCubeMap->bind(); gl::pushMatrices(); gl::scale( SKY_BOX_SIZE, SKY_BOX_SIZE, SKY_BOX_SIZE ); mSkyBoxBatch->draw(); gl::popMatrices(); } void DynamicCubeMappingApp::draw() { gl::clear( Color( 1, 0, 0 ) ); gl::pushViewport( ivec2( 0, 0 ), mDynamicCubeMapFbo->getSize() ); // we need to save the current FBO because we'll be calling bindFramebufferFace() below gl::context()->pushFramebuffer(); for( uint8_t dir = 0; dir < 6; ++dir ) { gl::setProjectionMatrix( ci::CameraPersp( mDynamicCubeMapFbo->getWidth(), mDynamicCubeMapFbo->getHeight(), 90.0f, 1, 1000 ).getProjectionMatrix() ); gl::setViewMatrix( mDynamicCubeMapFbo->calcViewMatrix( GL_TEXTURE_CUBE_MAP_POSITIVE_X + dir, vec3( 0 ) ) ); mDynamicCubeMapFbo->bindFramebufferFace( GL_TEXTURE_CUBE_MAP_POSITIVE_X + dir ); gl::clear(); drawSatellites(); drawSkyBox(); } // restore the FBO before we bound the various faces of the CubeMapFbo gl::context()->popFramebuffer(); gl::popViewport(); gl::setMatrices( mCam ); // now draw the full scene drawSatellites(); drawSkyBox(); mDynamicCubeMapFbo->bindTexture( 0 ); gl::pushMatrices(); gl::multModelMatrix( mObjectRotation ); gl::scale( vec3( 4 ) ); mTeapotBatch->draw(); gl::popMatrices(); if( mDrawCubeMap ) { gl::setMatricesWindow( getWindowSize() ); gl::ScopedDepth d( false ); gl::drawHorizontalCross( mDynamicCubeMapFbo->getTextureCubeMap(), Rectf( 0, 0, 300, 150 ) ); //gl::drawEquirectangular( mDynamicCubeMapFbo->getTextureCubeMap(), Rectf( 0, getWindowHeight() - 200, 400, getWindowHeight() ) ); // try this alternative } } CINDER_APP( DynamicCubeMappingApp, RendererGl( RendererGl::Options().msaa( 16 ) ) )<|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkImageToParametricSpaceFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "itkImageToParametricSpaceFilter.h" #include "itkMesh.h" #include "itkImage.h" #include "itkImageRegionIteratorWithIndex.h" int main() { // Declare the mesh pixel type. // Those are the values associated // with each mesh point. (not used on this filter test) typedef int MeshPixelType; typedef float ImagePixelType; // Declare the types of the Mesh typedef itk::Mesh<MeshPixelType> MeshType; // Declare the type for PointsContainer typedef MeshType::PointsContainer PointsContainerType; // Declare the type for PointsContainerPointer typedef MeshType::PointsContainerPointer PointsContainerPointer; // Declare the type for Points typedef MeshType::PointType PointType; // Create an input Mesh MeshType::Pointer inputMesh = MeshType::New(); // Insert data on the Mesh PointsContainerPointer points = inputMesh->GetPoints(); // Declare the type for the images typedef itk::Image<ImagePixelType,2> ImageType; typedef ImageType::Pointer ImagePointer; typedef ImageType::IndexType IndexType; // Declare the type for the images typedef itk::ImageRegionIteratorWithIndex<ImageType> ImageIteratorType; // Declare the type for the filter typedef itk::ImageToParametricSpaceFilter< ImageType, MeshType > FilterType; typedef FilterType::Pointer FilterPointer; ImagePointer imageX = ImageType::New(); ImagePointer imageY = ImageType::New(); ImagePointer imageZ = ImageType::New(); ImageType::SizeType size; ImageType::IndexType start; start = IndexType::ZeroIndex; size[0] = 10; size[1] = 10; ImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); imageX->SetLargestPossibleRegion( region ); imageY->SetLargestPossibleRegion( region ); imageZ->SetLargestPossibleRegion( region ); imageX->SetBufferedRegion( region ); imageY->SetBufferedRegion( region ); imageZ->SetBufferedRegion( region ); imageX->SetRequestedRegion( region ); imageY->SetRequestedRegion( region ); imageZ->SetRequestedRegion( region ); imageX->Allocate(); imageY->Allocate(); imageZ->Allocate(); ImageIteratorType ix( imageX, region ); ImageIteratorType iy( imageY, region ); ImageIteratorType iz( imageZ, region ); ix.GoToBegin(); iy.GoToBegin(); iz.GoToBegin(); while( ! ix.IsAtEnd() ) { ix.Set( rand() ); ++ix; } while( ! iy.IsAtEnd() ) { iy.Set( rand() ); ++iy; } while( ! iz.IsAtEnd() ) { iz.Set( rand() ); ++iz; } FilterPointer filter = FilterType::New(); // Connect the inputs filter->SetInput( 0, imageX ); filter->SetInput( 1, imageY ); filter->SetInput( 2, imageZ ); // Execute the filter filter->Update(); // Get the Smart Pointer to the Filter Output MeshType::Pointer outputMesh = filter->GetOutput(); // Get the the point container MeshType::PointsContainer::Iterator beginPoint = outputMesh->GetPoints()->Begin(); MeshType::PointsContainer::Iterator endPoint = outputMesh->GetPoints()->End(); MeshType::PointsContainer::Iterator pointIt = beginPoint; bool ok = true; ix.GoToBegin(); iy.GoToBegin(); iz.GoToBegin(); while( pointIt != endPoint ) { PointType point = pointIt.Value(); if( point[0] != ix.Value() ) { ok = false; break; } if( point[1] != iy.Value() ) { ok = false; break; } if( point[2] != iz.Value() ) { ok = false; break; } ++pointIt; ++ix; ++iy; ++iz; } // All objects should be automatically destroyed at this point if( !ok ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>FIX: Mesh pixels have to be Image::IndexType<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkImageToParametricSpaceFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "itkImageToParametricSpaceFilter.h" #include "itkMesh.h" #include "itkImage.h" #include "itkImageRegionIteratorWithIndex.h" int main() { typedef float ImagePixelType; // Declare the type for the images typedef itk::Image<ImagePixelType,2> ImageType; typedef ImageType::Pointer ImagePointer; typedef ImageType::IndexType IndexType; // Make the Mesh PointData type be an Image Index. typedef IndexType MeshPixelType; // Declare the types of the Mesh typedef itk::Mesh<MeshPixelType> MeshType; // Declare the type for PointsContainer typedef MeshType::PointsContainer PointsContainerType; // Declare the type for PointsContainerPointer typedef MeshType::PointsContainerPointer PointsContainerPointer; // Declare the type for Points typedef MeshType::PointType PointType; // Create an input Mesh MeshType::Pointer inputMesh = MeshType::New(); // Insert data on the Mesh PointsContainerPointer points = inputMesh->GetPoints(); // Declare the type for the images typedef itk::ImageRegionIteratorWithIndex<ImageType> ImageIteratorType; // Declare the type for the filter typedef itk::ImageToParametricSpaceFilter< ImageType, MeshType > FilterType; typedef FilterType::Pointer FilterPointer; ImagePointer imageX = ImageType::New(); ImagePointer imageY = ImageType::New(); ImagePointer imageZ = ImageType::New(); ImageType::SizeType size; ImageType::IndexType start; start = IndexType::ZeroIndex; size[0] = 10; size[1] = 10; ImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); imageX->SetLargestPossibleRegion( region ); imageY->SetLargestPossibleRegion( region ); imageZ->SetLargestPossibleRegion( region ); imageX->SetBufferedRegion( region ); imageY->SetBufferedRegion( region ); imageZ->SetBufferedRegion( region ); imageX->SetRequestedRegion( region ); imageY->SetRequestedRegion( region ); imageZ->SetRequestedRegion( region ); imageX->Allocate(); imageY->Allocate(); imageZ->Allocate(); ImageIteratorType ix( imageX, region ); ImageIteratorType iy( imageY, region ); ImageIteratorType iz( imageZ, region ); ix.GoToBegin(); iy.GoToBegin(); iz.GoToBegin(); while( ! ix.IsAtEnd() ) { ix.Set( rand() ); ++ix; } while( ! iy.IsAtEnd() ) { iy.Set( rand() ); ++iy; } while( ! iz.IsAtEnd() ) { iz.Set( rand() ); ++iz; } FilterPointer filter = FilterType::New(); // Connect the inputs filter->SetInput( 0, imageX ); filter->SetInput( 1, imageY ); filter->SetInput( 2, imageZ ); // Execute the filter filter->Update(); // Get the Smart Pointer to the Filter Output MeshType::Pointer outputMesh = filter->GetOutput(); // Get the the point container MeshType::PointsContainer::Iterator beginPoint = outputMesh->GetPoints()->Begin(); MeshType::PointsContainer::Iterator endPoint = outputMesh->GetPoints()->End(); MeshType::PointsContainer::Iterator pointIt = beginPoint; bool ok = true; ix.GoToBegin(); iy.GoToBegin(); iz.GoToBegin(); while( pointIt != endPoint ) { PointType point = pointIt.Value(); if( point[0] != ix.Value() ) { ok = false; break; } if( point[1] != iy.Value() ) { ok = false; break; } if( point[2] != iz.Value() ) { ok = false; break; } ++pointIt; ++ix; ++iy; ++iz; } // All objects should be automatically destroyed at this point if( !ok ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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 "CShapeSetProperty.h" #include "items/VCommentDiagramShape.h" #include "VisualizationBase/src/VisualizationManager.h" namespace Comments { bool CShapeSetProperty::canInterpret(Visualization::Item*, Visualization::Item*, const QStringList& commandTokens) { return commandTokens.size() == 2 && (commandTokens.first() == "fgcolor" || commandTokens.first() == "bgcolor" || commandTokens.first() == "bordercolor"); } Interaction::CommandResult* CShapeSetProperty::execute(Visualization::Item*, Visualization::Item* target, const QStringList& commandTokens) { auto shape = dynamic_cast<VCommentDiagramShape*>(target); shape->node()->model()->beginModification(shape->node(), "Setting color"); if(commandTokens.first() == "fgcolor") shape->node()->setTextColor(commandTokens.last()); else if(commandTokens.first() == "bgcolor") shape->node()->setBackgroundColor(commandTokens.last()); else if(commandTokens.first() == "bordercolor") shape->node()->setShapeColor(commandTokens.last()); shape->node()->model()->endModification(); shape->setUpdateNeeded(Visualization::Item::StandardUpdate); return new Interaction::CommandResult(); } QList<Interaction::CommandSuggestion*> CShapeSetProperty::suggest(Visualization::Item*, Visualization::Item*, const QString& textSoFar) { QList<Interaction::CommandSuggestion*> s; if(QString("fgcolor").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive)) s.append(new Interaction::CommandSuggestion("fgcolor", "Set shape's foreground color")); if(QString("bgcolor").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive)) s.append(new Interaction::CommandSuggestion("bgcolor", "Set shape's background color")); if(QString("bordercolor").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive)) s.append(new Interaction::CommandSuggestion("bordercolor", "Set shape's border color")); return s; } QStringList CShapeSetProperty::commandForms(Visualization::Item*, Visualization::Item*, const QString& textSoFar) { QStringList forms; if (textSoFar.isEmpty() || QString("exit").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive) ) forms.append("exit"); return forms; } } <commit_msg>Rename command fgcolor to textcolor<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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 "CShapeSetProperty.h" #include "items/VCommentDiagramShape.h" #include "VisualizationBase/src/VisualizationManager.h" namespace Comments { bool CShapeSetProperty::canInterpret(Visualization::Item*, Visualization::Item*, const QStringList& commandTokens) { return commandTokens.size() == 2 && (commandTokens.first() == "textcolor" || commandTokens.first() == "bgcolor" || commandTokens.first() == "bordercolor"); } Interaction::CommandResult* CShapeSetProperty::execute(Visualization::Item*, Visualization::Item* target, const QStringList& commandTokens) { auto shape = dynamic_cast<VCommentDiagramShape*>(target); shape->node()->model()->beginModification(shape->node(), "Setting color"); if(commandTokens.first() == "textcolor") shape->node()->setTextColor(commandTokens.last()); else if(commandTokens.first() == "bgcolor") shape->node()->setBackgroundColor(commandTokens.last()); else if(commandTokens.first() == "bordercolor") shape->node()->setShapeColor(commandTokens.last()); shape->node()->model()->endModification(); shape->setUpdateNeeded(Visualization::Item::StandardUpdate); return new Interaction::CommandResult(); } QList<Interaction::CommandSuggestion*> CShapeSetProperty::suggest(Visualization::Item*, Visualization::Item*, const QString& textSoFar) { QList<Interaction::CommandSuggestion*> s; if(QString("fgcolor").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive)) s.append(new Interaction::CommandSuggestion("textcolor", "Set shape's foreground color")); if(QString("bgcolor").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive)) s.append(new Interaction::CommandSuggestion("bgcolor", "Set shape's background color")); if(QString("bordercolor").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive)) s.append(new Interaction::CommandSuggestion("bordercolor", "Set shape's border color")); return s; } QStringList CShapeSetProperty::commandForms(Visualization::Item*, Visualization::Item*, const QString&) { QStringList forms; return forms; } } <|endoftext|>
<commit_before> #include "ksp_plugin/planetarium.hpp" #include <algorithm> #include <vector> #include "geometry/point.hpp" #include "quantities/elementary_functions.hpp" namespace principia { namespace ksp_plugin { namespace internal_planetarium { using geometry::Position; using geometry::RP2Line; using geometry::Sign; using geometry::Velocity; using quantities::Pow; using quantities::Sin; using quantities::Sqrt; using quantities::Tan; using quantities::Time; Planetarium::Parameters::Parameters(double const sphere_radius_multiplier, Angle const& angular_resolution, Angle const& field_of_view) : sphere_radius_multiplier_(sphere_radius_multiplier), sin²_angular_resolution_(Pow<2>(Sin(angular_resolution))), tan_angular_resolution_(Tan(angular_resolution)), tan_field_of_view_(Tan(field_of_view)) {} Planetarium::Planetarium( Parameters const& parameters, Perspective<Navigation, Camera> const& perspective, not_null<Ephemeris<Barycentric> const*> const ephemeris, not_null<NavigationFrame const*> const plotting_frame) : parameters_(parameters), perspective_(perspective), ephemeris_(ephemeris), plotting_frame_(plotting_frame) {} RP2Lines<Length, Camera> Planetarium::PlotMethod0( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Instant const& now, bool const reverse) const { auto const plottable_begin = begin.trajectory()->LowerBound(plotting_frame_->t_min()); auto const plottable_end = begin.trajectory()->LowerBound(plotting_frame_->t_max()); auto const plottable_spheres = ComputePlottableSpheres(now); auto const plottable_segments = ComputePlottableSegments(plottable_spheres, plottable_begin, plottable_end); auto const field_of_view_radius² = perspective_.focal() * perspective_.focal() * parameters_.tan_field_of_view_ * parameters_.tan_field_of_view_; std::experimental::optional<Position<Navigation>> previous_position; RP2Lines<Length, Camera> rp2_lines; for (auto const& plottable_segment : plottable_segments) { // Apply the projection to the current plottable segment. auto const rp2_first = perspective_(plottable_segment.first); auto const rp2_second = perspective_(plottable_segment.second); // If the segment is entirely outside the field of view, ignore it. Length const x1 = rp2_first.x(); Length const y1 = rp2_first.y(); Length const x2 = rp2_second.x(); Length const y2 = rp2_second.y(); if (x1 * x1 + y1 * y1 > field_of_view_radius² && x2 * x2 + y2 * y2 > field_of_view_radius²) { continue; } // Create a new ℝP² line when two segments are not consecutive. Don't // compare ℝP² points for equality, that's expensive. bool const are_consecutive = previous_position == plottable_segment.first; previous_position = plottable_segment.second; if (are_consecutive) { rp2_lines.back().push_back(rp2_second); } else { RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second}; rp2_lines.push_back(rp2_line); } } return rp2_lines; } RP2Lines<Length, Camera> Planetarium::PlotMethod1( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Instant const& now, bool const reverse) const { Length const focal_plane_tolerance = perspective_.focal() * parameters_.tan_angular_resolution_; auto const focal_plane_tolerance² = focal_plane_tolerance * focal_plane_tolerance; auto const rp2_lines = PlotMethod0(begin, end, now, reverse); int skipped = 0; int total = 0; RP2Lines<Length, Camera> new_rp2_lines; for (auto const& rp2_line : rp2_lines) { RP2Line<Length, Camera> new_rp2_line; std::experimental::optional<RP2Point<Length, Camera>> start_rp2_point; for (int i = 0; i < rp2_line.size(); ++i) { RP2Point<Length, Camera> const& rp2_point = rp2_line[i]; if (i == 0) { new_rp2_line.push_back(rp2_point); start_rp2_point = rp2_point; } else if (Pow<2>(rp2_point.x() - start_rp2_point->x()) + Pow<2>(rp2_point.y() - start_rp2_point->y()) > focal_plane_tolerance²) { // TODO(phl): This creates a segment if the tolerance is exceeded. It // should probably create a segment that stays just below the tolerance. new_rp2_line.push_back(rp2_point); start_rp2_point = rp2_point; } else if (i == rp2_line.size() - 1) { new_rp2_line.push_back(rp2_point); } else { ++skipped; } ++total; } new_rp2_lines.push_back(std::move(new_rp2_line)); } LOG(INFO) << "PlotMethod1 skipped " << skipped << " points out of " << total << ", emitting " << total - skipped << " points"; return new_rp2_lines; } RP2Lines<Length, Camera> Planetarium::PlotMethod2( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Instant const& now, bool const reverse) const { RP2Lines<Length, Camera> lines; if (begin == end) { return lines; } auto last = end; --last; double const tan²_angular_resolution = Pow<2>(parameters_.tan_angular_resolution_); auto const plottable_spheres = ComputePlottableSpheres(now); auto const& trajectory = *begin.trajectory(); auto const begin_time = std::max(begin.time(), plotting_frame_->t_min()); auto const last_time = std::min(last.time(), plotting_frame_->t_max()); auto const final_time = reverse ? begin_time : last_time; auto previous_time = reverse ? last_time : begin_time; Sign const direction = reverse ? Sign(-1) : Sign(1); if (direction * (final_time - previous_time) <= Time{}) { return lines; } RigidMotion<Barycentric, Navigation> to_plotting_frame_at_t = plotting_frame_->ToThisFrameAtTime(previous_time); DegreesOfFreedom<Navigation> const initial_degrees_of_freedom = to_plotting_frame_at_t( trajectory.EvaluateDegreesOfFreedom(previous_time)); Position<Navigation> previous_position = initial_degrees_of_freedom.position(); Velocity<Navigation> previous_velocity = initial_degrees_of_freedom.velocity(); Time Δt = final_time - previous_time; Instant t; double estimated_tan²_error; std::experimental::optional<DegreesOfFreedom<Barycentric>> degrees_of_freedom_in_barycentric; Position<Navigation> position; std::experimental::optional<Position<Navigation>> last_endpoint; int steps_accepted = 0; int steps_attempted = 0; goto estimate_tan²_error; while (direction * (previous_time - final_time) < Time{} && steps_accepted < 10'000) { do { // One square root because we have squared errors, another one because the // errors are quadratic in time (in other words, two square roots because // the squared errors are quartic in time). // A safety factor prevents catastrophic retries. Δt *= 0.9 * Sqrt(Sqrt(tan²_angular_resolution / estimated_tan²_error)); estimate_tan²_error: t = previous_time + Δt; if (direction * (t - final_time) > Time{}) { t = final_time; Δt = t - previous_time; } Position<Navigation> const extrapolated_position = previous_position + previous_velocity * Δt; to_plotting_frame_at_t = plotting_frame_->ToThisFrameAtTime(t); degrees_of_freedom_in_barycentric = trajectory.EvaluateDegreesOfFreedom(t); position = to_plotting_frame_at_t.rigid_transformation()( degrees_of_freedom_in_barycentric->position()); // The quadratic term of the error between the linear interpolation and // the actual function is maximized halfway through the segment, so it is // 1/2 (Δt/2)² f″(t-Δt) = (1/2 Δt² f″(t-Δt)) / 4; the squared error is // thus (1/2 Δt² f″(t-Δt))² / 16. estimated_tan²_error = perspective_.Tan²AngularDistance(extrapolated_position, position) / 16; ++steps_attempted; } while (estimated_tan²_error > tan²_angular_resolution); ++steps_accepted; // TODO(egg): also limit to field of view. auto const segment_behind_focal_plane = perspective_.SegmentBehindFocalPlane( Segment<Navigation>(previous_position, position)); previous_time = t; previous_position = position; previous_velocity = to_plotting_frame_at_t(*degrees_of_freedom_in_barycentric).velocity(); if (!segment_behind_focal_plane) { continue; } auto const visible_segments = perspective_.VisibleSegments( *segment_behind_focal_plane, plottable_spheres); for (auto const& segment : visible_segments) { if (last_endpoint != segment.first) { lines.emplace_back(); lines.back().push_back(perspective_(segment.first)); } lines.back().push_back(perspective_(segment.second)); last_endpoint = segment.second; } } LOG(INFO) << "PlotMethod2 took " << steps_accepted << " steps, attempted " << steps_attempted << " steps"; return lines; } std::vector<Sphere<Navigation>> Planetarium::ComputePlottableSpheres( Instant const& now) const { RigidMotion<Barycentric, Navigation> const rigid_motion_at_now = plotting_frame_->ToThisFrameAtTime(now); std::vector<Sphere<Navigation>> plottable_spheres; auto const& bodies = ephemeris_->bodies(); for (auto const body : bodies) { auto const trajectory = ephemeris_->trajectory(body); Length const mean_radius = body->mean_radius(); Position<Barycentric> const centre_in_barycentric = trajectory->EvaluatePosition(now); Sphere<Navigation> plottable_sphere( rigid_motion_at_now.rigid_transformation()(centre_in_barycentric), parameters_.sphere_radius_multiplier_ * mean_radius); // If the sphere is seen under an angle that is very small it doesn't // participate in hiding. if (perspective_.SphereSin²HalfAngle(plottable_sphere) > parameters_.sin²_angular_resolution_) { plottable_spheres.emplace_back(std::move(plottable_sphere)); } } return plottable_spheres; } Segments<Navigation> Planetarium::ComputePlottableSegments( const std::vector<Sphere<Navigation>>& plottable_spheres, DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end) const { Segments<Navigation> all_segments; if (begin == end) { return all_segments; } auto it1 = begin; Instant t1 = it1.time(); RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 = plotting_frame_->ToThisFrameAtTime(t1); Position<Navigation> p1 = rigid_motion_at_t1(it1.degrees_of_freedom()).position(); auto it2 = it1; while (++it2 != end) { // Processing one segment of the trajectory. Instant const t2 = it2.time(); // Transform the degrees of freedom to the plotting frame. RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 = plotting_frame_->ToThisFrameAtTime(t2); Position<Navigation> const p2 = rigid_motion_at_t2(it2.degrees_of_freedom()).position(); // Find the part of the segment that is behind the focal plane. We don't // care about things that are in front of the focal plane. const Segment<Navigation> segment = {p1, p2}; auto const segment_behind_focal_plane = perspective_.SegmentBehindFocalPlane(segment); if (segment_behind_focal_plane) { // Find the part(s) of the segment that are not hidden by spheres. These // are the ones we want to plot. auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane, plottable_spheres); std::move(segments.begin(), segments.end(), std::back_inserter(all_segments)); } it1 = it2; t1 = t2; rigid_motion_at_t1 = rigid_motion_at_t2; p1 = p2; } return all_segments; } } // namespace internal_planetarium } // namespace ksp_plugin } // namespace principia <commit_msg>the linter is stupid<commit_after> #include "ksp_plugin/planetarium.hpp" #include <algorithm> #include <vector> #include "geometry/point.hpp" #include "quantities/elementary_functions.hpp" namespace principia { namespace ksp_plugin { namespace internal_planetarium { using geometry::Position; using geometry::RP2Line; using geometry::Sign; using geometry::Velocity; using quantities::Pow; using quantities::Sin; using quantities::Sqrt; using quantities::Tan; using quantities::Time; Planetarium::Parameters::Parameters(double const sphere_radius_multiplier, Angle const& angular_resolution, Angle const& field_of_view) : sphere_radius_multiplier_(sphere_radius_multiplier), sin²_angular_resolution_(Pow<2>(Sin(angular_resolution))), tan_angular_resolution_(Tan(angular_resolution)), tan_field_of_view_(Tan(field_of_view)) {} Planetarium::Planetarium( Parameters const& parameters, Perspective<Navigation, Camera> const& perspective, not_null<Ephemeris<Barycentric> const*> const ephemeris, not_null<NavigationFrame const*> const plotting_frame) : parameters_(parameters), perspective_(perspective), ephemeris_(ephemeris), plotting_frame_(plotting_frame) {} RP2Lines<Length, Camera> Planetarium::PlotMethod0( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Instant const& now, bool const reverse) const { auto const plottable_begin = begin.trajectory()->LowerBound(plotting_frame_->t_min()); auto const plottable_end = begin.trajectory()->LowerBound(plotting_frame_->t_max()); auto const plottable_spheres = ComputePlottableSpheres(now); auto const plottable_segments = ComputePlottableSegments(plottable_spheres, plottable_begin, plottable_end); auto const field_of_view_radius² = perspective_.focal() * perspective_.focal() * parameters_.tan_field_of_view_ * parameters_.tan_field_of_view_; std::experimental::optional<Position<Navigation>> previous_position; RP2Lines<Length, Camera> rp2_lines; for (auto const& plottable_segment : plottable_segments) { // Apply the projection to the current plottable segment. auto const rp2_first = perspective_(plottable_segment.first); auto const rp2_second = perspective_(plottable_segment.second); // If the segment is entirely outside the field of view, ignore it. Length const x1 = rp2_first.x(); Length const y1 = rp2_first.y(); Length const x2 = rp2_second.x(); Length const y2 = rp2_second.y(); if (x1 * x1 + y1 * y1 > field_of_view_radius² && x2 * x2 + y2 * y2 > field_of_view_radius²) { continue; } // Create a new ℝP² line when two segments are not consecutive. Don't // compare ℝP² points for equality, that's expensive. bool const are_consecutive = previous_position == plottable_segment.first; previous_position = plottable_segment.second; if (are_consecutive) { rp2_lines.back().push_back(rp2_second); } else { RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second}; rp2_lines.push_back(rp2_line); } } return rp2_lines; } RP2Lines<Length, Camera> Planetarium::PlotMethod1( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Instant const& now, bool const reverse) const { Length const focal_plane_tolerance = perspective_.focal() * parameters_.tan_angular_resolution_; auto const focal_plane_tolerance² = focal_plane_tolerance * focal_plane_tolerance; auto const rp2_lines = PlotMethod0(begin, end, now, reverse); int skipped = 0; int total = 0; RP2Lines<Length, Camera> new_rp2_lines; for (auto const& rp2_line : rp2_lines) { RP2Line<Length, Camera> new_rp2_line; std::experimental::optional<RP2Point<Length, Camera>> start_rp2_point; for (int i = 0; i < rp2_line.size(); ++i) { RP2Point<Length, Camera> const& rp2_point = rp2_line[i]; if (i == 0) { new_rp2_line.push_back(rp2_point); start_rp2_point = rp2_point; } else if (Pow<2>(rp2_point.x() - start_rp2_point->x()) + Pow<2>(rp2_point.y() - start_rp2_point->y()) > focal_plane_tolerance²) { // TODO(phl): This creates a segment if the tolerance is exceeded. It // should probably create a segment that stays just below the tolerance. new_rp2_line.push_back(rp2_point); start_rp2_point = rp2_point; } else if (i == rp2_line.size() - 1) { new_rp2_line.push_back(rp2_point); } else { ++skipped; } ++total; } new_rp2_lines.push_back(std::move(new_rp2_line)); } LOG(INFO) << "PlotMethod1 skipped " << skipped << " points out of " << total << ", emitting " << total - skipped << " points"; return new_rp2_lines; } RP2Lines<Length, Camera> Planetarium::PlotMethod2( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Instant const& now, bool const reverse) const { RP2Lines<Length, Camera> lines; if (begin == end) { return lines; } auto last = end; --last; double const tan²_angular_resolution = Pow<2>(parameters_.tan_angular_resolution_); auto const plottable_spheres = ComputePlottableSpheres(now); auto const& trajectory = *begin.trajectory(); auto const begin_time = std::max(begin.time(), plotting_frame_->t_min()); auto const last_time = std::min(last.time(), plotting_frame_->t_max()); auto const final_time = reverse ? begin_time : last_time; auto previous_time = reverse ? last_time : begin_time; Sign const direction = reverse ? Sign(-1) : Sign(1); if (direction * (final_time - previous_time) <= Time{}) { return lines; } RigidMotion<Barycentric, Navigation> to_plotting_frame_at_t = plotting_frame_->ToThisFrameAtTime(previous_time); DegreesOfFreedom<Navigation> const initial_degrees_of_freedom = to_plotting_frame_at_t( trajectory.EvaluateDegreesOfFreedom(previous_time)); Position<Navigation> previous_position = initial_degrees_of_freedom.position(); Velocity<Navigation> previous_velocity = initial_degrees_of_freedom.velocity(); Time Δt = final_time - previous_time; Instant t; double estimated_tan²_error; std::experimental::optional<DegreesOfFreedom<Barycentric>> degrees_of_freedom_in_barycentric; Position<Navigation> position; std::experimental::optional<Position<Navigation>> last_endpoint; int steps_accepted = 0; int steps_attempted = 0; goto estimate_tan²_error; while (steps_accepted < 10'000 && direction * (previous_time - final_time) < Time{}) { do { // One square root because we have squared errors, another one because the // errors are quadratic in time (in other words, two square roots because // the squared errors are quartic in time). // A safety factor prevents catastrophic retries. Δt *= 0.9 * Sqrt(Sqrt(tan²_angular_resolution / estimated_tan²_error)); estimate_tan²_error: t = previous_time + Δt; if (direction * (t - final_time) > Time{}) { t = final_time; Δt = t - previous_time; } Position<Navigation> const extrapolated_position = previous_position + previous_velocity * Δt; to_plotting_frame_at_t = plotting_frame_->ToThisFrameAtTime(t); degrees_of_freedom_in_barycentric = trajectory.EvaluateDegreesOfFreedom(t); position = to_plotting_frame_at_t.rigid_transformation()( degrees_of_freedom_in_barycentric->position()); // The quadratic term of the error between the linear interpolation and // the actual function is maximized halfway through the segment, so it is // 1/2 (Δt/2)² f″(t-Δt) = (1/2 Δt² f″(t-Δt)) / 4; the squared error is // thus (1/2 Δt² f″(t-Δt))² / 16. estimated_tan²_error = perspective_.Tan²AngularDistance(extrapolated_position, position) / 16; ++steps_attempted; } while (estimated_tan²_error > tan²_angular_resolution); ++steps_accepted; // TODO(egg): also limit to field of view. auto const segment_behind_focal_plane = perspective_.SegmentBehindFocalPlane( Segment<Navigation>(previous_position, position)); previous_time = t; previous_position = position; previous_velocity = to_plotting_frame_at_t(*degrees_of_freedom_in_barycentric).velocity(); if (!segment_behind_focal_plane) { continue; } auto const visible_segments = perspective_.VisibleSegments( *segment_behind_focal_plane, plottable_spheres); for (auto const& segment : visible_segments) { if (last_endpoint != segment.first) { lines.emplace_back(); lines.back().push_back(perspective_(segment.first)); } lines.back().push_back(perspective_(segment.second)); last_endpoint = segment.second; } } LOG(INFO) << "PlotMethod2 took " << steps_accepted << " steps, attempted " << steps_attempted << " steps"; return lines; } std::vector<Sphere<Navigation>> Planetarium::ComputePlottableSpheres( Instant const& now) const { RigidMotion<Barycentric, Navigation> const rigid_motion_at_now = plotting_frame_->ToThisFrameAtTime(now); std::vector<Sphere<Navigation>> plottable_spheres; auto const& bodies = ephemeris_->bodies(); for (auto const body : bodies) { auto const trajectory = ephemeris_->trajectory(body); Length const mean_radius = body->mean_radius(); Position<Barycentric> const centre_in_barycentric = trajectory->EvaluatePosition(now); Sphere<Navigation> plottable_sphere( rigid_motion_at_now.rigid_transformation()(centre_in_barycentric), parameters_.sphere_radius_multiplier_ * mean_radius); // If the sphere is seen under an angle that is very small it doesn't // participate in hiding. if (perspective_.SphereSin²HalfAngle(plottable_sphere) > parameters_.sin²_angular_resolution_) { plottable_spheres.emplace_back(std::move(plottable_sphere)); } } return plottable_spheres; } Segments<Navigation> Planetarium::ComputePlottableSegments( const std::vector<Sphere<Navigation>>& plottable_spheres, DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end) const { Segments<Navigation> all_segments; if (begin == end) { return all_segments; } auto it1 = begin; Instant t1 = it1.time(); RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 = plotting_frame_->ToThisFrameAtTime(t1); Position<Navigation> p1 = rigid_motion_at_t1(it1.degrees_of_freedom()).position(); auto it2 = it1; while (++it2 != end) { // Processing one segment of the trajectory. Instant const t2 = it2.time(); // Transform the degrees of freedom to the plotting frame. RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 = plotting_frame_->ToThisFrameAtTime(t2); Position<Navigation> const p2 = rigid_motion_at_t2(it2.degrees_of_freedom()).position(); // Find the part of the segment that is behind the focal plane. We don't // care about things that are in front of the focal plane. const Segment<Navigation> segment = {p1, p2}; auto const segment_behind_focal_plane = perspective_.SegmentBehindFocalPlane(segment); if (segment_behind_focal_plane) { // Find the part(s) of the segment that are not hidden by spheres. These // are the ones we want to plot. auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane, plottable_spheres); std::move(segments.begin(), segments.end(), std::back_inserter(all_segments)); } it1 = it2; t1 = t2; rigid_motion_at_t1 = rigid_motion_at_t2; p1 = p2; } return all_segments; } } // namespace internal_planetarium } // namespace ksp_plugin } // namespace principia <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/voice_engine/channel_manager.h" #include "webrtc/voice_engine/channel.h" namespace webrtc { namespace voe { ChannelOwner::ChannelOwner(class Channel* channel) : channel_ref_(new ChannelRef(channel)) {} ChannelOwner::ChannelOwner(const ChannelOwner& channel_owner) : channel_ref_(channel_owner.channel_ref_) { ++channel_ref_->ref_count; } ChannelOwner::~ChannelOwner() { if (--channel_ref_->ref_count == 0) delete channel_ref_; } ChannelOwner& ChannelOwner::operator=(const ChannelOwner& other) { if (other.channel_ref_ == channel_ref_) return *this; if (--channel_ref_->ref_count == 0) delete channel_ref_; channel_ref_ = other.channel_ref_; ++channel_ref_->ref_count; return *this; } ChannelOwner::ChannelRef::ChannelRef(class Channel* channel) : channel(channel), ref_count(1) {} ChannelManager::ChannelManager(uint32_t instance_id) : instance_id_(instance_id), last_channel_id_(-1), lock_(CriticalSectionWrapper::CreateCriticalSection()) {} ChannelOwner ChannelManager::CreateChannel() { Channel* channel; Channel::CreateChannel(channel, ++last_channel_id_, instance_id_); ChannelOwner channel_owner(channel); CriticalSectionScoped crit(lock_.get()); channels_.push_back(channel_owner); return channel_owner; } ChannelOwner ChannelManager::GetChannel(int32_t channel_id) { CriticalSectionScoped crit(lock_.get()); for (size_t i = 0; i < channels_.size(); ++i) { if (channels_[i].channel()->ChannelId() == channel_id) return channels_[i]; } return ChannelOwner(NULL); } void ChannelManager::GetAllChannels(std::vector<ChannelOwner>* channels) { CriticalSectionScoped crit(lock_.get()); *channels = channels_; } void ChannelManager::DestroyChannel(int32_t channel_id) { CriticalSectionScoped crit(lock_.get()); assert(channel_id >= 0); for (std::vector<ChannelOwner>::iterator it = channels_.begin(); it != channels_.end(); ++it) { if (it->channel()->ChannelId() == channel_id) { channels_.erase(it); break; } } } void ChannelManager::DestroyAllChannels() { CriticalSectionScoped crit(lock_.get()); channels_.clear(); } size_t ChannelManager::NumOfChannels() const { CriticalSectionScoped crit(lock_.get()); return channels_.size(); } ChannelManager::Iterator::Iterator(ChannelManager* channel_manager) : iterator_pos_(0) { channel_manager->GetAllChannels(&channels_); } Channel* ChannelManager::Iterator::GetChannel() { if (iterator_pos_ < channels_.size()) return channels_[iterator_pos_].channel(); return NULL; } bool ChannelManager::Iterator::IsValid() { return iterator_pos_ < channels_.size(); } void ChannelManager::Iterator::Increment() { ++iterator_pos_; } } // namespace voe } // namespace webrtc <commit_msg>Delete Channels without ChannelManager lock.<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/voice_engine/channel_manager.h" #include "webrtc/voice_engine/channel.h" namespace webrtc { namespace voe { ChannelOwner::ChannelOwner(class Channel* channel) : channel_ref_(new ChannelRef(channel)) {} ChannelOwner::ChannelOwner(const ChannelOwner& channel_owner) : channel_ref_(channel_owner.channel_ref_) { ++channel_ref_->ref_count; } ChannelOwner::~ChannelOwner() { if (--channel_ref_->ref_count == 0) delete channel_ref_; } ChannelOwner& ChannelOwner::operator=(const ChannelOwner& other) { if (other.channel_ref_ == channel_ref_) return *this; if (--channel_ref_->ref_count == 0) delete channel_ref_; channel_ref_ = other.channel_ref_; ++channel_ref_->ref_count; return *this; } ChannelOwner::ChannelRef::ChannelRef(class Channel* channel) : channel(channel), ref_count(1) {} ChannelManager::ChannelManager(uint32_t instance_id) : instance_id_(instance_id), last_channel_id_(-1), lock_(CriticalSectionWrapper::CreateCriticalSection()) {} ChannelOwner ChannelManager::CreateChannel() { Channel* channel; Channel::CreateChannel(channel, ++last_channel_id_, instance_id_); ChannelOwner channel_owner(channel); CriticalSectionScoped crit(lock_.get()); channels_.push_back(channel_owner); return channel_owner; } ChannelOwner ChannelManager::GetChannel(int32_t channel_id) { CriticalSectionScoped crit(lock_.get()); for (size_t i = 0; i < channels_.size(); ++i) { if (channels_[i].channel()->ChannelId() == channel_id) return channels_[i]; } return ChannelOwner(NULL); } void ChannelManager::GetAllChannels(std::vector<ChannelOwner>* channels) { CriticalSectionScoped crit(lock_.get()); *channels = channels_; } void ChannelManager::DestroyChannel(int32_t channel_id) { assert(channel_id >= 0); // Holds a reference to a channel, this is used so that we never delete // Channels while holding a lock, but rather when the method returns. ChannelOwner reference(NULL); { CriticalSectionScoped crit(lock_.get()); for (std::vector<ChannelOwner>::iterator it = channels_.begin(); it != channels_.end(); ++it) { if (it->channel()->ChannelId() == channel_id) { reference = *it; channels_.erase(it); break; } } } } void ChannelManager::DestroyAllChannels() { // Holds references so that Channels are not destroyed while holding this // lock, but rather when the method returns. std::vector<ChannelOwner> references; { CriticalSectionScoped crit(lock_.get()); references = channels_; channels_.clear(); } } size_t ChannelManager::NumOfChannels() const { CriticalSectionScoped crit(lock_.get()); return channels_.size(); } ChannelManager::Iterator::Iterator(ChannelManager* channel_manager) : iterator_pos_(0) { channel_manager->GetAllChannels(&channels_); } Channel* ChannelManager::Iterator::GetChannel() { if (iterator_pos_ < channels_.size()) return channels_[iterator_pos_].channel(); return NULL; } bool ChannelManager::Iterator::IsValid() { return iterator_pos_ < channels_.size(); } void ChannelManager::Iterator::Increment() { ++iterator_pos_; } } // namespace voe } // namespace webrtc <|endoftext|>
<commit_before>#include <string> /* public class TennisGame4 implements TennisGame { int serverScore; int receiverScore; String server; String receiver; public TennisGame4(String player1, String player2) { this.server = player1; this.receiver = player2; } @java.lang.Override public void wonPoint(String playerName) { if (server.equals(playerName)) this.serverScore += 1; else this.receiverScore += 1; } @java.lang.Override public String getScore() { TennisResult result = new Deuce( this, new GameServer( this, new GameReceiver( this, new AdvantageServer( this, new AdvantageReceiver( this, new DefaultResult(this)))))).getResult(); return result.format(); } boolean receiverHasAdvantage() { return receiverScore >= 4 && (receiverScore - serverScore) == 1; } boolean serverHasAdvantage() { return serverScore >= 4 && (serverScore - receiverScore) == 1; } boolean receiverHasWon() { return receiverScore >= 4 && (receiverScore - serverScore) >= 2; } boolean serverHasWon() { return serverScore >= 4 && (serverScore - receiverScore) >= 2; } boolean isDeuce() { return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore); } } class TennisResult { String serverScore; String receiverScore; TennisResult(String serverScore, String receiverScore) { this.serverScore = serverScore; this.receiverScore = receiverScore; } String format() { if ("".equals(this.receiverScore)) return this.serverScore; if (serverScore.equals(receiverScore)) return serverScore + "-All"; return this.serverScore + "-" + this.receiverScore; } } interface ResultProvider { TennisResult getResult(); } class Deuce implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public Deuce(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.isDeuce()) return new TennisResult("Deuce", ""); return this.nextResult.getResult(); } } class GameServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasWon()) return new TennisResult("Win for " + game.server, ""); return this.nextResult.getResult(); } } class GameReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasWon()) return new TennisResult("Win for " + game.receiver, ""); return this.nextResult.getResult(); }t } class AdvantageServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasAdvantage()) return new TennisResult("Advantage " + game.server, ""); return this.nextResult.getResult(); } } class AdvantageReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasAdvantage()) return new TennisResult("Advantage " + game.receiver, ""); return this.nextResult.getResult(); } } class DefaultResult implements ResultProvider { private static final String[] scores = {"Love", "Fifteen", "Thirty", "Forty"}; private final TennisGame4 game; public DefaultResult(TennisGame4 game) { this.game = game; } @Override public TennisResult getResult() { return new TennisResult(scores[game.serverScore], scores[game.receiverScore]); } } */ class TennisResult { std::string serverScore; std::string receiverScore; TennisResult(std::string serverScore, std::string receiverScore) { this->serverScore = serverScore; this->receiverScore = receiverScore; } std::string format() { if ("" == this->receiverScore) return this->serverScore; if (serverScore == this->receiverScore) return serverScore + "-All"; return this->serverScore + "-" + this->receiverScore; } }; class ResultProvider { virtual ~ResultProvider() {} virtual TennisResult getResult() = 0; }; const std::string tennis_score(int p1, int p2) { std::string s; std::string p1N = "player1"; std::string p2N = "player2"; if ((p1 < 4 && p2 < 4) && (p1 + p2 < 6)) { std::string p[4] = {"Love", "Fifteen", "Thirty", "Forty"}; s = p[p1]; return (p1 == p2) ? s + "-All" : s + "-" + p[p2]; } else { if (p1 == p2) return "Deuce"; s = p1 > p2 ? p1N : p2N; return ((p1-p2)*(p1-p2) == 1) ? "Advantage " + s : "Win for " + s; } }<commit_msg>Add helpful w.i.p comments<commit_after>#include <string> /* public class TennisGame4 implements TennisGame { int serverScore; int receiverScore; String server; String receiver; public TennisGame4(String player1, String player2) { this.server = player1; this.receiver = player2; } @java.lang.Override public void wonPoint(String playerName) { if (server.equals(playerName)) this.serverScore += 1; else this.receiverScore += 1; } @java.lang.Override public String getScore() { TennisResult result = new Deuce( this, new GameServer( this, new GameReceiver( this, new AdvantageServer( this, new AdvantageReceiver( this, new DefaultResult(this)))))).getResult(); return result.format(); } boolean receiverHasAdvantage() { return receiverScore >= 4 && (receiverScore - serverScore) == 1; } boolean serverHasAdvantage() { return serverScore >= 4 && (serverScore - receiverScore) == 1; } boolean receiverHasWon() { return receiverScore >= 4 && (receiverScore - serverScore) >= 2; } boolean serverHasWon() { return serverScore >= 4 && (serverScore - receiverScore) >= 2; } boolean isDeuce() { return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore); } } class TennisResult { String serverScore; String receiverScore; TennisResult(String serverScore, String receiverScore) { this.serverScore = serverScore; this.receiverScore = receiverScore; } String format() { if ("".equals(this.receiverScore)) return this.serverScore; if (serverScore.equals(receiverScore)) return serverScore + "-All"; return this.serverScore + "-" + this.receiverScore; } } interface ResultProvider { TennisResult getResult(); } class Deuce implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public Deuce(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.isDeuce()) return new TennisResult("Deuce", ""); return this.nextResult.getResult(); } } class GameServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasWon()) return new TennisResult("Win for " + game.server, ""); return this.nextResult.getResult(); } } class GameReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasWon()) return new TennisResult("Win for " + game.receiver, ""); return this.nextResult.getResult(); }t } class AdvantageServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasAdvantage()) return new TennisResult("Advantage " + game.server, ""); return this.nextResult.getResult(); } } class AdvantageReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasAdvantage()) return new TennisResult("Advantage " + game.receiver, ""); return this.nextResult.getResult(); } } class DefaultResult implements ResultProvider { private static final String[] scores = {"Love", "Fifteen", "Thirty", "Forty"}; private final TennisGame4 game; public DefaultResult(TennisGame4 game) { this.game = game; } @Override public TennisResult getResult() { return new TennisResult(scores[game.serverScore], scores[game.receiverScore]); } } */ class TennisResult { std::string serverScore; std::string receiverScore; TennisResult(std::string serverScore, std::string receiverScore) { this->serverScore = serverScore; this->receiverScore = receiverScore; } std::string format() { if ("" == this->receiverScore) return this->serverScore; if (serverScore == this->receiverScore) return serverScore + "-All"; return this->serverScore + "-" + this->receiverScore; } }; class ResultProvider { virtual ~ResultProvider() {} virtual TennisResult getResult() = 0; }; /* public class TennisGame4 implements TennisGame { ##class TennisResult { ##interface ResultProvider { class Deuce implements ResultProvider { class GameServer implements ResultProvider { class GameReceiver implements ResultProvider { class AdvantageServer implements ResultProvider { class AdvantageReceiver implements ResultProvider { class DefaultResult implements ResultProvider { */ // tennis3 function below (TODO: re-implement using class mess above!) /* relevant inspiration from Java Unit Test public void checkAllScores(TennisGame game) { int highestScore = Math.max(this.player1Score, this.player2Score); for (int i = 0; i < highestScore; i++) { if (i < this.player1Score) game.wonPoint("player1"); if (i < this.player2Score) game.wonPoint("player2"); } assertEquals(this.expectedScore, game.getScore()); } */ const std::string tennis_score(int p1, int p2) { std::string s; std::string p1N = "player1"; std::string p2N = "player2"; if ((p1 < 4 && p2 < 4) && (p1 + p2 < 6)) { std::string p[4] = {"Love", "Fifteen", "Thirty", "Forty"}; s = p[p1]; return (p1 == p2) ? s + "-All" : s + "-" + p[p2]; } else { if (p1 == p2) return "Deuce"; s = p1 > p2 ? p1N : p2N; return ((p1-p2)*(p1-p2) == 1) ? "Advantage " + s : "Win for " + s; } }<|endoftext|>
<commit_before>/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "glm/glm.hpp" #include "glm/gtc/type_ptr.hpp" #include "shaders/shader.h" #include "shader_data.h" namespace gvr { /** * Constructs a bnse material. * The material contains a UniformBlock describing the possible uniforms * that can be used by this material. It also maintains the list of * possible textures in the order specified by the descriptor. * All materials which use the same shader will have the same ordering * of uniforms and textures in their descriptors. * @param uniform_desc string describing uniforms used by this material * @param texture_desc string describing textures used by this material */ ShaderData::ShaderData(const char* texture_desc) : mNativeShader(0), mTextureDesc(texture_desc), mLock() { DataDescriptor texdesc(texture_desc); texdesc.forEach([this](const char* name, const char* type, int size) mutable { mTextureNames.push_back(name); mTextures.push_back(nullptr); }); } Texture* ShaderData::getTexture(const char* key) const { for (auto it = mTextureNames.begin(); it < mTextureNames.end(); ++it) { if (*it == key) { return mTextures[it - mTextureNames.begin()]; } } return NULL; } void ShaderData::setTexture(const char* key, Texture* texture) { std::lock_guard<std::mutex> lock(mLock); for (auto it = mTextureNames.begin(); it < mTextureNames.end(); ++it) { const std::string& temp = *it; if (temp.compare(key) == 0) { int i = it - mTextureNames.begin(); Texture* oldtex = mTextures[i]; dirty(oldtex ? MOD_TEXTURE : NEW_TEXTURE); mTextures[i] = texture; return; } } } /** * Visits each texture in the material and calls the given function. */ void ShaderData::forEachTexture(std::function< void(const char* texname, Texture* tex) > func) const { std::lock_guard<std::mutex> lock(mLock); for (int i = 0; i < mTextureNames.size(); ++i) { Texture* tex = mTextures[i]; const std::string& name = mTextureNames[i]; func(name.c_str(), tex); } } std::string ShaderData::makeShaderLayout() { return uniforms().makeShaderLayout(); } int ShaderData::getByteSize(const char* name) const { return uniforms().getByteSize(name); } const char* ShaderData::getUniformDescriptor() const { return uniforms().getDescriptor(); } const char* ShaderData::getTextureDescriptor() const { return mTextureDesc.c_str(); } bool ShaderData::getFloat(const char* name, float& v) const { return uniforms().getFloat(name, v); } bool ShaderData::getInt(const char* name, int& v) const { return uniforms().getInt(name, v); } bool ShaderData::setInt(const char* name, int val) { std::lock_guard<std::mutex> lock(mLock); dirty(MAT_DATA); return uniforms().setInt(name, val); } bool ShaderData::setFloat(const char* name, float val) { std::lock_guard<std::mutex> lock(mLock); dirty(MAT_DATA); return uniforms().setFloat(name, val); } bool ShaderData::setIntVec(const char* name, const int* val, int n) { std::lock_guard<std::mutex> lock(mLock); dirty(MAT_DATA); return uniforms().setIntVec(name, val, n); } bool ShaderData::setFloatVec(const char* name, const float* val, int n) { std::lock_guard<std::mutex> lock(mLock); dirty(MAT_DATA); return uniforms().setFloatVec(name, val, n); } bool ShaderData::getFloatVec(const char* name, float* val, int n) { return uniforms().getFloatVec(name, val, n); } bool ShaderData::getIntVec(const char* name, int* val, int n) { return uniforms().getIntVec(name, val, n); } bool ShaderData::setVec2(const char* name, const glm::vec2& v) { std::lock_guard<std::mutex> lock(mLock); return uniforms().setVec2(name, v); } bool ShaderData::setVec3(const char* name, const glm::vec3& v) { std::lock_guard<std::mutex> lock(mLock); return uniforms().setVec3(name, v); } bool ShaderData::setVec4(const char* name, const glm::vec4& v) { std::lock_guard<std::mutex> lock(mLock); return uniforms().setVec4(name, v); } bool ShaderData::setMat4(const char* name, const glm::mat4& m) { std::lock_guard<std::mutex> lock(mLock); return uniforms().setMat4(name, m); } void ShaderData::add_dirty_flag(const std::shared_ptr<u_short>& dirty_flag) { mDirtyFlags.insert(dirty_flag); } void ShaderData::add_dirty_flags(const std::unordered_set<std::shared_ptr<u_short>>& dirty_flags) { mDirtyFlags.insert(dirty_flags.begin(), dirty_flags.end()); } void ShaderData::dirty(DIRTY_BITS bit) { dirtyImpl(mDirtyFlags,bit); } bool ShaderData::hasTexture(const char* key) const { for (auto it = mTextureNames.begin(); it < mTextureNames.end(); ++it) { if (*it == key) { return true; } } return false; } bool ShaderData::hasUniform(const char* key) const { return (uniforms().getByteSize(key) > 0); } /** * Updates the values of the uniforms and textures * by copying the relevant data from the CPU to the GPU. * This function operates independently of the shader, * so it cannot tell if a texture the shader requires * is missing. * @param renderer * @return 1 = success, -1 texture not ready, 0 uniforms failed to load */ int ShaderData::updateGPU(Renderer* renderer) { std::lock_guard<std::mutex> lock(mLock); for (auto it = mTextures.begin(); it != mTextures.end(); ++it) { Texture *tex = *it; if (tex != NULL) { bool ready = tex->isReady(); if (Shader::LOG_SHADER) { const std::string& name = mTextureNames[it - mTextures.begin()]; LOGV("ShaderData::updateGPU %s is %s", name.c_str(), ready ? "ready" : "not ready"); } if (!ready) { return -1; } } } return 1; } } <commit_msg>fix screen shot shader, texturing bug<commit_after>/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "glm/glm.hpp" #include "glm/gtc/type_ptr.hpp" #include "shaders/shader.h" #include "shader_data.h" namespace gvr { /** * Constructs a bnse material. * The material contains a UniformBlock describing the possible uniforms * that can be used by this material. It also maintains the list of * possible textures in the order specified by the descriptor. * All materials which use the same shader will have the same ordering * of uniforms and textures in their descriptors. * @param uniform_desc string describing uniforms used by this material * @param texture_desc string describing textures used by this material */ ShaderData::ShaderData(const char* texture_desc) : mNativeShader(0), mTextureDesc(texture_desc), mLock() { DataDescriptor texdesc(texture_desc); texdesc.forEach([this](const char* name, const char* type, int size) mutable { mTextureNames.push_back(name); mTextures.push_back(nullptr); }); } Texture* ShaderData::getTexture(const char* key) const { for (auto it = mTextureNames.begin(); it < mTextureNames.end(); ++it) { if (*it == key) { return mTextures[it - mTextureNames.begin()]; } } return NULL; } void ShaderData::setTexture(const char* key, Texture* texture) { std::lock_guard<std::mutex> lock(mLock); for (auto it = mTextureNames.begin(); it < mTextureNames.end(); ++it) { const std::string& temp = *it; if (temp.compare(key) == 0) { int i = it - mTextureNames.begin(); Texture* oldtex = mTextures[i]; dirty(oldtex ? MOD_TEXTURE : NEW_TEXTURE); mTextures[i] = texture; return; } } } /** * Visits each texture in the material and calls the given function. */ void ShaderData::forEachTexture(std::function< void(const char* texname, Texture* tex) > func) const { std::lock_guard<std::mutex> lock(mLock); for (int i = 0; i < mTextureNames.size(); ++i) { Texture* tex = mTextures[i]; const std::string& name = mTextureNames[i]; func(name.c_str(), tex); } } std::string ShaderData::makeShaderLayout() { return uniforms().makeShaderLayout(); } int ShaderData::getByteSize(const char* name) const { return uniforms().getByteSize(name); } const char* ShaderData::getUniformDescriptor() const { return uniforms().getDescriptor(); } const char* ShaderData::getTextureDescriptor() const { return mTextureDesc.c_str(); } bool ShaderData::getFloat(const char* name, float& v) const { return uniforms().getFloat(name, v); } bool ShaderData::getInt(const char* name, int& v) const { return uniforms().getInt(name, v); } bool ShaderData::setInt(const char* name, int val) { std::lock_guard<std::mutex> lock(mLock); dirty(MAT_DATA); return uniforms().setInt(name, val); } bool ShaderData::setFloat(const char* name, float val) { std::lock_guard<std::mutex> lock(mLock); dirty(MAT_DATA); return uniforms().setFloat(name, val); } bool ShaderData::setIntVec(const char* name, const int* val, int n) { std::lock_guard<std::mutex> lock(mLock); dirty(MAT_DATA); return uniforms().setIntVec(name, val, n); } bool ShaderData::setFloatVec(const char* name, const float* val, int n) { std::lock_guard<std::mutex> lock(mLock); dirty(MAT_DATA); return uniforms().setFloatVec(name, val, n); } bool ShaderData::getFloatVec(const char* name, float* val, int n) { return uniforms().getFloatVec(name, val, n); } bool ShaderData::getIntVec(const char* name, int* val, int n) { return uniforms().getIntVec(name, val, n); } bool ShaderData::setVec2(const char* name, const glm::vec2& v) { std::lock_guard<std::mutex> lock(mLock); return uniforms().setVec2(name, v); } bool ShaderData::setVec3(const char* name, const glm::vec3& v) { std::lock_guard<std::mutex> lock(mLock); return uniforms().setVec3(name, v); } bool ShaderData::setVec4(const char* name, const glm::vec4& v) { std::lock_guard<std::mutex> lock(mLock); return uniforms().setVec4(name, v); } bool ShaderData::setMat4(const char* name, const glm::mat4& m) { std::lock_guard<std::mutex> lock(mLock); return uniforms().setMat4(name, m); } void ShaderData::add_dirty_flag(const std::shared_ptr<u_short>& dirty_flag) { mDirtyFlags.insert(dirty_flag); } void ShaderData::add_dirty_flags(const std::unordered_set<std::shared_ptr<u_short>>& dirty_flags) { mDirtyFlags.insert(dirty_flags.begin(), dirty_flags.end()); } void ShaderData::dirty(DIRTY_BITS bit) { dirtyImpl(mDirtyFlags,bit); } bool ShaderData::hasTexture(const char* key) const { for (auto it = mTextureNames.begin(); it < mTextureNames.end(); ++it) { if (*it == key) { return true; } } return false; } bool ShaderData::hasUniform(const char* key) const { return (uniforms().getByteSize(key) > 0); } /** * Updates the values of the uniforms and textures * by copying the relevant data from the CPU to the GPU. * This function operates independently of the shader, * so it cannot tell if a texture the shader requires * is missing. * @param renderer * @return 1 = success, -1 texture not ready, 0 uniforms failed to load */ int ShaderData::updateGPU(Renderer* renderer) { std::lock_guard<std::mutex> lock(mLock); for (auto it = mTextures.begin(); it != mTextures.end(); ++it) { Texture *tex = *it; if (tex != NULL) { bool ready = tex->isReady(); if (Shader::LOG_SHADER) { const std::string& name = mTextureNames[it - mTextures.begin()]; LOGV("ShaderData::updateGPU %s is %s", name.c_str(), ready ? "ready" : "not ready"); } if (!ready) { return -1; } } } return (uniforms().updateGPU(renderer) ? 1 : 0); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Google Inc. 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 "config.h" #include "WebImage.h" #include "WebData.h" #include "WebSize.h" #include "Image.h" #include "ImageSource.h" #include "NativeImageSkia.h" #include "SharedBuffer.h" #include <wtf/OwnPtr.h> #include <wtf/PassRefPtr.h> using namespace WebCore; namespace WebKit { WebImage WebImage::fromData(const WebData& data, const WebSize& desiredSize) { ImageSource source; source.setData(PassRefPtr<SharedBuffer>(data).get(), true); if (!source.isSizeAvailable()) return WebImage(); // Frames are arranged by decreasing size, then decreasing bit depth. // Pick the frame closest to |desiredSize|'s area without being smaller, // which has the highest bit depth. const size_t frameCount = source.frameCount(); size_t index; int frameAreaAtIndex; for (size_t i = 0; i < frameCount; ++i) { const IntSize frameSize = source.frameSizeAtIndex(i); if (WebSize(frameSize) == desiredSize) { index = i; break; // Perfect match. } const int frameArea = frameSize.width() * frameSize.height(); if (frameArea < (desiredSize.width * desiredSize.height)) break; // No more frames that are large enough. if ((i == 0) || (frameArea < frameAreaAtIndex)) { index = i; // Closer to desired area than previous best match. frameAreaAtIndex = frameArea; } } OwnPtr<NativeImageSkia> frame(source.createFrameAtIndex(index)); if (!frame.get()) return WebImage(); return WebImage(*frame); } void WebImage::reset() { m_bitmap.reset(); } void WebImage::assign(const WebImage& image) { m_bitmap = image.m_bitmap; } bool WebImage::isNull() const { return m_bitmap.isNull(); } WebSize WebImage::size() const { return WebSize(m_bitmap.width(), m_bitmap.height()); } WebImage::WebImage(const PassRefPtr<Image>& image) { operator=(image); } WebImage& WebImage::operator=(const PassRefPtr<Image>& image) { NativeImagePtr p; if (image.get() && (p = image->nativeImageForCurrentFrame())) assign(*p); else reset(); return *this; } } // namespace WebKit <commit_msg>Fix possible uninitialized variable if all frames in the .ico are smaller than the desired size.<commit_after>/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Google Inc. 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 "config.h" #include "WebImage.h" #include "WebData.h" #include "WebSize.h" #include "Image.h" #include "ImageSource.h" #include "NativeImageSkia.h" #include "SharedBuffer.h" #include <wtf/OwnPtr.h> #include <wtf/PassRefPtr.h> using namespace WebCore; namespace WebKit { WebImage WebImage::fromData(const WebData& data, const WebSize& desiredSize) { ImageSource source; source.setData(PassRefPtr<SharedBuffer>(data).get(), true); if (!source.isSizeAvailable()) return WebImage(); // Frames are arranged by decreasing size, then decreasing bit depth. // Pick the frame closest to |desiredSize|'s area without being smaller, // which has the highest bit depth. const size_t frameCount = source.frameCount(); size_t index = 0; // Default to first frame if none are large enough. int frameAreaAtIndex; for (size_t i = 0; i < frameCount; ++i) { const IntSize frameSize = source.frameSizeAtIndex(i); if (WebSize(frameSize) == desiredSize) { index = i; break; // Perfect match. } const int frameArea = frameSize.width() * frameSize.height(); if (frameArea < (desiredSize.width * desiredSize.height)) break; // No more frames that are large enough. if ((i == 0) || (frameArea < frameAreaAtIndex)) { index = i; // Closer to desired area than previous best match. frameAreaAtIndex = frameArea; } } OwnPtr<NativeImageSkia> frame(source.createFrameAtIndex(index)); if (!frame.get()) return WebImage(); return WebImage(*frame); } void WebImage::reset() { m_bitmap.reset(); } void WebImage::assign(const WebImage& image) { m_bitmap = image.m_bitmap; } bool WebImage::isNull() const { return m_bitmap.isNull(); } WebSize WebImage::size() const { return WebSize(m_bitmap.width(), m_bitmap.height()); } WebImage::WebImage(const PassRefPtr<Image>& image) { operator=(image); } WebImage& WebImage::operator=(const PassRefPtr<Image>& image) { NativeImagePtr p; if (image.get() && (p = image->nativeImageForCurrentFrame())) assign(*p); else reset(); return *this; } } // namespace WebKit <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "config.h" #include "base/compiler_specific.h" #include "KeyboardCodes.h" #include "StringImpl.h" // This is so that the KJS build works MSVC_PUSH_WARNING_LEVEL(0); #include "PlatformKeyboardEvent.h" #include "PlatformMouseEvent.h" #include "PlatformWheelEvent.h" #include "Widget.h" MSVC_POP_WARNING(); #undef LOG #include "base/gfx/point.h" #include "base/logging.h" #include "webkit/glue/event_conversion.h" #include "webkit/glue/webinputevent.h" #include "webkit/glue/webkit_glue.h" using namespace WebCore; // MakePlatformMouseEvent ----------------------------------------------------- int MakePlatformMouseEvent::last_click_count_ = 0; uint32 MakePlatformMouseEvent::last_click_time_ = 0; MakePlatformMouseEvent::MakePlatformMouseEvent(Widget* widget, const WebMouseEvent& e) { // TODO(mpcomplete): widget is always toplevel, unless it's a popup. We // may be able to get rid of this once we abstract popups into a WebKit API. m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y)); m_globalPosition = IntPoint(e.global_x, e.global_y); m_button = static_cast<MouseButton>(e.button); m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; m_modifierFlags = e.modifiers; m_timestamp = e.timestamp_sec; // This differs slightly from the WebKit code in WebKit/win/WebView.cpp where // their original code looks buggy. static IntPoint last_click_position; static MouseButton last_click_button = LeftButton; const uint32 current_time = static_cast<uint32>(m_timestamp * 1000); #if defined(OS_WIN) const bool cancel_previous_click = (abs(last_click_position.x() - m_position.x()) > (GetSystemMetrics(SM_CXDOUBLECLK) / 2)) || (abs(last_click_position.y() - m_position.y()) > (GetSystemMetrics(SM_CYDOUBLECLK) / 2)) || ((current_time - last_click_time_) > GetDoubleClickTime()); #elif defined(OS_MACOSX) || defined(OS_LINUX) const bool cancel_previous_click = false; #endif switch (e.type) { case WebInputEvent::MOUSE_MOVE: case WebInputEvent::MOUSE_LEAVE: // synthesize a move event if (cancel_previous_click) { last_click_count_ = 0; last_click_position = IntPoint(); last_click_time_ = 0; } m_clickCount = last_click_count_; m_eventType = MouseEventMoved; break; // TODO(port): make these platform agnostic when we restructure this code. #if defined(OS_LINUX) || defined(OS_MACOSX) case WebInputEvent::MOUSE_DOUBLE_CLICK: ++m_clickCount; // fall through case WebInputEvent::MOUSE_DOWN: ++m_clickCount; last_click_time_ = current_time; last_click_button = m_button; m_eventType = MouseEventPressed; break; #else case WebInputEvent::MOUSE_DOWN: case WebInputEvent::MOUSE_DOUBLE_CLICK: if (!cancel_previous_click && (m_button == last_click_button)) { ++last_click_count_; } else { last_click_count_ = 1; last_click_position = m_position; } last_click_time_ = current_time; last_click_button = m_button; m_clickCount = last_click_count_; m_eventType = MouseEventPressed; break; #endif case WebInputEvent::MOUSE_UP: m_clickCount = last_click_count_; m_eventType = MouseEventReleased; break; default: NOTREACHED() << "unexpected mouse event type"; } if (webkit_glue::IsLayoutTestMode()) { m_clickCount = e.layout_test_click_count; } } // MakePlatformWheelEvent ----------------------------------------------------- MakePlatformWheelEvent::MakePlatformWheelEvent(Widget* widget, const WebMouseWheelEvent& e) { m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y)); m_globalPosition = IntPoint(e.global_x, e.global_y); m_deltaX = static_cast<float>(e.delta_x); m_deltaY = static_cast<float>(e.delta_y); m_isAccepted = false; m_granularity = ScrollByLineWheelEvent; m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; } // MakePlatformKeyboardEvent -------------------------------------------------- static inline const PlatformKeyboardEvent::Type ToPlatformKeyboardEventType( WebInputEvent::Type type) { switch (type) { case WebInputEvent::KEY_UP: return PlatformKeyboardEvent::KeyUp; case WebInputEvent::KEY_DOWN: return PlatformKeyboardEvent::KeyDown; case WebInputEvent::CHAR: return PlatformKeyboardEvent::Char; default: ASSERT_NOT_REACHED(); } return PlatformKeyboardEvent::KeyDown; } static inline String ToSingleCharacterString(UChar c) { return String(&c, 1); } static String GetKeyIdentifierForWindowsKeyCode(unsigned short keyCode) { switch (keyCode) { case VKEY_MENU: return "Alt"; case VKEY_CONTROL: return "Control"; case VKEY_SHIFT: return "Shift"; case VKEY_CAPITAL: return "CapsLock"; case VKEY_LWIN: case VKEY_RWIN: return "Win"; case VKEY_CLEAR: return "Clear"; case VKEY_DOWN: return "Down"; // "End" case VKEY_END: return "End"; // "Enter" case VKEY_RETURN: return "Enter"; case VKEY_EXECUTE: return "Execute"; case VKEY_F1: return "F1"; case VKEY_F2: return "F2"; case VKEY_F3: return "F3"; case VKEY_F4: return "F4"; case VKEY_F5: return "F5"; case VKEY_F6: return "F6"; case VKEY_F7: return "F7"; case VKEY_F8: return "F8"; case VKEY_F9: return "F9"; case VKEY_F10: return "F11"; case VKEY_F12: return "F12"; case VKEY_F13: return "F13"; case VKEY_F14: return "F14"; case VKEY_F15: return "F15"; case VKEY_F16: return "F16"; case VKEY_F17: return "F17"; case VKEY_F18: return "F18"; case VKEY_F19: return "F19"; case VKEY_F20: return "F20"; case VKEY_F21: return "F21"; case VKEY_F22: return "F22"; case VKEY_F23: return "F23"; case VKEY_F24: return "F24"; case VKEY_HELP: return "Help"; case VKEY_HOME: return "Home"; case VKEY_INSERT: return "Insert"; case VKEY_LEFT: return "Left"; case VKEY_NEXT: return "PageDown"; case VKEY_PRIOR: return "PageUp"; case VKEY_PAUSE: return "Pause"; case VKEY_SNAPSHOT: return "PrintScreen"; case VKEY_RIGHT: return "Right"; case VKEY_SCROLL: return "Scroll"; case VKEY_SELECT: return "Select"; case VKEY_UP: return "Up"; // Standard says that DEL becomes U+007F. case VKEY_DELETE: return "U+007F"; default: return String::format("U+%04X", toupper(keyCode)); } } MakePlatformKeyboardEvent::MakePlatformKeyboardEvent(const WebKeyboardEvent& e) { m_type = ToPlatformKeyboardEventType(e.type); if (m_type == Char || m_type == KeyDown) { #if defined(OS_MACOSX) m_text = &e.text[0]; m_unmodifiedText = &e.unmodified_text[0]; m_keyIdentifier = &e.key_identifier[0]; // Always use 13 for Enter/Return -- we don't want to use AppKit's // different character for Enter. if (m_windowsVirtualKeyCode == '\r') { m_text = "\r"; m_unmodifiedText = "\r"; } // The adjustments below are only needed in backward compatibility mode, // but we cannot tell what mode we are in from here. // Turn 0x7F into 8, because backspace needs to always be 8. if (m_text == "\x7F") m_text = "\x8"; if (m_unmodifiedText == "\x7F") m_unmodifiedText = "\x8"; // Always use 9 for tab -- we don't want to use AppKit's different character for shift-tab. if (m_windowsVirtualKeyCode == 9) { m_text = "\x9"; m_unmodifiedText = "\x9"; } #elif defined(OS_WIN) || defined(OS_LINUX) m_text = m_unmodifiedText = ToSingleCharacterString(e.key_code); #endif } #if defined(OS_WIN) || defined(OS_LINUX) if (m_type != Char) m_keyIdentifier = GetKeyIdentifierForWindowsKeyCode(e.key_code); #endif if (m_type == Char || m_type == KeyDown || m_type == KeyUp || m_type == RawKeyDown) { m_windowsVirtualKeyCode = e.key_code; } else { m_windowsVirtualKeyCode = 0; } m_autoRepeat = (e.modifiers & WebInputEvent::IS_AUTO_REPEAT) != 0; m_isKeypad = (e.modifiers & WebInputEvent::IS_KEYPAD) != 0; m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; #if defined(OS_WIN) m_isSystemKey = e.system_key; // TODO(port): set this field properly for linux and mac. #elif defined(OS_LINUX) m_isSystemKey = m_altKey; #else m_isSystemKey = false; #endif } void MakePlatformKeyboardEvent::SetKeyType(Type type) { // According to the behavior of Webkit in Windows platform, // we need to convert KeyDown to RawKeydown and Char events // See WebKit/WebKit/Win/WebView.cpp ASSERT(m_type == KeyDown); ASSERT(type == RawKeyDown || type == Char); m_type = type; if (type == RawKeyDown) { m_text = String(); m_unmodifiedText = String(); } else { m_keyIdentifier = String(); m_windowsVirtualKeyCode = 0; } } // Please refer to bug http://b/issue?id=961192, which talks about Webkit // keyboard event handling changes. It also mentions the list of keys // which don't have associated character events. bool MakePlatformKeyboardEvent::IsCharacterKey() const { switch (windowsVirtualKeyCode()) { case VKEY_BACK: case VKEY_ESCAPE: return false; default: break; } return true; } <commit_msg>Undo part of issue 12981.<commit_after>// Copyright (c) 2006-2008 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 "config.h" #include "base/compiler_specific.h" #include "KeyboardCodes.h" #include "StringImpl.h" // This is so that the KJS build works MSVC_PUSH_WARNING_LEVEL(0); #include "PlatformKeyboardEvent.h" #include "PlatformMouseEvent.h" #include "PlatformWheelEvent.h" #include "Widget.h" MSVC_POP_WARNING(); #undef LOG #include "base/gfx/point.h" #include "base/logging.h" #include "webkit/glue/event_conversion.h" #include "webkit/glue/webinputevent.h" #include "webkit/glue/webkit_glue.h" using namespace WebCore; // MakePlatformMouseEvent ----------------------------------------------------- int MakePlatformMouseEvent::last_click_count_ = 0; uint32 MakePlatformMouseEvent::last_click_time_ = 0; MakePlatformMouseEvent::MakePlatformMouseEvent(Widget* widget, const WebMouseEvent& e) { // TODO(mpcomplete): widget is always toplevel, unless it's a popup. We // may be able to get rid of this once we abstract popups into a WebKit API. m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y)); m_globalPosition = IntPoint(e.global_x, e.global_y); m_button = static_cast<MouseButton>(e.button); m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; m_modifierFlags = e.modifiers; m_timestamp = e.timestamp_sec; // This differs slightly from the WebKit code in WebKit/win/WebView.cpp where // their original code looks buggy. static IntPoint last_click_position; static MouseButton last_click_button = LeftButton; const uint32 current_time = static_cast<uint32>(m_timestamp * 1000); #if defined(OS_WIN) const bool cancel_previous_click = (abs(last_click_position.x() - m_position.x()) > (GetSystemMetrics(SM_CXDOUBLECLK) / 2)) || (abs(last_click_position.y() - m_position.y()) > (GetSystemMetrics(SM_CYDOUBLECLK) / 2)) || ((current_time - last_click_time_) > GetDoubleClickTime()); #elif defined(OS_MACOSX) || defined(OS_LINUX) const bool cancel_previous_click = false; #endif switch (e.type) { case WebInputEvent::MOUSE_MOVE: case WebInputEvent::MOUSE_LEAVE: // synthesize a move event if (cancel_previous_click) { last_click_count_ = 0; last_click_position = IntPoint(); last_click_time_ = 0; } m_clickCount = last_click_count_; m_eventType = MouseEventMoved; break; // TODO(port): make these platform agnostic when we restructure this code. #if defined(OS_LINUX) || defined(OS_MACOSX) case WebInputEvent::MOUSE_DOUBLE_CLICK: ++m_clickCount; // fall through case WebInputEvent::MOUSE_DOWN: ++m_clickCount; last_click_time_ = current_time; last_click_button = m_button; m_eventType = MouseEventPressed; break; #else case WebInputEvent::MOUSE_DOWN: case WebInputEvent::MOUSE_DOUBLE_CLICK: if (!cancel_previous_click && (m_button == last_click_button)) { ++last_click_count_; } else { last_click_count_ = 1; last_click_position = m_position; } last_click_time_ = current_time; last_click_button = m_button; m_clickCount = last_click_count_; m_eventType = MouseEventPressed; break; #endif case WebInputEvent::MOUSE_UP: m_clickCount = last_click_count_; m_eventType = MouseEventReleased; break; default: NOTREACHED() << "unexpected mouse event type"; } if (webkit_glue::IsLayoutTestMode()) { m_clickCount = e.layout_test_click_count; } } // MakePlatformWheelEvent ----------------------------------------------------- MakePlatformWheelEvent::MakePlatformWheelEvent(Widget* widget, const WebMouseWheelEvent& e) { m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y)); m_globalPosition = IntPoint(e.global_x, e.global_y); m_deltaX = static_cast<float>(e.delta_x); m_deltaY = static_cast<float>(e.delta_y); m_isAccepted = false; m_granularity = ScrollByLineWheelEvent; m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; } // MakePlatformKeyboardEvent -------------------------------------------------- static inline const PlatformKeyboardEvent::Type ToPlatformKeyboardEventType( WebInputEvent::Type type) { switch (type) { case WebInputEvent::KEY_UP: return PlatformKeyboardEvent::KeyUp; case WebInputEvent::KEY_DOWN: return PlatformKeyboardEvent::KeyDown; case WebInputEvent::CHAR: return PlatformKeyboardEvent::Char; default: ASSERT_NOT_REACHED(); } return PlatformKeyboardEvent::KeyDown; } static inline String ToSingleCharacterString(UChar c) { return String(&c, 1); } static String GetKeyIdentifierForWindowsKeyCode(unsigned short keyCode) { switch (keyCode) { case VKEY_MENU: return "Alt"; case VKEY_CONTROL: return "Control"; case VKEY_SHIFT: return "Shift"; case VKEY_CAPITAL: return "CapsLock"; case VKEY_LWIN: case VKEY_RWIN: return "Win"; case VKEY_CLEAR: return "Clear"; case VKEY_DOWN: return "Down"; // "End" case VKEY_END: return "End"; // "Enter" case VKEY_RETURN: return "Enter"; case VKEY_EXECUTE: return "Execute"; case VKEY_F1: return "F1"; case VKEY_F2: return "F2"; case VKEY_F3: return "F3"; case VKEY_F4: return "F4"; case VKEY_F5: return "F5"; case VKEY_F6: return "F6"; case VKEY_F7: return "F7"; case VKEY_F8: return "F8"; case VKEY_F9: return "F9"; case VKEY_F10: return "F11"; case VKEY_F12: return "F12"; case VKEY_F13: return "F13"; case VKEY_F14: return "F14"; case VKEY_F15: return "F15"; case VKEY_F16: return "F16"; case VKEY_F17: return "F17"; case VKEY_F18: return "F18"; case VKEY_F19: return "F19"; case VKEY_F20: return "F20"; case VKEY_F21: return "F21"; case VKEY_F22: return "F22"; case VKEY_F23: return "F23"; case VKEY_F24: return "F24"; case VKEY_HELP: return "Help"; case VKEY_HOME: return "Home"; case VKEY_INSERT: return "Insert"; case VKEY_LEFT: return "Left"; case VKEY_NEXT: return "PageDown"; case VKEY_PRIOR: return "PageUp"; case VKEY_PAUSE: return "Pause"; case VKEY_SNAPSHOT: return "PrintScreen"; case VKEY_RIGHT: return "Right"; case VKEY_SCROLL: return "Scroll"; case VKEY_SELECT: return "Select"; case VKEY_UP: return "Up"; // Standard says that DEL becomes U+007F. case VKEY_DELETE: return "U+007F"; default: return String::format("U+%04X", toupper(keyCode)); } } MakePlatformKeyboardEvent::MakePlatformKeyboardEvent(const WebKeyboardEvent& e) { m_type = ToPlatformKeyboardEventType(e.type); if (m_type == Char || m_type == KeyDown) { #if defined(OS_MACOSX) m_text = &e.text[0]; m_unmodifiedText = &e.unmodified_text[0]; m_keyIdentifier = &e.key_identifier[0]; // Always use 13 for Enter/Return -- we don't want to use AppKit's // different character for Enter. if (m_windowsVirtualKeyCode == '\r') { m_text = "\r"; m_unmodifiedText = "\r"; } // The adjustments below are only needed in backward compatibility mode, // but we cannot tell what mode we are in from here. // Turn 0x7F into 8, because backspace needs to always be 8. if (m_text == "\x7F") m_text = "\x8"; if (m_unmodifiedText == "\x7F") m_unmodifiedText = "\x8"; // Always use 9 for tab -- we don't want to use AppKit's different character for shift-tab. if (m_windowsVirtualKeyCode == 9) { m_text = "\x9"; m_unmodifiedText = "\x9"; } #elif defined(OS_WIN) m_text = m_unmodifiedText = ToSingleCharacterString(e.key_code); #elif defined(OS_LINUX) m_text = m_unmodifiedText = ToSingleCharacterString(e.text); #endif } #if defined(OS_WIN) || defined(OS_LINUX) if (m_type != Char) m_keyIdentifier = GetKeyIdentifierForWindowsKeyCode(e.key_code); #endif if (m_type == Char || m_type == KeyDown || m_type == KeyUp || m_type == RawKeyDown) { m_windowsVirtualKeyCode = e.key_code; } else { m_windowsVirtualKeyCode = 0; } m_autoRepeat = (e.modifiers & WebInputEvent::IS_AUTO_REPEAT) != 0; m_isKeypad = (e.modifiers & WebInputEvent::IS_KEYPAD) != 0; m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; #if defined(OS_WIN) m_isSystemKey = e.system_key; // TODO(port): set this field properly for linux and mac. #elif defined(OS_LINUX) m_isSystemKey = m_altKey; #else m_isSystemKey = false; #endif } void MakePlatformKeyboardEvent::SetKeyType(Type type) { // According to the behavior of Webkit in Windows platform, // we need to convert KeyDown to RawKeydown and Char events // See WebKit/WebKit/Win/WebView.cpp ASSERT(m_type == KeyDown); ASSERT(type == RawKeyDown || type == Char); m_type = type; if (type == RawKeyDown) { m_text = String(); m_unmodifiedText = String(); } else { m_keyIdentifier = String(); m_windowsVirtualKeyCode = 0; } } // Please refer to bug http://b/issue?id=961192, which talks about Webkit // keyboard event handling changes. It also mentions the list of keys // which don't have associated character events. bool MakePlatformKeyboardEvent::IsCharacterKey() const { switch (windowsVirtualKeyCode()) { case VKEY_BACK: case VKEY_ESCAPE: return false; default: break; } return true; } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright © 2018-2019 Ruben Van Boxem * * 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 "css/parser.h++" #include "css/grammar.h++" #include <core/debug.h++> #include <boost/spirit/home/x3/core/parse.hpp> #include <unordered_map> namespace skui::css { declaration_block parser::parse(const skui::core::string& input) { using boost::spirit::x3::phrase_parse; using boost::spirit::x3::space; declaration_block result; bool success = phrase_parse(input.begin(), input.end(), grammar::declaration_block,//grammar::rule_set, space, result); core::debug_print("parse success: ", success, '\n'); return result; } } <commit_msg>Comment out test that fails to compile on VS.<commit_after>/** * The MIT License (MIT) * * Copyright © 2018-2019 Ruben Van Boxem * * 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 "css/parser.h++" #include "css/grammar.h++" #include <core/debug.h++> #include <boost/spirit/home/x3/core/parse.hpp> #include <unordered_map> /* namespace skui::css { declaration_block parser::parse(const skui::core::string& input) { using boost::spirit::x3::phrase_parse; using boost::spirit::x3::space; declaration_block result; bool success = phrase_parse(input.begin(), input.end(), grammar::declaration_block,//grammar::rule_set, space, result); core::debug_print("parse success: ", success, '\n'); return result; } } */ <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2019 The Khronos Group 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. * *//*! * \file * \brief SPIR-V Assembly Tests for indexing with access chain operations. *//*--------------------------------------------------------------------*/ #include "vktSpvAsmFromHlslTests.hpp" #include "vktTestCaseUtil.hpp" #include "vkPrograms.hpp" #include "vkObjUtil.hpp" #include "vkRefUtil.hpp" #include "vkTypeUtil.hpp" #include "vkQueryUtil.hpp" #include "vkBuilderUtil.hpp" #include "vkBarrierUtil.hpp" #include "vkCmdUtil.hpp" namespace vkt { namespace SpirVAssembly { namespace { using namespace vk; enum TestType { TT_CBUFFER_PACKING = 0, }; struct TestConfig { TestType type; }; struct Programs { void init (vk::SourceCollections& dst, TestConfig config) const { if (config.type == TT_CBUFFER_PACKING) { // HLSL shaders has a packing corner case that GLSL shaders cannot exhibit. // Below shader, foo has an ArrayStride of 16, which leaves bar effectively // 'within' the end of the foo array. This is entirely valid for HLSL and // with the VK_EXT_scalar_block_layout extension. std::string source( "cbuffer cbIn\n" "{\n" " int foo[2] : packoffset(c0);\n" " int bar : packoffset(c1.y);\n" "};\n" "RWStructuredBuffer<int> result : register(u1);\n" "[numthreads(1, 1, 1)]\n" "void main(uint3 dispatchThreadID : SV_DispatchThreadID)\n" "{\n" " result[0] = bar;\n" "}\n"); dst.hlslSources.add("comp") << glu::ComputeSource(source) << vk::ShaderBuildOptions(dst.usedVulkanVersion, vk::SPIRV_VERSION_1_0, vk::ShaderBuildOptions::FLAG_ALLOW_SCALAR_OFFSETS); } } }; class HlslTest : public TestInstance { public: HlslTest (Context& context, TestConfig config); virtual ~HlslTest (void) = default; tcu::TestStatus iterate (void); }; HlslTest::HlslTest(Context& context, TestConfig config) : TestInstance(context) { DE_UNREF(config); } tcu::TestStatus HlslTest::iterate(void) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice device = m_context.getDevice(); const VkQueue queue = m_context.getUniversalQueue(); const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex(); Allocator& allocator = m_context.getDefaultAllocator(); const int testValue = 5; // Create an input buffer const VkBufferUsageFlags inBufferUsageFlags = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; const VkDeviceSize inBufferSizeBytes = 32; // 2 element array with 16B stride VkBufferCreateInfo inBufferCreateInfo = makeBufferCreateInfo(inBufferSizeBytes, inBufferUsageFlags); vk::Move<vk::VkBuffer> inBuffer = createBuffer(vk, device, &inBufferCreateInfo); de::MovePtr<vk::Allocation> inAllocation = allocator.allocate(getBufferMemoryRequirements(vk, device, *inBuffer), MemoryRequirement::HostVisible); VK_CHECK(vk.bindBufferMemory(device, *inBuffer, inAllocation->getMemory(), inAllocation->getOffset())); // Fill the input structure with data - first attribute is array that has 16B stride, // this means that second attribute has to start at offset 20B (4B + 16B) { int* bufferPtr = static_cast<int*>(inAllocation->getHostPtr()); memset(bufferPtr, 0, inBufferSizeBytes); bufferPtr[5] = testValue; flushAlloc(vk, device, *inAllocation); } // Create an output buffer const VkBufferUsageFlags outBufferUsageFlags = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; const VkDeviceSize outBufferSizeBytes = sizeof(int); VkBufferCreateInfo outBufferCreateInfo = makeBufferCreateInfo(outBufferSizeBytes, outBufferUsageFlags); vk::Move<vk::VkBuffer> outBuffer = createBuffer(vk, device, &outBufferCreateInfo); de::MovePtr<vk::Allocation> outAllocation = allocator.allocate(getBufferMemoryRequirements(vk, device, *outBuffer), MemoryRequirement::HostVisible); VK_CHECK(vk.bindBufferMemory(device, *outBuffer, outAllocation->getMemory(), outAllocation->getOffset())); // Create descriptor set const VkDescriptorType uniBufDesc = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; const VkDescriptorType storBufDesc = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; const Unique<VkDescriptorSetLayout> descriptorSetLayout( DescriptorSetLayoutBuilder() .addSingleBinding(uniBufDesc, VK_SHADER_STAGE_COMPUTE_BIT) .addSingleBinding(storBufDesc, VK_SHADER_STAGE_COMPUTE_BIT) .build(vk, device)); const Unique<VkDescriptorPool> descriptorPool( DescriptorPoolBuilder() .addType(uniBufDesc) .addType(storBufDesc) .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u)); const Unique<VkDescriptorSet> descriptorSet(makeDescriptorSet(vk, device, *descriptorPool, *descriptorSetLayout)); const VkDescriptorBufferInfo inputBufferDescriptorInfo = makeDescriptorBufferInfo(*inBuffer, 0ull, inBufferSizeBytes); const VkDescriptorBufferInfo outputBufferDescriptorInfo = makeDescriptorBufferInfo(*outBuffer, 0ull, outBufferSizeBytes); DescriptorSetUpdateBuilder() .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), uniBufDesc, &inputBufferDescriptorInfo) .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), storBufDesc, &outputBufferDescriptorInfo) .update(vk, device); // Perform the computation const Unique<VkShaderModule> shaderModule(createShaderModule(vk, device, m_context.getBinaryCollection().get("comp"), 0u)); const Unique<VkPipelineLayout> pipelineLayout(makePipelineLayout(vk, device, *descriptorSetLayout)); const VkPipelineShaderStageCreateInfo pipelineShaderStageParams = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, DE_NULL, static_cast<VkPipelineShaderStageCreateFlags>(0u), VK_SHADER_STAGE_COMPUTE_BIT, *shaderModule, "main", DE_NULL, }; const VkComputePipelineCreateInfo pipelineCreateInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, DE_NULL, static_cast<VkPipelineCreateFlags>(0u), pipelineShaderStageParams, *pipelineLayout, DE_NULL, 0, }; Unique<VkPipeline> pipeline(createComputePipeline(vk, device, DE_NULL, &pipelineCreateInfo)); const VkBufferMemoryBarrier hostWriteBarrier = makeBufferMemoryBarrier(VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, *inBuffer, 0ull, inBufferSizeBytes); const VkBufferMemoryBarrier shaderWriteBarrier = makeBufferMemoryBarrier(VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, *outBuffer, 0ull, outBufferSizeBytes); const Unique<VkCommandPool> cmdPool(makeCommandPool(vk, device, queueFamilyIndex)); const Unique<VkCommandBuffer> cmdBuffer(allocateCommandBuffer(vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY)); // Start recording commands beginCommandBuffer(vk, *cmdBuffer); vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); vk.cmdBindDescriptorSets(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineLayout, 0u, 1u, &descriptorSet.get(), 0u, DE_NULL); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &hostWriteBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL); vk.cmdDispatch(*cmdBuffer, 1, 1, 1); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &shaderWriteBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL); endCommandBuffer(vk, *cmdBuffer); // Wait for completion submitCommandsAndWait(vk, device, queue, *cmdBuffer); // Validate the results invalidateAlloc(vk, device, *outAllocation); const int* bufferPtr = static_cast<int*>(outAllocation->getHostPtr()); if (*bufferPtr != testValue) return tcu::TestStatus::fail("Fail"); return tcu::TestStatus::pass("Pass"); } } // anonymous tcu::TestCaseGroup* createHlslComputeGroup (tcu::TestContext& testCtx) { typedef InstanceFactory1<HlslTest, TestConfig, Programs> HlslTestInstance; de::MovePtr<tcu::TestCaseGroup> hlslCasesGroup(new tcu::TestCaseGroup(testCtx, "hlsl_cases", "")); TestConfig testConfig = { TT_CBUFFER_PACKING }; hlslCasesGroup->addChild(new HlslTestInstance(testCtx, tcu::NODETYPE_SELF_VALIDATE, "cbuffer_packing", "", testConfig)); return hlslCasesGroup.release(); } } // SpirVAssembly } // vkt <commit_msg>Fix cbuffer packing test<commit_after>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2019 The Khronos Group 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. * *//*! * \file * \brief SPIR-V Assembly Tests for indexing with access chain operations. *//*--------------------------------------------------------------------*/ #include "vktSpvAsmFromHlslTests.hpp" #include "vktTestCaseUtil.hpp" #include "vkPrograms.hpp" #include "vkObjUtil.hpp" #include "vkRefUtil.hpp" #include "vkTypeUtil.hpp" #include "vkQueryUtil.hpp" #include "vkBuilderUtil.hpp" #include "vkBarrierUtil.hpp" #include "vkCmdUtil.hpp" namespace vkt { namespace SpirVAssembly { namespace { using namespace vk; enum TestType { TT_CBUFFER_PACKING = 0, }; struct TestConfig { TestType type; }; struct Programs { void init (vk::SourceCollections& dst, TestConfig config) const { if (config.type == TT_CBUFFER_PACKING) { // HLSL shaders has a packing corner case that GLSL shaders cannot exhibit. // Below shader, foo has an ArrayStride of 16, which leaves bar effectively // 'within' the end of the foo array. This is entirely valid for HLSL and // with the VK_EXT_scalar_block_layout extension. std::string source( "cbuffer cbIn\n" "{\n" " int foo[2] : packoffset(c0);\n" " int bar : packoffset(c1.y);\n" "};\n" "RWStructuredBuffer<int> result : register(u1);\n" "[numthreads(1, 1, 1)]\n" "void main(uint3 dispatchThreadID : SV_DispatchThreadID)\n" "{\n" " result[0] = bar;\n" "}\n"); dst.hlslSources.add("comp") << glu::ComputeSource(source) << vk::ShaderBuildOptions(dst.usedVulkanVersion, vk::SPIRV_VERSION_1_0, vk::ShaderBuildOptions::FLAG_ALLOW_SCALAR_OFFSETS); } } }; class HlslTest : public TestInstance { public: HlslTest (Context& context, TestConfig config); virtual ~HlslTest (void) = default; tcu::TestStatus iterate (void); }; HlslTest::HlslTest(Context& context, TestConfig config) : TestInstance(context) { DE_UNREF(config); } tcu::TestStatus HlslTest::iterate(void) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice device = m_context.getDevice(); const VkQueue queue = m_context.getUniversalQueue(); const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex(); Allocator& allocator = m_context.getDefaultAllocator(); const int testValue = 5; // Create an input buffer const VkBufferUsageFlags inBufferUsageFlags = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; const VkDeviceSize inBufferSizeBytes = 32; // 2 element array with 16B stride VkBufferCreateInfo inBufferCreateInfo = makeBufferCreateInfo(inBufferSizeBytes, inBufferUsageFlags); vk::Move<vk::VkBuffer> inBuffer = createBuffer(vk, device, &inBufferCreateInfo); de::MovePtr<vk::Allocation> inAllocation = allocator.allocate(getBufferMemoryRequirements(vk, device, *inBuffer), MemoryRequirement::HostVisible); VK_CHECK(vk.bindBufferMemory(device, *inBuffer, inAllocation->getMemory(), inAllocation->getOffset())); // Fill the input structure with data - first attribute is array that has 16B stride, // this means that second attribute has to start at offset 20B (4B + 16B) { int* bufferPtr = static_cast<int*>(inAllocation->getHostPtr()); memset(bufferPtr, 0, inBufferSizeBytes); bufferPtr[5] = testValue; flushAlloc(vk, device, *inAllocation); } // Create an output buffer const VkBufferUsageFlags outBufferUsageFlags = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; const VkDeviceSize outBufferSizeBytes = sizeof(int); VkBufferCreateInfo outBufferCreateInfo = makeBufferCreateInfo(outBufferSizeBytes, outBufferUsageFlags); vk::Move<vk::VkBuffer> outBuffer = createBuffer(vk, device, &outBufferCreateInfo); de::MovePtr<vk::Allocation> outAllocation = allocator.allocate(getBufferMemoryRequirements(vk, device, *outBuffer), MemoryRequirement::HostVisible); VK_CHECK(vk.bindBufferMemory(device, *outBuffer, outAllocation->getMemory(), outAllocation->getOffset())); // Create descriptor set const VkDescriptorType uniBufDesc = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; const VkDescriptorType storBufDesc = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; const Unique<VkDescriptorSetLayout> descriptorSetLayout( DescriptorSetLayoutBuilder() .addSingleBinding(uniBufDesc, VK_SHADER_STAGE_COMPUTE_BIT) .addSingleBinding(storBufDesc, VK_SHADER_STAGE_COMPUTE_BIT) .build(vk, device)); const Unique<VkDescriptorPool> descriptorPool( DescriptorPoolBuilder() .addType(uniBufDesc) .addType(storBufDesc) .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u)); const Unique<VkDescriptorSet> descriptorSet(makeDescriptorSet(vk, device, *descriptorPool, *descriptorSetLayout)); const VkDescriptorBufferInfo inputBufferDescriptorInfo = makeDescriptorBufferInfo(*inBuffer, 0ull, inBufferSizeBytes); const VkDescriptorBufferInfo outputBufferDescriptorInfo = makeDescriptorBufferInfo(*outBuffer, 0ull, outBufferSizeBytes); DescriptorSetUpdateBuilder() .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), uniBufDesc, &inputBufferDescriptorInfo) .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), storBufDesc, &outputBufferDescriptorInfo) .update(vk, device); // Perform the computation const Unique<VkShaderModule> shaderModule(createShaderModule(vk, device, m_context.getBinaryCollection().get("comp"), 0u)); const Unique<VkPipelineLayout> pipelineLayout(makePipelineLayout(vk, device, *descriptorSetLayout)); const VkPipelineShaderStageCreateInfo pipelineShaderStageParams = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, DE_NULL, static_cast<VkPipelineShaderStageCreateFlags>(0u), VK_SHADER_STAGE_COMPUTE_BIT, *shaderModule, "main", DE_NULL, }; const VkComputePipelineCreateInfo pipelineCreateInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, DE_NULL, static_cast<VkPipelineCreateFlags>(0u), pipelineShaderStageParams, *pipelineLayout, DE_NULL, 0, }; Unique<VkPipeline> pipeline(createComputePipeline(vk, device, DE_NULL, &pipelineCreateInfo)); const VkBufferMemoryBarrier hostWriteBarrier = makeBufferMemoryBarrier(VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, *inBuffer, 0ull, inBufferSizeBytes); const VkBufferMemoryBarrier shaderWriteBarrier = makeBufferMemoryBarrier(VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, *outBuffer, 0ull, outBufferSizeBytes); const Unique<VkCommandPool> cmdPool(makeCommandPool(vk, device, queueFamilyIndex)); const Unique<VkCommandBuffer> cmdBuffer(allocateCommandBuffer(vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY)); // Start recording commands beginCommandBuffer(vk, *cmdBuffer); vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); vk.cmdBindDescriptorSets(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineLayout, 0u, 1u, &descriptorSet.get(), 0u, DE_NULL); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &hostWriteBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL); vk.cmdDispatch(*cmdBuffer, 1, 1, 1); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &shaderWriteBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL); endCommandBuffer(vk, *cmdBuffer); // Wait for completion submitCommandsAndWait(vk, device, queue, *cmdBuffer); // Validate the results invalidateAlloc(vk, device, *outAllocation); const int* bufferPtr = static_cast<int*>(outAllocation->getHostPtr()); if (*bufferPtr != testValue) return tcu::TestStatus::fail("Fail"); return tcu::TestStatus::pass("Pass"); } void checkSupport(Context& context) { context.requireDeviceFunctionality("VK_EXT_scalar_block_layout"); } } // anonymous tcu::TestCaseGroup* createHlslComputeGroup (tcu::TestContext& testCtx) { typedef InstanceFactory1WithSupport<HlslTest, TestConfig, FunctionSupport0, Programs> HlslTestInstance; de::MovePtr<tcu::TestCaseGroup> hlslCasesGroup(new tcu::TestCaseGroup(testCtx, "hlsl_cases", "")); TestConfig testConfig = { TT_CBUFFER_PACKING }; hlslCasesGroup->addChild(new HlslTestInstance(testCtx, tcu::NODETYPE_SELF_VALIDATE, "cbuffer_packing", "", testConfig, checkSupport)); return hlslCasesGroup.release(); } } // SpirVAssembly } // vkt <|endoftext|>
<commit_before>/*=================================================================== BlueBerry Platform 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. ===================================================================*/ #include "berryHelpPluginActivator.h" #include "berryHelpContentView.h" #include "berryHelpIndexView.h" #include "berryHelpSearchView.h" #include "berryHelpEditor.h" #include "berryHelpEditorInput.h" #include "berryHelpPerspective.h" #include "berryQHelpEngineConfiguration.h" #include "berryQHelpEngineWrapper.h" #include <berryPlatformUI.h> #include <service/event/ctkEventConstants.h> #include <QtPlugin> #include <QDir> #include <QDateTime> namespace berry { class HelpPerspectiveListener : public IPerspectiveListener { public: Events::Types GetPerspectiveEventTypes() const; void PerspectiveOpened(SmartPointer<IWorkbenchPage> page, IPerspectiveDescriptor::Pointer perspective); void PerspectiveChanged(SmartPointer<IWorkbenchPage> page, IPerspectiveDescriptor::Pointer perspective, const std::string &changeId); }; class HelpWindowListener : public IWindowListener { public: HelpWindowListener(); ~HelpWindowListener(); void WindowClosed(IWorkbenchWindow::Pointer window); void WindowOpened(IWorkbenchWindow::Pointer window); private: // We use the same perspective listener for every window IPerspectiveListener::Pointer perspListener; }; HelpPluginActivator* HelpPluginActivator::instance = 0; HelpPluginActivator::HelpPluginActivator() : pluginListener(0) { this->instance = this; } HelpPluginActivator::~HelpPluginActivator() { instance = 0; } void HelpPluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(berry::HelpContentView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpIndexView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpSearchView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpEditor, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpPerspective, context) QFileInfo qhcInfo = context->getDataFile("qthelpcollection.qhc"); helpEngine.reset(new QHelpEngineWrapper(qhcInfo.absoluteFilePath())); if (!helpEngine->setupData()) { BERRY_ERROR << "QHelpEngine set-up failed: " << helpEngine->error().toStdString(); return; } helpEngineConfiguration.reset(new QHelpEngineConfiguration(context, *helpEngine.data())); delete pluginListener; pluginListener = new QCHPluginListener(context, helpEngine.data()); context->connectPluginListener(pluginListener, SLOT(pluginChanged(ctkPluginEvent))); // register all QCH files from all the currently installed plugins pluginListener->processPlugins(); helpEngine->initialDocSetupDone(); // Register a wnd listener which registers a perspective listener for each // new window. The perspective listener opens the help home page in the window // if no other help page is opened yet. wndListener = IWindowListener::Pointer(new HelpWindowListener()); PlatformUI::GetWorkbench()->AddWindowListener(wndListener); // Register an event handler for CONTEXTHELP_REQUESTED events helpContextHandler.reset(new HelpContextHandler); ctkDictionary helpHandlerProps; helpHandlerProps.insert(ctkEventConstants::EVENT_TOPIC, "org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); context->registerService<ctkEventHandler>(helpContextHandler.data(), helpHandlerProps); } void HelpPluginActivator::stop(ctkPluginContext* /*context*/) { delete pluginListener; pluginListener = 0; if (PlatformUI::IsWorkbenchRunning()) { PlatformUI::GetWorkbench()->RemoveWindowListener(wndListener); } wndListener = 0; } HelpPluginActivator *HelpPluginActivator::getInstance() { return instance; } QHelpEngineWrapper& HelpPluginActivator::getQHelpEngine() { return *helpEngine; } void HelpPluginActivator::linkActivated(IWorkbenchPage::Pointer page, const QUrl &link) { IEditorInput::Pointer input(new HelpEditorInput(link)); // see if an editor with the same input is already open IEditorPart::Pointer reuseEditor = page->FindEditor(input); if (reuseEditor) { // just activate it page->Activate(reuseEditor); } else { // reuse the currently active editor, if it is a HelpEditor reuseEditor = page->GetActiveEditor(); if (reuseEditor.IsNotNull() && page->GetReference(reuseEditor)->GetId() == HelpEditor::EDITOR_ID) { page->ReuseEditor(reuseEditor.Cast<IReusableEditor>(), input); page->Activate(reuseEditor); } else { // get the last used HelpEditor instance std::vector<IEditorReference::Pointer> editors = page->FindEditors(IEditorInput::Pointer(0), HelpEditor::EDITOR_ID, IWorkbenchPage::MATCH_ID); if (editors.empty()) { // no HelpEditor is currently open, create a new one page->OpenEditor(input, HelpEditor::EDITOR_ID); } else { // reuse an existing editor reuseEditor = editors.front()->GetEditor(false); page->ReuseEditor(reuseEditor.Cast<IReusableEditor>(), input); page->Activate(reuseEditor); } } } } QCHPluginListener::QCHPluginListener(ctkPluginContext* context, QHelpEngine* helpEngine) : delayRegistration(true), context(context), helpEngine(helpEngine) {} void QCHPluginListener::processPlugins() { QMutexLocker lock(&mutex); processPlugins_unlocked(); } void QCHPluginListener::pluginChanged(const ctkPluginEvent& event) { QMutexLocker lock(&mutex); if (delayRegistration) { this->processPlugins_unlocked(); return; } /* Only should listen for RESOLVED and UNRESOLVED events. * * When a plugin is updated the Framework will publish an UNRESOLVED and * then a RESOLVED event which should cause the plugin to be removed * and then added back into the registry. * * When a plugin is uninstalled the Framework should publish an UNRESOLVED * event and then an UNINSTALLED event so the plugin will have been removed * by the UNRESOLVED event before the UNINSTALLED event is published. */ QSharedPointer<ctkPlugin> plugin = event.getPlugin(); switch (event.getType()) { case ctkPluginEvent::RESOLVED : addPlugin(plugin); break; case ctkPluginEvent::UNRESOLVED : removePlugin(plugin); break; } } void QCHPluginListener::processPlugins_unlocked() { if (!delayRegistration) return; foreach (QSharedPointer<ctkPlugin> plugin, context->getPlugins()) { if (isPluginResolved(plugin)) addPlugin(plugin); else removePlugin(plugin); } delayRegistration = false; } bool QCHPluginListener::isPluginResolved(QSharedPointer<ctkPlugin> plugin) { return (plugin->getState() & (ctkPlugin::RESOLVED | ctkPlugin::ACTIVE | ctkPlugin::STARTING | ctkPlugin::STOPPING)) != 0; } void QCHPluginListener::removePlugin(QSharedPointer<ctkPlugin> plugin) { // bail out if system plugin if (plugin->getPluginId() == 0) return; QFileInfo qchDirInfo = context->getDataFile("qch_files/" + QString::number(plugin->getPluginId())); if (qchDirInfo.exists()) { QDir qchDir(qchDirInfo.absoluteFilePath()); QStringList qchEntries = qchDir.entryList(QStringList("*.qch")); QStringList qchFiles; foreach(QString qchEntry, qchEntries) { qchFiles << qchDir.absoluteFilePath(qchEntry); } // unregister the cached qch files foreach(QString qchFile, qchFiles) { QString namespaceName = QHelpEngineCore::namespaceName(qchFile); if (namespaceName.isEmpty()) { BERRY_ERROR << "Could not get the namespace for qch file " << qchFile.toStdString(); continue; } else { if (!helpEngine->unregisterDocumentation(namespaceName)) { BERRY_ERROR << "Unregistering qch namespace " << namespaceName.toStdString() << " failed: " << helpEngine->error().toStdString(); } } } // clean the directory foreach(QString qchEntry, qchEntries) { qchDir.remove(qchEntry); } } } void QCHPluginListener::addPlugin(QSharedPointer<ctkPlugin> plugin) { // bail out if system plugin if (plugin->getPluginId() == 0) return; QFileInfo qchDirInfo = context->getDataFile("qch_files/" + QString::number(plugin->getPluginId())); QUrl location(plugin->getLocation()); QFileInfo pluginFileInfo(location.toLocalFile()); if (!qchDirInfo.exists() || qchDirInfo.lastModified() < pluginFileInfo.lastModified()) { removePlugin(plugin); if (!qchDirInfo.exists()) { QDir().mkpath(qchDirInfo.absoluteFilePath()); } QStringList localQCHFiles; QStringList resourceList = plugin->findResources("/", "*.qch", true); foreach(QString resource, resourceList) { QByteArray content = plugin->getResource(resource); QFile localFile(qchDirInfo.absoluteFilePath() + "/" + resource.section('/', -1)); localFile.open(QIODevice::WriteOnly); localFile.write(content); localFile.close(); if (localFile.error() != QFile::NoError) { BERRY_WARN << "Error writing " << localFile.fileName().toStdString() << ": " << localFile.errorString().toStdString(); } else { localQCHFiles << localFile.fileName(); } } foreach(QString qchFile, localQCHFiles) { if (!helpEngine->registerDocumentation(qchFile)) { BERRY_ERROR << "Registering qch file " << qchFile.toStdString() << " failed: " << helpEngine->error().toStdString(); } } } } IPerspectiveListener::Events::Types HelpPerspectiveListener::GetPerspectiveEventTypes() const { return Events::OPENED | Events::CHANGED; } void HelpPerspectiveListener::PerspectiveOpened(SmartPointer<IWorkbenchPage> page, IPerspectiveDescriptor::Pointer perspective) { // if no help editor is opened, open one showing the home page if (perspective->GetId() == HelpPerspective::ID && page->FindEditors(IEditorInput::Pointer(0), HelpEditor::EDITOR_ID, IWorkbenchPage::MATCH_ID).empty()) { IEditorInput::Pointer input(new HelpEditorInput()); page->OpenEditor(input, HelpEditor::EDITOR_ID); } } void HelpPerspectiveListener::PerspectiveChanged(SmartPointer<IWorkbenchPage> page, IPerspectiveDescriptor::Pointer perspective, const std::string &changeId) { if (perspective->GetId() == HelpPerspective::ID && changeId == IWorkbenchPage::CHANGE_RESET) { PerspectiveOpened(page, perspective); } } HelpWindowListener::HelpWindowListener() : perspListener(new HelpPerspectiveListener()) { // Register perspective listener for already opened windows typedef std::vector<IWorkbenchWindow::Pointer> WndVec; WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i) { (*i)->AddPerspectiveListener(perspListener); } } HelpWindowListener::~HelpWindowListener() { typedef std::vector<IWorkbenchWindow::Pointer> WndVec; WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i) { (*i)->RemovePerspectiveListener(perspListener); } } void HelpWindowListener::WindowClosed(IWorkbenchWindow::Pointer window) { window->RemovePerspectiveListener(perspListener); } void HelpWindowListener::WindowOpened(IWorkbenchWindow::Pointer window) { window->AddPerspectiveListener(perspListener); } void HelpContextHandler::handleEvent(const ctkEvent &event) { struct _runner : public Poco::Runnable { _runner(const ctkEvent& ev) : ev(ev) {} void run() { QUrl helpUrl; if (ev.containsProperty("url")) { helpUrl = QUrl(ev.getProperty("url").toString()); } else { helpUrl = contextUrl(); } HelpPluginActivator::linkActivated(PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(), helpUrl); delete this; } QUrl contextUrl() const { berry::IWorkbench* currentWorkbench = berry::PlatformUI::GetWorkbench(); if (currentWorkbench) { berry::IWorkbenchWindow::Pointer currentWorkbenchWindow = currentWorkbench->GetActiveWorkbenchWindow(); if (currentWorkbenchWindow) { berry::IWorkbenchPage::Pointer currentPage = currentWorkbenchWindow->GetActivePage(); if (currentPage) { berry::IWorkbenchPart::Pointer currentPart = currentPage->GetActivePart(); if (currentPart) { QString pluginID = QString::fromStdString(currentPart->GetSite()->GetPluginId()); QString viewID = QString::fromStdString(currentPart->GetSite()->GetId()); QString loc = "qthelp://" + pluginID + "/bundle/%1.html"; QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine(); QUrl contextUrl(loc.arg(viewID.replace(".", "_"))); QUrl url = helpEngine.findFile(contextUrl); if (url.isValid()) return url; else { BERRY_INFO << "Context help url invalid: " << contextUrl.toString().toStdString(); } // Try to get the index.html file of the plug-in contributing the // currently active part. QUrl pluginIndexUrl(loc.arg("index")); url = helpEngine.findFile(pluginIndexUrl); if (url != pluginIndexUrl) { // Use the default page instead of another index.html // (merged via the virtual folder property). url = QUrl(); } return url; } } } } return QUrl(); } ctkEvent ev; }; // sync with GUI thread Display::GetDefault()->AsyncExec(new _runner(event)); } } Q_EXPORT_PLUGIN2(org_blueberry_ui_qt_help, berry::HelpPluginActivator) <commit_msg>Look first for view id, then plugin id, then index.html<commit_after>/*=================================================================== BlueBerry Platform 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. ===================================================================*/ #include "berryHelpPluginActivator.h" #include "berryHelpContentView.h" #include "berryHelpIndexView.h" #include "berryHelpSearchView.h" #include "berryHelpEditor.h" #include "berryHelpEditorInput.h" #include "berryHelpPerspective.h" #include "berryQHelpEngineConfiguration.h" #include "berryQHelpEngineWrapper.h" #include <berryPlatformUI.h> #include <service/event/ctkEventConstants.h> #include <QtPlugin> #include <QDir> #include <QDateTime> namespace berry { class HelpPerspectiveListener : public IPerspectiveListener { public: Events::Types GetPerspectiveEventTypes() const; void PerspectiveOpened(SmartPointer<IWorkbenchPage> page, IPerspectiveDescriptor::Pointer perspective); void PerspectiveChanged(SmartPointer<IWorkbenchPage> page, IPerspectiveDescriptor::Pointer perspective, const std::string &changeId); }; class HelpWindowListener : public IWindowListener { public: HelpWindowListener(); ~HelpWindowListener(); void WindowClosed(IWorkbenchWindow::Pointer window); void WindowOpened(IWorkbenchWindow::Pointer window); private: // We use the same perspective listener for every window IPerspectiveListener::Pointer perspListener; }; HelpPluginActivator* HelpPluginActivator::instance = 0; HelpPluginActivator::HelpPluginActivator() : pluginListener(0) { this->instance = this; } HelpPluginActivator::~HelpPluginActivator() { instance = 0; } void HelpPluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(berry::HelpContentView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpIndexView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpSearchView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpEditor, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpPerspective, context) QFileInfo qhcInfo = context->getDataFile("qthelpcollection.qhc"); helpEngine.reset(new QHelpEngineWrapper(qhcInfo.absoluteFilePath())); if (!helpEngine->setupData()) { BERRY_ERROR << "QHelpEngine set-up failed: " << helpEngine->error().toStdString(); return; } helpEngineConfiguration.reset(new QHelpEngineConfiguration(context, *helpEngine.data())); delete pluginListener; pluginListener = new QCHPluginListener(context, helpEngine.data()); context->connectPluginListener(pluginListener, SLOT(pluginChanged(ctkPluginEvent))); // register all QCH files from all the currently installed plugins pluginListener->processPlugins(); helpEngine->initialDocSetupDone(); // Register a wnd listener which registers a perspective listener for each // new window. The perspective listener opens the help home page in the window // if no other help page is opened yet. wndListener = IWindowListener::Pointer(new HelpWindowListener()); PlatformUI::GetWorkbench()->AddWindowListener(wndListener); // Register an event handler for CONTEXTHELP_REQUESTED events helpContextHandler.reset(new HelpContextHandler); ctkDictionary helpHandlerProps; helpHandlerProps.insert(ctkEventConstants::EVENT_TOPIC, "org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); context->registerService<ctkEventHandler>(helpContextHandler.data(), helpHandlerProps); } void HelpPluginActivator::stop(ctkPluginContext* /*context*/) { delete pluginListener; pluginListener = 0; if (PlatformUI::IsWorkbenchRunning()) { PlatformUI::GetWorkbench()->RemoveWindowListener(wndListener); } wndListener = 0; } HelpPluginActivator *HelpPluginActivator::getInstance() { return instance; } QHelpEngineWrapper& HelpPluginActivator::getQHelpEngine() { return *helpEngine; } void HelpPluginActivator::linkActivated(IWorkbenchPage::Pointer page, const QUrl &link) { IEditorInput::Pointer input(new HelpEditorInput(link)); // see if an editor with the same input is already open IEditorPart::Pointer reuseEditor = page->FindEditor(input); if (reuseEditor) { // just activate it page->Activate(reuseEditor); } else { // reuse the currently active editor, if it is a HelpEditor reuseEditor = page->GetActiveEditor(); if (reuseEditor.IsNotNull() && page->GetReference(reuseEditor)->GetId() == HelpEditor::EDITOR_ID) { page->ReuseEditor(reuseEditor.Cast<IReusableEditor>(), input); page->Activate(reuseEditor); } else { // get the last used HelpEditor instance std::vector<IEditorReference::Pointer> editors = page->FindEditors(IEditorInput::Pointer(0), HelpEditor::EDITOR_ID, IWorkbenchPage::MATCH_ID); if (editors.empty()) { // no HelpEditor is currently open, create a new one page->OpenEditor(input, HelpEditor::EDITOR_ID); } else { // reuse an existing editor reuseEditor = editors.front()->GetEditor(false); page->ReuseEditor(reuseEditor.Cast<IReusableEditor>(), input); page->Activate(reuseEditor); } } } } QCHPluginListener::QCHPluginListener(ctkPluginContext* context, QHelpEngine* helpEngine) : delayRegistration(true), context(context), helpEngine(helpEngine) {} void QCHPluginListener::processPlugins() { QMutexLocker lock(&mutex); processPlugins_unlocked(); } void QCHPluginListener::pluginChanged(const ctkPluginEvent& event) { QMutexLocker lock(&mutex); if (delayRegistration) { this->processPlugins_unlocked(); return; } /* Only should listen for RESOLVED and UNRESOLVED events. * * When a plugin is updated the Framework will publish an UNRESOLVED and * then a RESOLVED event which should cause the plugin to be removed * and then added back into the registry. * * When a plugin is uninstalled the Framework should publish an UNRESOLVED * event and then an UNINSTALLED event so the plugin will have been removed * by the UNRESOLVED event before the UNINSTALLED event is published. */ QSharedPointer<ctkPlugin> plugin = event.getPlugin(); switch (event.getType()) { case ctkPluginEvent::RESOLVED : addPlugin(plugin); break; case ctkPluginEvent::UNRESOLVED : removePlugin(plugin); break; } } void QCHPluginListener::processPlugins_unlocked() { if (!delayRegistration) return; foreach (QSharedPointer<ctkPlugin> plugin, context->getPlugins()) { if (isPluginResolved(plugin)) addPlugin(plugin); else removePlugin(plugin); } delayRegistration = false; } bool QCHPluginListener::isPluginResolved(QSharedPointer<ctkPlugin> plugin) { return (plugin->getState() & (ctkPlugin::RESOLVED | ctkPlugin::ACTIVE | ctkPlugin::STARTING | ctkPlugin::STOPPING)) != 0; } void QCHPluginListener::removePlugin(QSharedPointer<ctkPlugin> plugin) { // bail out if system plugin if (plugin->getPluginId() == 0) return; QFileInfo qchDirInfo = context->getDataFile("qch_files/" + QString::number(plugin->getPluginId())); if (qchDirInfo.exists()) { QDir qchDir(qchDirInfo.absoluteFilePath()); QStringList qchEntries = qchDir.entryList(QStringList("*.qch")); QStringList qchFiles; foreach(QString qchEntry, qchEntries) { qchFiles << qchDir.absoluteFilePath(qchEntry); } // unregister the cached qch files foreach(QString qchFile, qchFiles) { QString namespaceName = QHelpEngineCore::namespaceName(qchFile); if (namespaceName.isEmpty()) { BERRY_ERROR << "Could not get the namespace for qch file " << qchFile.toStdString(); continue; } else { if (!helpEngine->unregisterDocumentation(namespaceName)) { BERRY_ERROR << "Unregistering qch namespace " << namespaceName.toStdString() << " failed: " << helpEngine->error().toStdString(); } } } // clean the directory foreach(QString qchEntry, qchEntries) { qchDir.remove(qchEntry); } } } void QCHPluginListener::addPlugin(QSharedPointer<ctkPlugin> plugin) { // bail out if system plugin if (plugin->getPluginId() == 0) return; QFileInfo qchDirInfo = context->getDataFile("qch_files/" + QString::number(plugin->getPluginId())); QUrl location(plugin->getLocation()); QFileInfo pluginFileInfo(location.toLocalFile()); if (!qchDirInfo.exists() || qchDirInfo.lastModified() < pluginFileInfo.lastModified()) { removePlugin(plugin); if (!qchDirInfo.exists()) { QDir().mkpath(qchDirInfo.absoluteFilePath()); } QStringList localQCHFiles; QStringList resourceList = plugin->findResources("/", "*.qch", true); foreach(QString resource, resourceList) { QByteArray content = plugin->getResource(resource); QFile localFile(qchDirInfo.absoluteFilePath() + "/" + resource.section('/', -1)); localFile.open(QIODevice::WriteOnly); localFile.write(content); localFile.close(); if (localFile.error() != QFile::NoError) { BERRY_WARN << "Error writing " << localFile.fileName().toStdString() << ": " << localFile.errorString().toStdString(); } else { localQCHFiles << localFile.fileName(); } } foreach(QString qchFile, localQCHFiles) { if (!helpEngine->registerDocumentation(qchFile)) { BERRY_ERROR << "Registering qch file " << qchFile.toStdString() << " failed: " << helpEngine->error().toStdString(); } } } } IPerspectiveListener::Events::Types HelpPerspectiveListener::GetPerspectiveEventTypes() const { return Events::OPENED | Events::CHANGED; } void HelpPerspectiveListener::PerspectiveOpened(SmartPointer<IWorkbenchPage> page, IPerspectiveDescriptor::Pointer perspective) { // if no help editor is opened, open one showing the home page if (perspective->GetId() == HelpPerspective::ID && page->FindEditors(IEditorInput::Pointer(0), HelpEditor::EDITOR_ID, IWorkbenchPage::MATCH_ID).empty()) { IEditorInput::Pointer input(new HelpEditorInput()); page->OpenEditor(input, HelpEditor::EDITOR_ID); } } void HelpPerspectiveListener::PerspectiveChanged(SmartPointer<IWorkbenchPage> page, IPerspectiveDescriptor::Pointer perspective, const std::string &changeId) { if (perspective->GetId() == HelpPerspective::ID && changeId == IWorkbenchPage::CHANGE_RESET) { PerspectiveOpened(page, perspective); } } HelpWindowListener::HelpWindowListener() : perspListener(new HelpPerspectiveListener()) { // Register perspective listener for already opened windows typedef std::vector<IWorkbenchWindow::Pointer> WndVec; WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i) { (*i)->AddPerspectiveListener(perspListener); } } HelpWindowListener::~HelpWindowListener() { typedef std::vector<IWorkbenchWindow::Pointer> WndVec; WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i) { (*i)->RemovePerspectiveListener(perspListener); } } void HelpWindowListener::WindowClosed(IWorkbenchWindow::Pointer window) { window->RemovePerspectiveListener(perspListener); } void HelpWindowListener::WindowOpened(IWorkbenchWindow::Pointer window) { window->AddPerspectiveListener(perspListener); } void HelpContextHandler::handleEvent(const ctkEvent &event) { struct _runner : public Poco::Runnable { _runner(const ctkEvent& ev) : ev(ev) {} void run() { QUrl helpUrl; if (ev.containsProperty("url")) { helpUrl = QUrl(ev.getProperty("url").toString()); } else { helpUrl = contextUrl(); } HelpPluginActivator::linkActivated(PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(), helpUrl); delete this; } QUrl contextUrl() const { berry::IWorkbench* currentWorkbench = berry::PlatformUI::GetWorkbench(); if (currentWorkbench) { berry::IWorkbenchWindow::Pointer currentWorkbenchWindow = currentWorkbench->GetActiveWorkbenchWindow(); if (currentWorkbenchWindow) { berry::IWorkbenchPage::Pointer currentPage = currentWorkbenchWindow->GetActivePage(); if (currentPage) { berry::IWorkbenchPart::Pointer currentPart = currentPage->GetActivePart(); if (currentPart) { QString pluginID = QString::fromStdString(currentPart->GetSite()->GetPluginId()); QString viewID = QString::fromStdString(currentPart->GetSite()->GetId()); QString loc = "qthelp://" + pluginID + "/bundle/%1.html"; QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine(); // Get view help page if available QUrl contextUrl(loc.arg(viewID.replace(".", "_"))); QUrl url = helpEngine.findFile(contextUrl); if (url.isValid()) return url; else { BERRY_INFO << "Context help url invalid: " << contextUrl.toString().toStdString(); } // If no view help exists get plugin help if available QUrl pluginContextUrl(pluginID.replace(".", "_")); url = helpEngine.findFile(pluginContextUrl); if (url.isValid()) return url; // Try to get the index.html file of the plug-in contributing the // currently active part. QUrl pluginIndexUrl(loc.arg("index")); url = helpEngine.findFile(pluginIndexUrl); if (url != pluginIndexUrl) { // Use the default page instead of another index.html // (merged via the virtual folder property). url = QUrl(); } return url; } } } } return QUrl(); } ctkEvent ev; }; // sync with GUI thread Display::GetDefault()->AsyncExec(new _runner(event)); } } Q_EXPORT_PLUGIN2(org_blueberry_ui_qt_help, berry::HelpPluginActivator) <|endoftext|>
<commit_before>// DXGL // Copyright (C) 2012 William Feely // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "common.h" #include "fog.h" static DWORD fogcolor = 0; static GLfloat fogstart = 0; static GLfloat fogend = 1; static GLfloat fogdensity = 1; void SetFogColor(DWORD color) { if(color == fogcolor) return; fogcolor = color; GLfloat colors[4]; colors[0] = (color >> 16) & 255; colors[1] = (color >> 8) & 255; colors[2] = color & 255; colors[3] = (color >> 24) & 255; glFogfv(GL_FOG_COLOR,colors); } void SetFogStart(GLfloat start) { if(start == fogstart) return; fogstart = start; glFogf(GL_FOG_START,start); } void SetFogEnd(GLfloat end) { if(end == fogend) return; fogend = end; glFogf(GL_FOG_END,end); } void SetFogDensity(GLfloat density) { if(density == fogdensity) return; fogdensity = density; glFogf(GL_FOG_DENSITY,density); }<commit_msg>Scale fog color channels to 0.0-1.0 range.<commit_after>// DXGL // Copyright (C) 2012 William Feely // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "common.h" #include "fog.h" static DWORD fogcolor = 0; static GLfloat fogstart = 0; static GLfloat fogend = 1; static GLfloat fogdensity = 1; void SetFogColor(DWORD color) { if(color == fogcolor) return; fogcolor = color; GLfloat colors[4]; colors[0] = (GLfloat)((color >> 16) & 255)/255.0f; colors[1] = (GLfloat)((color >> 8) & 255)/255.0f; colors[2] = (GLfloat)(color & 255)/255.0f; colors[3] = (GLfloat)((color >> 24) & 255)/255.0f; glFogfv(GL_FOG_COLOR,colors); } void SetFogStart(GLfloat start) { if(start == fogstart) return; fogstart = start; glFogf(GL_FOG_START,start); } void SetFogEnd(GLfloat end) { if(end == fogend) return; fogend = end; glFogf(GL_FOG_END,end); } void SetFogDensity(GLfloat density) { if(density == fogdensity) return; fogdensity = density; glFogf(GL_FOG_DENSITY,density); }<|endoftext|>
<commit_before>#include <cstring> // memcpy strdup #include <shoveler.h> #include "material.h" extern "C" { #include <shoveler/view/material.h> #include <shoveler/log.h> } using shoveler::Material; using shoveler::MaterialType; using shoveler::Vector2; using shoveler::Vector3; static ShovelerComponentMaterialType convertMaterialType(MaterialType type); void registerMaterialCallbacks(worker::Dispatcher& dispatcher, ShovelerView *view) { dispatcher.OnAddComponent<Material>([&, view](const worker::AddComponentOp<Material>& op) { ShovelerViewEntity *entity = shovelerViewGetEntity(view, op.EntityId); ShovelerViewMaterialConfiguration configuration; configuration.type = convertMaterialType(op.Data.type()); switch(op.Data.type()) { case MaterialType::COLOR: { configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_COLOR; Vector3 color = op.Data.color().value_or(Vector3{0, 0, 0}); configuration.color = shovelerVector3(color.x(), color.y(), color.z()); } break; case MaterialType::TEXTURE: configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_TEXTURE; configuration.textureEntityId = *op.Data.texture(); configuration.textureSamplerEntityId = *op.Data.texture_sampler(); break; case MaterialType::PARTICLE: { configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_PARTICLE; Vector3 color = op.Data.color().value_or(Vector3{0, 0, 0}); configuration.color = shovelerVector3(color.x(), color.y(), color.z()); } break; case MaterialType::TILEMAP: configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_TILEMAP; configuration.tilemapEntityId = *op.Data.tilemap(); break; case MaterialType::CANVAS: { configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_CANVAS; configuration.canvasEntityId = *op.Data.canvas(); Vector2 position = op.Data.canvas_region_position().value_or(Vector2{0.0f, 0.0f}); configuration.canvasRegionPosition = shovelerVector2(position.x(), position.y()); Vector2 size = op.Data.canvas_region_size().value_or(Vector2{0.0f, 0.0f}); configuration.canvasRegionSize = shovelerVector2(size.x(), size.y()); } break; case MaterialType::CHUNK: configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_CHUNK; configuration.chunkEntityId = *op.Data.chunk(); break; } shovelerViewEntityAddMaterial(entity, &configuration); }); dispatcher.OnComponentUpdate<Material>([&, view](const worker::ComponentUpdateOp<Material>& op) { ShovelerViewEntity *entity = shovelerViewGetEntity(view, op.EntityId); ShovelerViewMaterialConfiguration configuration; shovelerViewEntityGetMaterialConfiguration(entity, &configuration); if(op.Update.type()) { configuration.type = convertMaterialType(*op.Update.type()); } if(op.Update.texture()) { configuration.textureEntityId = **op.Update.texture(); } if(op.Update.texture_sampler()) { configuration.textureSamplerEntityId = **op.Update.texture_sampler(); } if(op.Update.tilemap()) { configuration.tilemapEntityId = **op.Update.tilemap(); } if(op.Update.canvas()) { configuration.canvasEntityId = **op.Update.canvas(); } if(op.Update.chunk()) { configuration.chunkEntityId = **op.Update.chunk(); } if(op.Update.color()) { Vector3 color = op.Update.color()->value_or(Vector3{0, 0, 0}); configuration.color = shovelerVector3(color.x(), color.y(), color.z()); } if(op.Update.canvas_region_position()) { Vector2 position = op.Update.canvas_region_position()->value_or(Vector2{0.0f, 0.0f}); configuration.canvasRegionPosition = shovelerVector2(position.x(), position.y()); } if(op.Update.canvas_region_size()) { Vector2 size = op.Update.canvas_region_size()->value_or(Vector2{0.0f, 0.0f}); configuration.canvasRegionSize = shovelerVector2(size.x(), size.y()); } shovelerViewEntityUpdateMaterial(entity, &configuration); }); dispatcher.OnRemoveComponent<Material>([&, view](const worker::RemoveComponentOp& op) { ShovelerViewEntity *entity = shovelerViewGetEntity(view, op.EntityId); shovelerViewEntityRemoveMaterial(entity); }); } static ShovelerComponentMaterialType convertMaterialType(MaterialType type) { switch(type) { case MaterialType::COLOR: return SHOVELER_COMPONENT_MATERIAL_TYPE_COLOR; case MaterialType::TEXTURE: return SHOVELER_COMPONENT_MATERIAL_TYPE_TEXTURE; case MaterialType::PARTICLE: return SHOVELER_COMPONENT_MATERIAL_TYPE_PARTICLE; case MaterialType::TILEMAP: return SHOVELER_COMPONENT_MATERIAL_TYPE_TILEMAP; case MaterialType::CANVAS: return SHOVELER_COMPONENT_MATERIAL_TYPE_CANVAS; case MaterialType::CHUNK: return SHOVELER_COMPONENT_MATERIAL_TYPE_CHUNK; } } <commit_msg>fixed C++ client material creation<commit_after>#include <cstring> // memcpy strdup #include <shoveler.h> #include "material.h" extern "C" { #include <shoveler/view/material.h> #include <shoveler/log.h> } using shoveler::Material; using shoveler::MaterialType; using shoveler::Vector2; using shoveler::Vector3; static ShovelerComponentMaterialType convertMaterialType(MaterialType type); void registerMaterialCallbacks(worker::Dispatcher& dispatcher, ShovelerView *view) { dispatcher.OnAddComponent<Material>([&, view](const worker::AddComponentOp<Material>& op) { ShovelerViewEntity *entity = shovelerViewGetEntity(view, op.EntityId); ShovelerViewMaterialConfiguration configuration; configuration.type = convertMaterialType(op.Data.type()); switch(op.Data.type()) { case MaterialType::COLOR: { configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_COLOR; Vector3 color = op.Data.color().value_or(Vector3{0, 0, 0}); configuration.color = shovelerVector3(color.x(), color.y(), color.z()); } break; case MaterialType::TEXTURE: configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_TEXTURE; configuration.textureEntityId = *op.Data.texture(); configuration.textureSamplerEntityId = *op.Data.texture_sampler(); break; case MaterialType::PARTICLE: { configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_PARTICLE; Vector3 color = op.Data.color().value_or(Vector3{0, 0, 0}); configuration.color = shovelerVector3(color.x(), color.y(), color.z()); } break; case MaterialType::TILEMAP: configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_TILEMAP; configuration.tilemapEntityId = *op.Data.tilemap(); break; case MaterialType::CANVAS: { configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_CANVAS; configuration.canvasEntityId = *op.Data.canvas(); Vector2 position = op.Data.canvas_region_position().value_or(Vector2{0.0f, 0.0f}); configuration.canvasRegionPosition = shovelerVector2(position.x(), position.y()); Vector2 size = op.Data.canvas_region_size().value_or(Vector2{0.0f, 0.0f}); configuration.canvasRegionSize = shovelerVector2(size.x(), size.y()); } break; case MaterialType::CHUNK: configuration.type = SHOVELER_COMPONENT_MATERIAL_TYPE_CHUNK; configuration.chunkEntityId = *op.Data.chunk(); break; } shovelerViewEntityAddMaterial(entity, &configuration); }); dispatcher.OnComponentUpdate<Material>([&, view](const worker::ComponentUpdateOp<Material>& op) { ShovelerViewEntity *entity = shovelerViewGetEntity(view, op.EntityId); ShovelerViewMaterialConfiguration configuration; shovelerViewEntityGetMaterialConfiguration(entity, &configuration); if(op.Update.type()) { configuration.type = convertMaterialType(*op.Update.type()); } if(op.Update.texture()) { configuration.textureEntityId = **op.Update.texture(); } if(op.Update.texture_sampler()) { configuration.textureSamplerEntityId = **op.Update.texture_sampler(); } if(op.Update.tilemap()) { configuration.tilemapEntityId = **op.Update.tilemap(); } if(op.Update.canvas()) { configuration.canvasEntityId = **op.Update.canvas(); } if(op.Update.chunk()) { configuration.chunkEntityId = **op.Update.chunk(); } if(op.Update.color()) { Vector3 color = op.Update.color()->value_or(Vector3{0, 0, 0}); configuration.color = shovelerVector3(color.x(), color.y(), color.z()); } if(op.Update.canvas_region_position()) { Vector2 position = op.Update.canvas_region_position()->value_or(Vector2{0.0f, 0.0f}); configuration.canvasRegionPosition = shovelerVector2(position.x(), position.y()); } if(op.Update.canvas_region_size()) { Vector2 size = op.Update.canvas_region_size()->value_or(Vector2{0.0f, 0.0f}); configuration.canvasRegionSize = shovelerVector2(size.x(), size.y()); } shovelerViewEntityUpdateMaterial(entity, &configuration); }); dispatcher.OnRemoveComponent<Material>([&, view](const worker::RemoveComponentOp& op) { ShovelerViewEntity *entity = shovelerViewGetEntity(view, op.EntityId); shovelerViewEntityRemoveMaterial(entity); }); } static ShovelerComponentMaterialType convertMaterialType(MaterialType type) { switch(type) { case MaterialType::COLOR: return SHOVELER_COMPONENT_MATERIAL_TYPE_COLOR; case MaterialType::TEXTURE: return SHOVELER_COMPONENT_MATERIAL_TYPE_TEXTURE; case MaterialType::PARTICLE: return SHOVELER_COMPONENT_MATERIAL_TYPE_PARTICLE; case MaterialType::TILEMAP: return SHOVELER_COMPONENT_MATERIAL_TYPE_TILEMAP; case MaterialType::CANVAS: return SHOVELER_COMPONENT_MATERIAL_TYPE_CANVAS; case MaterialType::CHUNK: return SHOVELER_COMPONENT_MATERIAL_TYPE_CHUNK; case MaterialType::TILE_SPRITE: return SHOVELER_COMPONENT_MATERIAL_TYPE_TILE_SPRITE; case MaterialType::TEXT: return SHOVELER_COMPONENT_MATERIAL_TYPE_TEXT; } } <|endoftext|>
<commit_before>#ifndef SILICIUM_THREAD_GENERATOR_HPP #define SILICIUM_THREAD_GENERATOR_HPP #include <silicium/observable/observer.hpp> #include <silicium/config.hpp> #include <silicium/exchange.hpp> #include <silicium/observable/yield_context.hpp> #include <future> #include <boost/thread/future.hpp> #include <boost/optional.hpp> #include <boost/concept_check.hpp> namespace Si { namespace detail { template <class ThreadingAPI> struct event : private observer<nothing> { event() : got_something(false) { } template <class NothingObservable> void block(NothingObservable &&blocked_on) { assert(!got_something); blocked_on.async_get_one(observe_by_ref(static_cast<observer<nothing> &>(*this))); typename ThreadingAPI::unique_lock lock(got_something_mutex); while (!got_something) { got_something_set.wait(lock); } got_something = false; } private: typename ThreadingAPI::mutex got_something_mutex; typename ThreadingAPI::condition_variable got_something_set; bool got_something; virtual void got_element(nothing) SILICIUM_OVERRIDE { wake_get_one(); } virtual void ended() SILICIUM_OVERRIDE { wake_get_one(); } void wake_get_one() { typename ThreadingAPI::unique_lock lock(got_something_mutex); got_something = true; got_something_set.notify_one(); } }; } template <class Element, class ThreadingAPI> struct thread_generator_observable { typedef Element element_type; thread_generator_observable() { } template <class Action> explicit thread_generator_observable(Action &&action) : state(Si::make_unique<state_type>(std::forward<Action>(action))) { } #if !SILICIUM_COMPILER_GENERATES_MOVES thread_generator_observable(thread_generator_observable &&other) BOOST_NOEXCEPT : state(std::move(other.state)) { } thread_generator_observable &operator = (thread_generator_observable &&other) BOOST_NOEXCEPT { state = std::move(other.state); return *this; } #endif void wait() { return state->wait(); } void async_get_one(ptr_observer<observer<element_type>> receiver) { return state->async_get_one(receiver); } private: struct state_type : private detail::push_context_impl<Element> { template <class Action> explicit state_type(Action &&action) : receiver(nullptr) , has_ended(false) { worker = ThreadingAPI::launch_async([action, this]() mutable { push_context<Element> yield(*this); (std::forward<Action>(action))(yield); typename ThreadingAPI::unique_lock lock(receiver_mutex); if (receiver) { auto receiver_ = Si::exchange(receiver, nullptr); lock.unlock(); receiver_->ended(); } else { has_ended = true; } }); } void async_get_one(ptr_observer<observer<element_type>> new_receiver) { typename ThreadingAPI::unique_lock lock(receiver_mutex); assert(!receiver); if (ready_result) { Element result = std::move(*ready_result); ready_result = boost::none; receiver_ready.notify_one(); lock.unlock(); new_receiver.get()->got_element(std::move(result)); } else { if (has_ended) { return new_receiver.get()->ended(); } receiver = new_receiver.get(); receiver_ready.notify_one(); } } void wait() { worker.get(); } private: typename ThreadingAPI::template future<void>::type worker; typename ThreadingAPI::mutex receiver_mutex; observer<Element> *receiver; boost::optional<Element> ready_result; typename ThreadingAPI::condition_variable receiver_ready; bool has_ended; detail::event<ThreadingAPI> got_something; virtual void push_result(Element result) SILICIUM_OVERRIDE { typename ThreadingAPI::unique_lock lock(receiver_mutex); while (ready_result && !receiver) { receiver_ready.wait(lock); } if (receiver) { auto * const receiver_ = Si::exchange(receiver, nullptr); lock.unlock(); receiver_->got_element(std::move(result)); } else { ready_result = std::move(result); } } virtual void get_one(observable<nothing, ptr_observer<observer<nothing>>> &target) SILICIUM_OVERRIDE { got_something.block(target); } }; std::unique_ptr<state_type> state; }; template <class Element, class ThreadingAPI, class Action> auto make_thread_generator(Action &&action) -> thread_generator_observable<Element, ThreadingAPI> { return thread_generator_observable<Element, ThreadingAPI>(std::forward<Action>(action)); } } #endif <commit_msg>thread_generator works with owning observers<commit_after>#ifndef SILICIUM_THREAD_GENERATOR_HPP #define SILICIUM_THREAD_GENERATOR_HPP #include <silicium/observable/observer.hpp> #include <silicium/config.hpp> #include <silicium/exchange.hpp> #include <silicium/observable/yield_context.hpp> #include <silicium/observable/erased_observer.hpp> #include <future> #include <boost/thread/future.hpp> #include <boost/optional.hpp> #include <boost/concept_check.hpp> namespace Si { namespace detail { template <class ThreadingAPI> struct event : private observer<nothing> { event() : got_something(false) { } template <class NothingObservable> void block(NothingObservable &&blocked_on) { assert(!got_something); blocked_on.async_get_one(observe_by_ref(static_cast<observer<nothing> &>(*this))); typename ThreadingAPI::unique_lock lock(got_something_mutex); while (!got_something) { got_something_set.wait(lock); } got_something = false; } private: typename ThreadingAPI::mutex got_something_mutex; typename ThreadingAPI::condition_variable got_something_set; bool got_something; virtual void got_element(nothing) SILICIUM_OVERRIDE { wake_get_one(); } virtual void ended() SILICIUM_OVERRIDE { wake_get_one(); } void wake_get_one() { typename ThreadingAPI::unique_lock lock(got_something_mutex); got_something = true; got_something_set.notify_one(); } }; } template <class Element, class ThreadingAPI> struct thread_generator_observable { typedef Element element_type; thread_generator_observable() { } template <class Action> explicit thread_generator_observable(Action &&action) : state(Si::make_unique<state_type>(std::forward<Action>(action))) { } #if !SILICIUM_COMPILER_GENERATES_MOVES thread_generator_observable(thread_generator_observable &&other) BOOST_NOEXCEPT : state(std::move(other.state)) { } thread_generator_observable &operator = (thread_generator_observable &&other) BOOST_NOEXCEPT { state = std::move(other.state); return *this; } #endif void wait() { return state->wait(); } template <class Observer> void async_get_one(Observer &&receiver) { return state->async_get_one(std::forward<Observer>(receiver)); } private: struct state_type : private detail::push_context_impl<Element> { template <class Action> explicit state_type(Action &&action) : has_ended(false) { worker = ThreadingAPI::launch_async([action, this]() mutable { push_context<Element> yield(*this); (std::forward<Action>(action))(yield); typename ThreadingAPI::unique_lock lock(receiver_mutex); if (receiver.get()) { auto receiver_ = Si::exchange(receiver, erased_observer<Element>()); lock.unlock(); std::move(receiver_).ended(); } else { has_ended = true; } }); } template <class Observer> void async_get_one(Observer &&new_receiver) { typename ThreadingAPI::unique_lock lock(receiver_mutex); if (ready_result) { Element result = std::move(*ready_result); ready_result = boost::none; receiver_ready.notify_one(); lock.unlock(); std::forward<Observer>(new_receiver).got_element(std::move(result)); } else { if (has_ended) { return std::forward<Observer>(new_receiver).ended(); } receiver = erased_observer<Element>(std::forward<Observer>(new_receiver)); receiver_ready.notify_one(); } } void wait() { worker.get(); } private: typename ThreadingAPI::template future<void>::type worker; typename ThreadingAPI::mutex receiver_mutex; erased_observer<Element> receiver; boost::optional<Element> ready_result; typename ThreadingAPI::condition_variable receiver_ready; bool has_ended; detail::event<ThreadingAPI> got_something; virtual void push_result(Element result) SILICIUM_OVERRIDE { typename ThreadingAPI::unique_lock lock(receiver_mutex); while (ready_result && !receiver.get()) { receiver_ready.wait(lock); } if (receiver.get()) { auto receiver_ = Si::exchange(receiver, erased_observer<Element>()); lock.unlock(); std::move(receiver_).got_element(std::move(result)); } else { ready_result = std::move(result); } } virtual void get_one(observable<nothing, ptr_observer<observer<nothing>>> &target) SILICIUM_OVERRIDE { got_something.block(target); } }; std::unique_ptr<state_type> state; }; template <class Element, class ThreadingAPI, class Action> auto make_thread_generator(Action &&action) -> thread_generator_observable<Element, ThreadingAPI> { return thread_generator_observable<Element, ThreadingAPI>(std::forward<Action>(action)); } } #endif <|endoftext|>
<commit_before>// // Created by dar on 11/24/15. // #include <GLES3/gl3.h> #include "Fbo.h" Fbo::~Fbo() { glDeleteTextures(1, &this->fbo_texture); glDeleteBuffers(1, &texture_vertices); glDeleteVertexArrays(1, &vaoId); glDeleteFramebuffers(1, &this->id); } unsigned char Fbo::initShader() { unsigned char errCode = 0; if (!vert_shader.load(this->shaderName + ".vert", GL_VERTEX_SHADER)) errCode |= 1 << 0; if (!frag_shader.load(this->shaderName + ".frag", GL_FRAGMENT_SHADER)) errCode |= 1 << 1; this->shader_program.createProgram(); if (!this->shader_program.addShaderToProgram(&vert_shader)) errCode |= 1 << 2; if (!this->shader_program.addShaderToProgram(&frag_shader)) errCode |= 1 << 3; if (!this->shader_program.linkProgram()) errCode |= 1 << 4; this->shader_program.useProgram(); GLint tmp_uniform_location = glGetUniformLocation(shader_program.getProgramID(), "fbo_texture"); if (tmp_uniform_location < 0) errCode |= 1 << 5; this->shader_tex_uniform = (GLuint) glGetUniformLocation(shader_program.getProgramID(), "fbo_texture"); return errCode; } int Fbo::init(int texId, unsigned int width, unsigned int height, float bgColor[], string shaderName) { this->texId = texId; this->width = width; this->height = height; this->bgColor = bgColor; this->shaderName = shaderName; unsigned char shaderRet = this->initShader(); if (shaderRet != 0) { return shaderRet; } glActiveTexture(GL_TEXTURE0); glGenTextures(1, &this->fbo_texture); glBindTexture(GL_TEXTURE_2D, this->fbo_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->width, this->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); glGenFramebuffers(1, &this->id); glBindFramebuffer(GL_FRAMEBUFFER, this->id); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->fbo_texture, 0); GLenum status = (GLenum) (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); return status; } void Fbo::resize(unsigned int width, unsigned int height) { this->width = width; this->height = height; glBindTexture(GL_TEXTURE_2D, this->fbo_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->width, this->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); } void Fbo::bind() { glBindFramebuffer(GL_FRAMEBUFFER, this->id); } void Fbo::unbind() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void Fbo::render(GLuint renderTo) { glBindFramebuffer(GL_FRAMEBUFFER, renderTo); glClearColor(this->bgColor[0], this->bgColor[1], this->bgColor[2], this->bgColor[3]); glClear(GL_COLOR_BUFFER_BIT); shader_program.useProgram(); shader_program.setUniform("uResolution", glm::vec2(this->width, this->height)); glActiveTexture(GL_TEXTURE0 + this->texId); glBindTexture(GL_TEXTURE_2D, this->fbo_texture); glUniform1i(this->shader_tex_uniform, /*GL_TEXTURE*/ this->texId); glBindVertexArray(vaoId); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(0); } void initTexData() { glGenVertexArrays(1, &vaoId); glGenBuffers(1, &texture_vertices); GLfloat fbo_vertices[] = { -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, }; glBindVertexArray(vaoId); glBindBuffer(GL_ARRAY_BUFFER, texture_vertices); glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(float), fbo_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray((GLuint) 0); glVertexAttribPointer((GLuint) 0, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindVertexArray(0); }<commit_msg>Change init method return status<commit_after>// // Created by dar on 11/24/15. // #include <GLES3/gl3.h> #include "Fbo.h" Fbo::~Fbo() { glDeleteTextures(1, &this->fbo_texture); glDeleteBuffers(1, &texture_vertices); glDeleteVertexArrays(1, &vaoId); glDeleteFramebuffers(1, &this->id); } unsigned char Fbo::initShader() { unsigned char errCode = 0; if (!vert_shader.load(this->shaderName + ".vert", GL_VERTEX_SHADER)) errCode |= 1 << 0; if (!frag_shader.load(this->shaderName + ".frag", GL_FRAGMENT_SHADER)) errCode |= 1 << 1; this->shader_program.createProgram(); if (!this->shader_program.addShaderToProgram(&vert_shader)) errCode |= 1 << 2; if (!this->shader_program.addShaderToProgram(&frag_shader)) errCode |= 1 << 3; if (!this->shader_program.linkProgram()) errCode |= 1 << 4; this->shader_program.useProgram(); GLint tmp_uniform_location = glGetUniformLocation(shader_program.getProgramID(), "fbo_texture"); if (tmp_uniform_location < 0) errCode |= 1 << 5; this->shader_tex_uniform = (GLuint) glGetUniformLocation(shader_program.getProgramID(), "fbo_texture"); return errCode; } int Fbo::init(int texId, unsigned int width, unsigned int height, float bgColor[], string shaderName) { this->texId = texId; this->width = width; this->height = height; this->bgColor = bgColor; this->shaderName = shaderName; unsigned char shaderRet = this->initShader(); if (shaderRet != 0) { return shaderRet; } glActiveTexture(GL_TEXTURE0); glGenTextures(1, &this->fbo_texture); glBindTexture(GL_TEXTURE_2D, this->fbo_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->width, this->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); glGenFramebuffers(1, &this->id); glBindFramebuffer(GL_FRAMEBUFFER, this->id); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->fbo_texture, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); return status; } void Fbo::resize(unsigned int width, unsigned int height) { this->width = width; this->height = height; glBindTexture(GL_TEXTURE_2D, this->fbo_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->width, this->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); } void Fbo::bind() { glBindFramebuffer(GL_FRAMEBUFFER, this->id); } void Fbo::unbind() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void Fbo::render(GLuint renderTo) { glBindFramebuffer(GL_FRAMEBUFFER, renderTo); glClearColor(this->bgColor[0], this->bgColor[1], this->bgColor[2], this->bgColor[3]); glClear(GL_COLOR_BUFFER_BIT); shader_program.useProgram(); shader_program.setUniform("uResolution", glm::vec2(this->width, this->height)); glActiveTexture(GL_TEXTURE0 + this->texId); glBindTexture(GL_TEXTURE_2D, this->fbo_texture); glUniform1i(this->shader_tex_uniform, /*GL_TEXTURE*/ this->texId); glBindVertexArray(vaoId); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(0); } void initTexData() { glGenVertexArrays(1, &vaoId); glGenBuffers(1, &texture_vertices); GLfloat fbo_vertices[] = { -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, }; glBindVertexArray(vaoId); glBindBuffer(GL_ARRAY_BUFFER, texture_vertices); glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(float), fbo_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray((GLuint) 0); glVertexAttribPointer((GLuint) 0, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindVertexArray(0); }<|endoftext|>
<commit_before>#include "agn_frac.h" #include "lumfunct.h" agn_frac::agn_frac(int agn_types){ if(agn_types <= 1){ _types=1; generate=false; printf("No AGN Detected\n"); } else{ _types=2; generate=true; } lf=NULL; } void agn_frac::set_lumfunct(lumfunct *lf){ if(lf != NULL){ this->lf = lf; } else cout << "ERROR: NULL Pointer Passed to Simulator" << endl; } //Fraction of galaxies as a function of luminosity and redshift that are AGN (note ALL AGN including obscured and unobscured, can try to sub-divide at some future point. double agn_frac::get_agn_frac(double lum, double redshift){ map <tuple<double,double>,double> values; tuple<double,double> point(lum,redshift); if(values.count(point) == 0){ printf("Initializing AGN_FRAC %f %f\n",lum,redshift); //the Chen,Hickox et al. 2013 relation between average(Log(Lx)) and Log(Lir) //here Lx is in ergs/s while lum (i.e. Lir) is in Lsun; float av_lglx=30.37+1.05*lum; //the Lutz et al. 2004 relation between Log(Lx) and Log(L6um) for Seybert 1s //both luminosities as in ergs/s; float av_lgl6um=av_lglx-0.41; //the average lgl6 to lg(Lagn_ir) conversion including converting to Lsun // for now a placeholder only, will need to calculate properly float av_lgAGNir=av_lgl6um-7-26-log10(3.86)+0.4; //the logic here is that if the average Lir_agn is comparable to the Lir of the given bin, essentially 100% of the galaxies are AGN and scales from there. With the Chen+13 relation, we end up with fairly low AGN fractions even at the highest luminosities. values[point]= pow(10,(av_lgAGNir-lum)); } return values[point]; } //here agntype = 0 (all agn) or 1 or 2 (includes Type 2 and reddened Type 1) double agn_frac::get_agn_frac2(double lum, double redshift, int agntype){ //Using the quasar LFs from Lacy et al. 2015, note that lum,lstar0,lstar, and phistar are all given in log_10 //note the luminosities in that paper are given in terms of the 5um monochromatic restframe luminosity [ergs*Hz] float phistar,lstar0,gamma1,gamma2,k1,k2,k3; if (agntype == 0){ phistar=-4.75; gamma1=1.07; gamma2=2.48; lstar0=31.92; k1=1.05; k2=-4.71; k3=-0.034; } if (agntype == 1){ phistar=-5.18; gamma1=0.25; gamma2=2.68; lstar0=31.99; k1=0.537; k2=-5.48; k3=0.768; } if (agntype == 2){ phistar=-4.98; gamma1=1.09; gamma2=2.61; lstar0=31.91; k1=1.165; k2=-4.45; k3=-0.23; } float eps=log10((1+redshift)/(1+2.5)); float lstar=lstar0+k1*eps+k2*pow(eps,2)+k3*pow(eps,3); //the average lgl6 to lg(Lagn_ir) conversion including converting to Lsun // for now a placeholder only, will need to calculate properly float lum5um=lum+7+26+log10(3.86)-0.4; float denom=pow(pow(10,lum5um)/pow(10,lstar),gamma1)+pow(pow(10,lum5um)/pow(10,lstar),gamma2); float phi=pow(10,phistar)/denom; float phi_all,fagn; phi_all = lf->get_nsrcs(redshift,lum); //the AGN fraction is the ratio of AGN Luminosity Function computed here and the overall luminosity function (from lumfunc.cpp), ensure that this does not exceed 100% fagn=pow(10,(phi-phi_all)); if (fagn > 1) fagn=1.0; return fagn; } int agn_frac::get_sedtype(double lum, double redshift){ if(generate) return get_agn_frac(lum,redshift) > rng.flat(0,1) ? 0 : 1; else return 0; } <commit_msg>fixed bug in agn_frac<commit_after>#include "agn_frac.h" #include "lumfunct.h" agn_frac::agn_frac(int agn_types){ if(agn_types <= 1){ _types=1; generate=false; printf("No AGN Detected\n"); } else{ _types=2; generate=true; } lf=NULL; } void agn_frac::set_lumfunct(lumfunct *lf){ if(lf != NULL){ this->lf = lf; } else cout << "ERROR: NULL Pointer Passed to Simulator" << endl; } //Fraction of galaxies as a function of luminosity and redshift that are AGN (note ALL AGN including obscured and unobscured, can try to sub-divide at some future point. double agn_frac::get_agn_frac(double lum, double redshift){ map <tuple<double,double>,double> values; tuple<double,double> point(lum,redshift); if(values.count(point) == 0){ printf("Initializing AGN_FRAC %f %f\n",lum,redshift); //the Chen,Hickox et al. 2013 relation between average(Log(Lx)) and Log(Lir) //here Lx is in ergs/s while lum (i.e. Lir) is in Lsun; float av_lglx=30.37+1.05*lum; //the Lutz et al. 2004 relation between Log(Lx) and Log(L6um) for Seybert 1s //both luminosities as in ergs/s; float av_lgl6um=av_lglx-0.41; //the average lgl6 to lg(Lagn_ir) conversion including converting to Lsun // for now a placeholder only, will need to calculate properly float av_lgAGNir=av_lgl6um-7-26-log10(3.86)+0.4; //the logic here is that if the average Lir_agn is comparable to the Lir of the given bin, essentially 100% of the galaxies are AGN and scales from there. With the Chen+13 relation, we end up with fairly low AGN fractions even at the highest luminosities. values[point]= pow(10,(av_lgAGNir-lum)); } return values[point]; } //here agntype = 0 (all agn) or 1 or 2 (includes Type 2 and reddened Type 1) double agn_frac::get_agn_frac2(double lum, double redshift, int agntype){ //Using the quasar LFs from Lacy et al. 2015, note that lum,lstar0,lstar, and phistar are all given in log_10 //note the luminosities in that paper are given in terms of the 5um monochromatic restframe luminosity [ergs*Hz] float phistar,lstar0,gamma1,gamma2,k1,k2,k3; if (agntype == 0){ phistar=-4.75; gamma1=1.07; gamma2=2.48; lstar0=31.92; k1=1.05; k2=-4.71; k3=-0.034; } if (agntype == 1){ phistar=-5.18; gamma1=0.25; gamma2=2.68; lstar0=31.99; k1=0.537; k2=-5.48; k3=0.768; } if (agntype == 2){ phistar=-4.98; gamma1=1.09; gamma2=2.61; lstar0=31.91; k1=1.165; k2=-4.45; k3=-0.23; } float eps=log10((1+redshift)/(1+2.5)); float lstar=lstar0+k1*eps+k2*pow(eps,2)+k3*pow(eps,3); //the lgl5 [ergs/Hz] to lgLagn_ir [Lsun] conversion float lum5um=lum+33+log10(3.86)-13.7782-0.48; float denom=pow(pow(10,lum5um)/pow(10,lstar),gamma1)+pow(pow(10,lum5um)/pow(10,lstar),gamma2); float phi=pow(10,phistar)/denom; float phi_all,fagn; phi_all = lf->get_nsrcs(redshift,lum); //the AGN fraction is the ratio of AGN Luminosity Function computed here and the overall luminosity function (from lumfunc.cpp), ensure that this does not exceed 100% fagn=pow(10,(phi-phi_all)); if (fagn > 1) fagn=1.0; return fagn; } int agn_frac::get_sedtype(double lum, double redshift){ if(generate) return get_agn_frac(lum,redshift) > rng.flat(0,1) ? 0 : 1; else return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "../inc/Frisk.h" #include "../inc/ConsoleReporter.h" int mult(int x, int y) { return x * y; } DEF_TEST(mult_test) { BEGIN_TEST(self); self.setOption(FRISK_OPTION_CONTINUE, true); EXPECT_EQUAL(self, mult(0, 0), 0, "0 times anything should be 0"); EXPECT_EQUAL(self, mult(0, 5), 0, "0 times anything should be 0"); EXPECT_EQUAL(self, mult(5, 0), 0, "0 times anything should be 0"); EXPECT_EQUAL(self, mult(1, 5), 5, "1 times anything is itself"); EXPECT_EQUAL(self, mult(5, 1), 5, "1 times anything is itself"); EXPECT_EQUAL(self, mult(5, 5), 25, "5 times itself is its square"); EXPECT_EQUAL(self, mult(1, -5), -5, "1 times a negative number is that negative number"); EXPECT_EQUAL(self, mult(-5, 1), -5, "1 times a negative number is that negative number"); EXPECT_GREATER(self, mult(-5, -5), 0, "Two negatives mutlipled should be positive."); EXPECT_LESS(self, mult(-5, 5), 0, "One negative times one positive should be negative."); } class myClass { public: DEF_TEST(myTest) { BEGIN_TEST(self); EXPECT_EQUAL(self, 10, 25, "should be equal!"); } }; int main() { Frisk::TestCollection tests; tests.addTest(mult_test, "mult_test"); tests.addTest(myClass::myTest, "myClass::myTest"); Frisk::ConsoleReporter reporter; reporter.setOption("description", true); std::list<Frisk::Test> results = tests.runTests(false, &reporter); return 1; } <commit_msg>updated demo test<commit_after>#include <iostream> #include "../inc/Frisk.h" #include "../inc/ConsoleReporter.h" int mult(int x, int y) { return x * y; } DEF_TEST(mult_test) { BEGIN_TEST(self); self.setOption(FRISK_OPTION_CONTINUE, true); EXPECT_EQUAL(self, mult(0, 0), 0, "0 times anything should be 0"); EXPECT_EQUAL(self, mult(0, 5), 0, "0 times anything should be 0"); EXPECT_EQUAL(self, mult(5, 0), 0, "0 times anything should be 0"); EXPECT_EQUAL(self, mult(1, 5), 5, "1 times anything is itself"); EXPECT_EQUAL(self, mult(5, 1), 5, "1 times anything is itself"); EXPECT_EQUAL(self, mult(5, 5), 25, "5 times itself is its square"); EXPECT_EQUAL(self, mult(1, -5), -5, "1 times a negative number is that negative number"); EXPECT_EQUAL(self, mult(-5, 1), -5, "1 times a negative number is that negative number"); EXPECT_GREATER(self, mult(-5, -5), 0, "Two negatives mutlipled should be positive."); EXPECT_LESS(self, mult(-5, 5), 0, "One negative times one positive should be negative."); } int main() { Frisk::TestCollection tests; tests.addTest(mult_test, "mult_test"); Frisk::ConsoleReporter reporter; reporter.setOption("description", true); std::list<Frisk::Test> results = tests.runTests(false, &reporter); return 1; } <|endoftext|>
<commit_before>#include "OpenGL.h" #include "window.h" #include "screenrenderer.h" #include "scenemanager.h" #include "transformation.h" #include "KeyboardTransformation.h" #include "animatedtransformation.h" #include "interpolatedrotation.h" #include "controllablecamera.h" #include "color.h" #include "ui_dockwidget.h" Node *initScene1(); void SceneManager::initScenes() { Ui_FPSWidget *lDock; QDockWidget *lDockWidget = new QDockWidget(QString("FPS"), SceneManager::getMainWindow()); ControllableCamera *cam = new ControllableCamera(); RenderingContext *myContext=new RenderingContext(cam); unsigned int myContextNr = SceneManager::instance()->addContext(myContext); unsigned int myScene = SceneManager::instance()->addScene(initScene1()); ScreenRenderer *myRenderer = new ScreenRenderer(myContextNr, myScene); //Vorsicht: Die Szene muss initialisiert sein, bevor das Fenster verändert wird (Fullscreen) SceneManager::instance()->setActiveScene(myScene); SceneManager::instance()->setActiveContext(myContextNr); // SceneManager::instance()->setFullScreen(); lDock = new Ui_FPSWidget(); lDock->setupUi(lDockWidget); lDockWidget->resize(200,100); SceneManager::getMainWindow()->addDockWidget(Qt::RightDockWidgetArea, lDockWidget); lDockWidget->show(); QObject::connect(Window::getInstance(), SIGNAL(sigFPS(int)), lDock->lcdNumber, SLOT(display(int))); } Node *initScene1() { Node* sonnensystem = new Node(); return sonnensystem; } <commit_msg>fps dock aus main window rausgenommen<commit_after>#include "OpenGL.h" #include "window.h" #include "screenrenderer.h" #include "scenemanager.h" #include "transformation.h" #include "KeyboardTransformation.h" #include "animatedtransformation.h" #include "interpolatedrotation.h" #include "controllablecamera.h" #include "color.h" #include "ui_dockwidget.h" Node* initHalbzeitScene(); void SceneManager::initScenes() { //Ui_FPSWidget *lDock; //QDockWidget *lDockWidget = new QDockWidget(QString("FPS"), SceneManager::getMainWindow()); ControllableCamera *cam = new ControllableCamera(); RenderingContext *myContext=new RenderingContext(cam); unsigned int myContextNr = SceneManager::instance()->addContext(myContext); unsigned int myScene = SceneManager::instance()->addScene(initHalbzeitScene()); ScreenRenderer *myRenderer = new ScreenRenderer(myContextNr, myScene); Q_UNUSED(myRenderer) //Vorsicht: Die Szene muss initialisiert sein, bevor das Fenster verändert wird (Fullscreen) SceneManager::instance()->setActiveScene(myScene); SceneManager::instance()->setActiveContext(myContextNr); // SceneManager::instance()->setFullScreen(); // Hab mir angeschaut wie man evtl die doofen ränder wegbekommt. Das ui Element was hier // ist das Widget was angezeit wird im MainWindow. Definiert wird das ganze in der Datei // glwithwidgets.ui im FrameworkSource und evtl kann es über die variable noch ein bisschen // konfiguriert werden ohne das man den kompletten Szenegraphen rekompiliert Ui::GLwithWidgets* ui = MainWindow::getUi(); Q_UNUSED(ui) // lDock = new Ui_FPSWidget(); // lDock->setupUi(lDockWidget); // lDockWidget->resize(200,100); // SceneManager::getMainWindow()->addDockWidget(Qt::RightDockWidgetArea, lDockWidget); // lDockWidget->show(); // QObject::connect(Window::getInstance(), SIGNAL(sigFPS(int)), lDock->lcdNumber, SLOT(display(int))); } Node *initHalbzeitScene() { Node* sonnensystem = new Node(); return sonnensystem; } <|endoftext|>
<commit_before>/* * Copyright 2004 The Apache Software 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 * imitations under the License. */ /* * XSEC * * XSECSOAPRequestorSimple := (Very) Basic implementation of a SOAP * HTTP wrapper for testing the client code. * * * $Id$ * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <errno.h> #include <xsec/utils/XSECSOAPRequestorSimple.hpp> #include <xsec/utils/XSECSafeBuffer.hpp> #include <xsec/framework/XSECError.hpp> #include <xercesc/dom/DOM.hpp> #include <xercesc/util/XMLNetAccessor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLExceptMsgs.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLUniDefs.hpp> XERCES_CPP_NAMESPACE_USE // -------------------------------------------------------------------------------- // Platform specific constructor // -------------------------------------------------------------------------------- XSECSOAPRequestorSimple::XSECSOAPRequestorSimple(const XMLCh * uri) : m_uri(uri) { } // -------------------------------------------------------------------------------- // Interface // -------------------------------------------------------------------------------- DOMDocument * XSECSOAPRequestorSimple::doRequest(DOMDocument * request) { char * content = wrapAndSerialise(request); // First we need to serialise char fBuffer[4000]; char * fBufferEnd; char * fBufferPos; // // Pull all of the parts of the URL out of th m_uri object, and transcode them // and transcode them back to ASCII. // const XMLCh* hostName = m_uri.getHost(); char* hostNameAsCharStar = XMLString::transcode(hostName); ArrayJanitor<char> janBuf1(hostNameAsCharStar); const XMLCh* path = m_uri.getPath(); char* pathAsCharStar = XMLString::transcode(path); ArrayJanitor<char> janBuf2(pathAsCharStar); const XMLCh* fragment = m_uri.getFragment(); char* fragmentAsCharStar = 0; if (fragment) fragmentAsCharStar = XMLString::transcode(fragment); ArrayJanitor<char> janBuf3(fragmentAsCharStar); const XMLCh* query = m_uri.getQueryString(); char* queryAsCharStar = 0; if (query) queryAsCharStar = XMLString::transcode(query); ArrayJanitor<char> janBuf4(queryAsCharStar); unsigned short portNumber = (unsigned short) m_uri.getPort(); // If no number is set, go with port 80 if (portNumber == USHRT_MAX) portNumber = 80; // // Set up a socket. // struct hostent* hostEntPtr = 0; struct sockaddr_in sa; if ((hostEntPtr = gethostbyname(hostNameAsCharStar)) == NULL) { unsigned long numAddress = inet_addr(hostNameAsCharStar); if (numAddress == 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_TargetResolution); } if ((hostEntPtr = gethostbyaddr((char *) &numAddress, sizeof(unsigned long), AF_INET)) == NULL) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_TargetResolution); } } memcpy((void *) &sa.sin_addr, (const void *) hostEntPtr->h_addr, hostEntPtr->h_length); sa.sin_family = hostEntPtr->h_addrtype; sa.sin_port = htons(portNumber); int s = socket(hostEntPtr->h_addrtype, SOCK_STREAM, 0); if (s < 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error creating socket"); } if (connect(s, (struct sockaddr *) &sa, sizeof(sa)) < 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error connecting to end server"); } // The port is open and ready to go. // Build up the http GET command to send to the server. // To do: We should really support http 1.1. This implementation // is weak. memset(fBuffer, 0, sizeof(fBuffer)); strcpy(fBuffer, "POST "); strcat(fBuffer, pathAsCharStar); if (queryAsCharStar != 0) { // Tack on a ? before the fragment strcat(fBuffer,"?"); strcat(fBuffer, queryAsCharStar); } if (fragmentAsCharStar != 0) { strcat(fBuffer, fragmentAsCharStar); } strcat(fBuffer, " HTTP/1.0\r\n"); strcat(fBuffer, "Content-Type: text/xml; charset=utf-8\r\n"); strcat(fBuffer, "Host: "); strcat(fBuffer, hostNameAsCharStar); if (portNumber != 80) { int i = strlen(fBuffer); sprintf(fBuffer+i, ":%d", portNumber); } strcat(fBuffer, "\r\n"); strcat(fBuffer, "Content-Length: "); int i = (int) strlen(fBuffer); sprintf(fBuffer+i, "%d", strlen(content)); strcat(fBuffer, "\r\n"); strcat(fBuffer, "SOAPAction: \"\"\r\n"); /* strcat(fBuffer, "Connection: Close\r\n"); strcat(fBuffer, "Cache-Control: no-cache\r\n");*/ strcat(fBuffer, "\r\n"); // Now the content strcat(fBuffer, content); // Send the http request int lent = strlen(fBuffer); int aLent = 0; if ((aLent = write(s, (void *) fBuffer, lent)) != lent) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error writing to socket"); } // // get the response, check the http header for errors from the server. // aLent = read(s, (void *)fBuffer, sizeof(fBuffer)-1); /* fBuffer[aLent] = '\0'; printf(fBuffer); */ if (aLent <= 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } fBufferEnd = fBuffer+aLent; *fBufferEnd = 0; // Find the break between the returned http header and any data. // (Delimited by a blank line) // Hang on to any data for use by the first read from this BinHTTPURLInputStream. // fBufferPos = strstr(fBuffer, "\r\n\r\n"); if (fBufferPos != 0) { fBufferPos += 4; *(fBufferPos-2) = 0; } else { fBufferPos = strstr(fBuffer, "\n\n"); if (fBufferPos != 0) { fBufferPos += 2; *(fBufferPos-1) = 0; } else fBufferPos = fBufferEnd; } // Make sure the header includes an HTTP 200 OK response. // char *p = strstr(fBuffer, "HTTP"); if (p == 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } p = strchr(p, ' '); if (p == 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } int httpResponse = atoi(p); if (httpResponse == 302 || httpResponse == 301) { //Once grows, should use a switch char redirectBuf[256]; int q; // Find the "Location:" string p = strstr(p, "Location:"); if (p == 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } p = strchr(p, ' '); if (p == 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } // Now read p++; for (q=0; q < 255 && p[q] != '\r' && p[q] !='\n'; ++q) redirectBuf[q] = p[q]; redirectBuf[q] = '\0'; // Try to find this location m_uri = XMLUri(XMLString::transcode(redirectBuf)); return doRequest(request); } else if (httpResponse != 200) { // Most likely a 404 Not Found error. // Should recognize and handle the forwarding responses. // char * q = strstr(p, "\n"); if (q == NULL) q = strstr(p, "\r"); if (q != NULL) *q = '\0'; safeBuffer sb; sb.sbStrcpyIn("SOAPRequestorSimple HTTP Error : "); if (strlen(p) < 256) sb.sbStrcatIn(p); throw XSECException(XSECException::HTTPURIInputStreamError, sb.rawCharBuffer()); } /* Now find out how long the return is */ p = strstr(fBuffer, "Content-Length:"); if (p == NULL) { throw XSECException(XSECException::HTTPURIInputStreamError, "Content-Length required in SOAP HTTP Response"); } p = strchr(p, ' '); p++; int responseLength = atoi(p); char * responseBuffer; XSECnew(responseBuffer, char[responseLength]); ArrayJanitor<char> j_responseBuffer(responseBuffer); lent = fBufferEnd - fBufferPos; memcpy(responseBuffer, fBufferPos, lent); while (lent < responseLength) { aLent = read(s, &responseBuffer[lent], responseLength - lent); lent += aLent; } return parseAndUnwrap(responseBuffer, responseLength); } <commit_msg>Fix SOAP client bugs<commit_after>/* * Copyright 2004 The Apache Software 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 * imitations under the License. */ /* * XSEC * * XSECSOAPRequestorSimple := (Very) Basic implementation of a SOAP * HTTP wrapper for testing the client code. * * * $Id$ * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <errno.h> #include <xsec/utils/XSECSOAPRequestorSimple.hpp> #include <xsec/utils/XSECSafeBuffer.hpp> #include <xsec/framework/XSECError.hpp> #include <xercesc/dom/DOM.hpp> #include <xercesc/util/XMLNetAccessor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLExceptMsgs.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLUniDefs.hpp> XERCES_CPP_NAMESPACE_USE // -------------------------------------------------------------------------------- // Platform specific constructor // -------------------------------------------------------------------------------- XSECSOAPRequestorSimple::XSECSOAPRequestorSimple(const XMLCh * uri) : m_uri(uri) { } // -------------------------------------------------------------------------------- // Interface // -------------------------------------------------------------------------------- DOMDocument * XSECSOAPRequestorSimple::doRequest(DOMDocument * request) { char * content = wrapAndSerialise(request); // First we need to serialise char fBuffer[4000]; char * fBufferEnd; char * fBufferPos; // // Pull all of the parts of the URL out of th m_uri object, and transcode them // and transcode them back to ASCII. // const XMLCh* hostName = m_uri.getHost(); char* hostNameAsCharStar = XMLString::transcode(hostName); ArrayJanitor<char> janBuf1(hostNameAsCharStar); const XMLCh* path = m_uri.getPath(); char* pathAsCharStar = XMLString::transcode(path); ArrayJanitor<char> janBuf2(pathAsCharStar); const XMLCh* fragment = m_uri.getFragment(); char* fragmentAsCharStar = 0; if (fragment) fragmentAsCharStar = XMLString::transcode(fragment); ArrayJanitor<char> janBuf3(fragmentAsCharStar); const XMLCh* query = m_uri.getQueryString(); char* queryAsCharStar = 0; if (query) queryAsCharStar = XMLString::transcode(query); ArrayJanitor<char> janBuf4(queryAsCharStar); unsigned short portNumber = (unsigned short) m_uri.getPort(); // If no number is set, go with port 80 if (portNumber == USHRT_MAX) portNumber = 80; // // Set up a socket. // struct hostent* hostEntPtr = 0; struct sockaddr_in sa; if ((hostEntPtr = gethostbyname(hostNameAsCharStar)) == NULL) { unsigned long numAddress = inet_addr(hostNameAsCharStar); if (numAddress == 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_TargetResolution); } if ((hostEntPtr = gethostbyaddr((char *) &numAddress, sizeof(unsigned long), AF_INET)) == NULL) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_TargetResolution); } } memcpy((void *) &sa.sin_addr, (const void *) hostEntPtr->h_addr, hostEntPtr->h_length); sa.sin_family = hostEntPtr->h_addrtype; sa.sin_port = htons(portNumber); int s = socket(hostEntPtr->h_addrtype, SOCK_STREAM, 0); if (s < 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error creating socket"); } if (connect(s, (struct sockaddr *) &sa, sizeof(sa)) < 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error connecting to end server"); } // The port is open and ready to go. // Build up the http GET command to send to the server. // To do: We should really support http 1.1. This implementation // is weak. memset(fBuffer, 0, sizeof(fBuffer)); strcpy(fBuffer, "POST "); strcat(fBuffer, pathAsCharStar); if (queryAsCharStar != 0) { // Tack on a ? before the fragment strcat(fBuffer,"?"); strcat(fBuffer, queryAsCharStar); } if (fragmentAsCharStar != 0) { strcat(fBuffer, fragmentAsCharStar); } strcat(fBuffer, " HTTP/1.0\r\n"); strcat(fBuffer, "Content-Type: text/xml; charset=utf-8\r\n"); strcat(fBuffer, "Host: "); strcat(fBuffer, hostNameAsCharStar); if (portNumber != 80) { int i = strlen(fBuffer); sprintf(fBuffer+i, ":%d", portNumber); } strcat(fBuffer, "\r\n"); strcat(fBuffer, "Content-Length: "); int i = (int) strlen(fBuffer); sprintf(fBuffer+i, "%d", strlen(content)); strcat(fBuffer, "\r\n"); strcat(fBuffer, "SOAPAction: \"\"\r\n"); /* strcat(fBuffer, "Connection: Close\r\n"); strcat(fBuffer, "Cache-Control: no-cache\r\n");*/ strcat(fBuffer, "\r\n"); // Now the content strcat(fBuffer, content); // Send the http request int lent = strlen(fBuffer); int aLent = 0; if ((aLent = write(s, (void *) fBuffer, lent)) != lent) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error writing to socket"); } // // get the response, check the http header for errors from the server. // aLent = read(s, (void *)fBuffer, sizeof(fBuffer)-1); /* fBuffer[aLent] = '\0'; printf(fBuffer); */ if (aLent <= 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } fBufferEnd = fBuffer+aLent; *fBufferEnd = 0; // Find the break between the returned http header and any data. // (Delimited by a blank line) // Hang on to any data for use by the first read from this BinHTTPURLInputStream. // fBufferPos = strstr(fBuffer, "\r\n\r\n"); if (fBufferPos != 0) { fBufferPos += 4; *(fBufferPos-2) = 0; } else { fBufferPos = strstr(fBuffer, "\n\n"); if (fBufferPos != 0) { fBufferPos += 2; *(fBufferPos-1) = 0; } else fBufferPos = fBufferEnd; } // Make sure the header includes an HTTP 200 OK response. // char *p = strstr(fBuffer, "HTTP"); if (p == 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } p = strchr(p, ' '); if (p == 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } int httpResponse = atoi(p); if (httpResponse == 302 || httpResponse == 301) { //Once grows, should use a switch char redirectBuf[256]; int q; // Find the "Location:" string p = strstr(p, "Location:"); if (p == 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } p = strchr(p, ' '); if (p == 0) { throw XSECException(XSECException::HTTPURIInputStreamError, "Error reported reading socket"); } // Now read p++; for (q=0; q < 255 && p[q] != '\r' && p[q] !='\n'; ++q) redirectBuf[q] = p[q]; redirectBuf[q] = '\0'; // Try to find this location m_uri = XMLUri(XMLString::transcode(redirectBuf)); return doRequest(request); } else if (httpResponse != 200) { // Most likely a 404 Not Found error. // Should recognize and handle the forwarding responses. // char * q = strstr(p, "\n"); if (q == NULL) q = strstr(p, "\r"); if (q != NULL) *q = '\0'; safeBuffer sb; sb.sbStrcpyIn("SOAPRequestorSimple HTTP Error : "); if (strlen(p) < 256) sb.sbStrcatIn(p); throw XSECException(XSECException::HTTPURIInputStreamError, sb.rawCharBuffer()); } /* Now find out how long the return is */ p = strstr(fBuffer, "Content-Length:"); int responseLength; if (p == NULL) { // Need to work it out from the amount of data returned responseLength = -1; } else { p = strchr(p, ' '); p++; responseLength = atoi(p); } safeBuffer responseBuffer; lent = fBufferEnd - fBufferPos; responseBuffer.sbMemcpyIn(fBufferPos, lent); while (responseLength == -1 || lent < responseLength) { aLent = read(s, (void *)fBuffer, sizeof(fBuffer)-1); if (aLent > 0) { responseBuffer.sbMemcpyIn(lent, fBuffer, aLent); lent += aLent; } else { responseLength = 0; } } return parseAndUnwrap(responseBuffer.rawCharBuffer(), lent); #if 0 char * responseBuffer; XSECnew(responseBuffer, char[responseLength]); ArrayJanitor<char> j_responseBuffer(responseBuffer); lent = fBufferEnd - fBufferPos; memcpy(responseBuffer, fBufferPos, lent); while (lent < responseLength) { aLent = read(s, &responseBuffer[lent], responseLength - lent); lent += aLent; } return parseAndUnwrap(responseBuffer, responseLength); #endif } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Version.h" #include "D435iCamera.h" #include "Visualizer.h" #include <librealsense2/rs.hpp> #include <librealsense2/rsutil.h> #include <librealsense2/hpp/rs_pipeline.hpp> /** RealSense SDK2 Cross-Platform Depth Camera Backend **/ namespace ark { D435iCamera::D435iCamera(): last_ts_g(0), kill(false) { //Setup camera //TODO: Make read from config file rs2::context ctx; device = ctx.query_devices().front(); width = 640; height = 480; //Setup configuration config.enable_stream(RS2_STREAM_DEPTH,-1,width, height,RS2_FORMAT_Z16,30); config.enable_stream(RS2_STREAM_INFRARED, 1, width, height, RS2_FORMAT_Y8, 30); config.enable_stream(RS2_STREAM_INFRARED, 2, width, height, RS2_FORMAT_Y8, 30); config.enable_stream(RS2_STREAM_COLOR, -1, width, height, RS2_FORMAT_RGB8, 30); motion_config.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F,250); motion_config.enable_stream(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F,200); imu_rate=200; //setting imu_rate to be the gyro rate since we are using the gyro timestamps //Need to get the depth sensor specifically as it is the one that controls the sync funciton depth_sensor = new rs2::depth_sensor(device.first<rs2::depth_sensor>()); scale = depth_sensor->get_option(RS2_OPTION_DEPTH_UNITS); rs2::sensor color_sensor = device.query_sensors()[1]; color_sensor.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE,false); } D435iCamera::~D435iCamera() { try { kill=true; imuReaderThread_.join(); pipe->stop(); if(depth_sensor){ delete depth_sensor; depth_sensor=nullptr; } } catch (...) {} } void D435iCamera::start(){ //enable sync //depth_sensor->set_option(RS2_OPTION_INTER_CAM_SYNC_MODE,1); //depth_sensor->set_option(RS2_OPTION_EMITTER_ENABLED, 1.f); //start streaming pipe = std::make_shared<rs2::pipeline>(); rs2::pipeline_profile selection = pipe->start(config); //get the depth intrinsics (needed for projection to 3d) auto depthStream = selection.get_stream(RS2_STREAM_DEPTH) .as<rs2::video_stream_profile>(); depthIntrinsics = depthStream.get_intrinsics(); auto dev = selection.get_device(); auto sensors = dev.query_sensors(); #ifdef RS2_OPTION_GLOBAL_TIME_ENABLED for (auto sensor: sensors) { sensor.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, false); } #endif motion_pipe = std::make_shared<rs2::pipeline>(); rs2::pipeline_profile selection_motion = motion_pipe->start(motion_config); auto dev_motion = selection_motion.get_device(); auto sensors_motion = dev_motion.query_sensors(); #ifdef RS2_OPTION_GLOBAL_TIME_ENABLED for (auto sensor: sensors_motion) { sensor.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, false); } #endif imuReaderThread_ = std::thread(&D435iCamera::imuReader, this); } void D435iCamera::imuReader(){ while(!kill){ auto frames = motion_pipe->wait_for_frames(); auto fa = frames.first(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F) .as<rs2::motion_frame>(); auto fg = frames.first(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F) .as<rs2::motion_frame>(); double ts_g = fg.get_timestamp(); if(ts_g != last_ts_g){ last_ts_g=ts_g; // std::cout << "GYRO: " << ts_g / 1e2 << std::endl; // Get gyro measures rs2_vector gyro_data = fg.get_motion_data(); // Get the timestamp of the current frame double ts_a = fa.get_timestamp(); //std::cout << "ACCEL: " << ts_a << std::endl; // Get accelerometer measures rs2_vector accel_data = fa.get_motion_data(); ImuPair imu_out { double(ts_g)*1e6, //convert to nanoseconds, for some reason gyro timestamp is in centiseconds Eigen::Vector3d(gyro_data.x,gyro_data.y,gyro_data.z), Eigen::Vector3d(accel_data.x,accel_data.y,accel_data.z)}; imu_queue_.enqueue(imu_out); } } } bool D435iCamera::getImuToTime(double timestamp, std::vector<ImuPair>& data_out){ ImuPair imu_data; imu_data.timestamp=0; while((imu_data.timestamp+1e9/imu_rate)<timestamp){ if(imu_queue_.try_dequeue(&imu_data)){ data_out.push_back(imu_data); } } return true; }; const std::string D435iCamera::getModelName() const { return "RealSense"; } cv::Size D435iCamera::getImageSize() const { return cv::Size(width,height); } void D435iCamera::update(MultiCameraFrame & frame) { try { // Ensure the frame has space for all images frame.images_.resize(5); // Get frames from camera auto frames = pipe->wait_for_frames(); auto infrared = frames.get_infrared_frame(1); auto infrared2 = frames.get_infrared_frame(2); auto depth = frames.get_depth_frame(); auto color = frames.get_color_frame(); // Store ID for later frame.frameId_ = depth.get_frame_number(); if(depth.supports_frame_metadata(RS2_FRAME_METADATA_SENSOR_TIMESTAMP)){ frame.timestamp_= depth.get_frame_metadata(RS2_FRAME_METADATA_SENSOR_TIMESTAMP)*1e3; //std::cout << "Image: " << std::fixed << frame.timestamp_/1e3 << std::endl; }else{ std::cout << "No Metadata" << std::endl; } // Convert infrared frame to opencv if (frame.images_[0].empty()) frame.images_[0] = cv::Mat(cv::Size(width,height), CV_8UC1); std::memcpy( frame.images_[0].data, infrared.get_data(),width * height); if (frame.images_[1].empty()) frame.images_[1] = cv::Mat(cv::Size(width,height), CV_8UC1); std::memcpy( frame.images_[1].data, infrared2.get_data(),width * height); if (frame.images_[2].empty()) frame.images_[2] = cv::Mat(cv::Size(width,height), CV_32FC3); project(depth, frame.images_[2]); frame.images_[2] = frame.images_[2]*scale; //depth is in mm by default if (frame.images_[3].empty()) frame.images_[3] = cv::Mat(cv::Size(width,height), CV_8UC3); std::memcpy( frame.images_[3].data, color.get_data(),3 * width * height); if (frame.images_[4].empty()) frame.images_[4] = cv::Mat(cv::Size(width,height), CV_16UC1); // 16 bits = 2 bytes std::memcpy(frame.images_[4].data, depth.get_data(),width * height * 2); } catch (std::runtime_error e) { // Try reconnecting badInputFlag = true; pipe->stop(); printf("Couldn't connect to camera, retrying in 0.5s...\n"); boost::this_thread::sleep_for(boost::chrono::milliseconds(500)); //query_intrinsics(); pipe->start(config); badInputFlag = false; return; } } // project depth map to xyz coordinates directly (faster and minimizes distortion, but will not be aligned to RGB/IR) void D435iCamera::project(const rs2::frame & depth_frame, cv::Mat & xyz_map) { const uint16_t * depth_data = (const uint16_t *)depth_frame.get_data(); rs2_intrinsics * dIntrin = &depthIntrinsics; const uint16_t * srcPtr; cv::Vec3f * destPtr; float srcPixel[2], destXYZ[3]; for (int r = 0; r < height; ++r) { srcPtr = depth_data + r * dIntrin->width; destPtr = xyz_map.ptr<Vec3f>(r); srcPixel[1] = r; for (int c = 0; c < width; ++c) { if (srcPtr[c] == 0) { memset(&destPtr[c], 0, 3 * sizeof(float)); continue; } srcPixel[0] = c; rs2_deproject_pixel_to_point(destXYZ, dIntrin, srcPixel, srcPtr[c]); memcpy(&destPtr[c], destXYZ, 3 * sizeof(float)); } } } const rs2_intrinsics &D435iCamera::getDepthIntrinsics() { return depthIntrinsics; } double D435iCamera::getDepthScale() { return scale; } } <commit_msg>fixed bug with new start<commit_after>#include "stdafx.h" #include "Version.h" #include "D435iCamera.h" #include "Visualizer.h" #include <librealsense2/rs.h> #include <librealsense2/rs.hpp> #include <librealsense2/rsutil.h> #include <librealsense2/hpp/rs_pipeline.hpp> /** RealSense SDK2 Cross-Platform Depth Camera Backend **/ namespace ark { D435iCamera::D435iCamera(): last_ts_g(0), kill(false) { //Setup camera //TODO: Make read from config file rs2::context ctx; device = ctx.query_devices().front(); width = 640; height = 480; //Setup configuration config.enable_stream(RS2_STREAM_DEPTH,-1,width, height,RS2_FORMAT_Z16,30); config.enable_stream(RS2_STREAM_INFRARED, 1, width, height, RS2_FORMAT_Y8, 30); config.enable_stream(RS2_STREAM_INFRARED, 2, width, height, RS2_FORMAT_Y8, 30); config.enable_stream(RS2_STREAM_COLOR, -1, width, height, RS2_FORMAT_RGB8, 30); motion_config.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F,250); motion_config.enable_stream(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F,200); imu_rate=200; //setting imu_rate to be the gyro rate since we are using the gyro timestamps //Need to get the depth sensor specifically as it is the one that controls the sync funciton depth_sensor = new rs2::depth_sensor(device.first<rs2::depth_sensor>()); scale = depth_sensor->get_option(RS2_OPTION_DEPTH_UNITS); rs2::sensor color_sensor = device.query_sensors()[1]; color_sensor.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE,false); } D435iCamera::~D435iCamera() { try { kill=true; imuReaderThread_.join(); pipe->stop(); if(depth_sensor){ delete depth_sensor; depth_sensor=nullptr; } } catch (...) {} } void D435iCamera::start(){ //enable sync //depth_sensor->set_option(RS2_OPTION_INTER_CAM_SYNC_MODE,1); //depth_sensor->set_option(RS2_OPTION_EMITTER_ENABLED, 1.f); //start streaming pipe = std::make_shared<rs2::pipeline>(); rs2::pipeline_profile selection = pipe->start(config); //get the depth intrinsics (needed for projection to 3d) auto depthStream = selection.get_stream(RS2_STREAM_DEPTH) .as<rs2::video_stream_profile>(); depthIntrinsics = depthStream.get_intrinsics(); if (RS2_API_MAJOR_VERSION > 2 || RS2_API_MAJOR_VERSION == 2 && RS2_API_MINOR_VERSION >= 22) { auto dev = selection.get_device(); auto sensors = dev.query_sensors(); for (auto sensor: sensors) { sensor.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, false); } motion_pipe = std::make_shared<rs2::pipeline>(); rs2::pipeline_profile selection_motion = motion_pipe->start(motion_config); auto dev_motion = selection_motion.get_device(); auto sensors_motion = dev_motion.query_sensors(); for (auto sensor: sensors_motion) { sensor.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, false); } } imuReaderThread_ = std::thread(&D435iCamera::imuReader, this); } void D435iCamera::imuReader(){ while(!kill){ auto frames = motion_pipe->wait_for_frames(); auto fa = frames.first(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F) .as<rs2::motion_frame>(); auto fg = frames.first(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F) .as<rs2::motion_frame>(); double ts_g = fg.get_timestamp(); if(ts_g != last_ts_g){ last_ts_g=ts_g; // std::cout << "GYRO: " << ts_g / 1e2 << std::endl; // Get gyro measures rs2_vector gyro_data = fg.get_motion_data(); // Get the timestamp of the current frame double ts_a = fa.get_timestamp(); //std::cout << "ACCEL: " << ts_a << std::endl; // Get accelerometer measures rs2_vector accel_data = fa.get_motion_data(); ImuPair imu_out { double(ts_g)*1e6, //convert to nanoseconds, for some reason gyro timestamp is in centiseconds Eigen::Vector3d(gyro_data.x,gyro_data.y,gyro_data.z), Eigen::Vector3d(accel_data.x,accel_data.y,accel_data.z)}; imu_queue_.enqueue(imu_out); } } } bool D435iCamera::getImuToTime(double timestamp, std::vector<ImuPair>& data_out){ ImuPair imu_data; imu_data.timestamp=0; while((imu_data.timestamp+1e9/imu_rate)<timestamp){ if(imu_queue_.try_dequeue(&imu_data)){ data_out.push_back(imu_data); } } return true; }; const std::string D435iCamera::getModelName() const { return "RealSense"; } cv::Size D435iCamera::getImageSize() const { return cv::Size(width,height); } void D435iCamera::update(MultiCameraFrame & frame) { try { // Ensure the frame has space for all images frame.images_.resize(5); // Get frames from camera auto frames = pipe->wait_for_frames(); auto infrared = frames.get_infrared_frame(1); auto infrared2 = frames.get_infrared_frame(2); auto depth = frames.get_depth_frame(); auto color = frames.get_color_frame(); // Store ID for later frame.frameId_ = depth.get_frame_number(); if(depth.supports_frame_metadata(RS2_FRAME_METADATA_SENSOR_TIMESTAMP)){ frame.timestamp_= depth.get_frame_metadata(RS2_FRAME_METADATA_SENSOR_TIMESTAMP)*1e3; //std::cout << "Image: " << std::fixed << frame.timestamp_/1e3 << std::endl; }else{ std::cout << "No Metadata" << std::endl; } // Convert infrared frame to opencv if (frame.images_[0].empty()) frame.images_[0] = cv::Mat(cv::Size(width,height), CV_8UC1); std::memcpy( frame.images_[0].data, infrared.get_data(),width * height); if (frame.images_[1].empty()) frame.images_[1] = cv::Mat(cv::Size(width,height), CV_8UC1); std::memcpy( frame.images_[1].data, infrared2.get_data(),width * height); if (frame.images_[2].empty()) frame.images_[2] = cv::Mat(cv::Size(width,height), CV_32FC3); project(depth, frame.images_[2]); frame.images_[2] = frame.images_[2]*scale; //depth is in mm by default if (frame.images_[3].empty()) frame.images_[3] = cv::Mat(cv::Size(width,height), CV_8UC3); std::memcpy( frame.images_[3].data, color.get_data(),3 * width * height); if (frame.images_[4].empty()) frame.images_[4] = cv::Mat(cv::Size(width,height), CV_16UC1); // 16 bits = 2 bytes std::memcpy(frame.images_[4].data, depth.get_data(),width * height * 2); } catch (std::runtime_error e) { // Try reconnecting badInputFlag = true; pipe->stop(); printf("Couldn't connect to camera, retrying in 0.5s...\n"); boost::this_thread::sleep_for(boost::chrono::milliseconds(500)); //query_intrinsics(); pipe->start(config); badInputFlag = false; return; } } // project depth map to xyz coordinates directly (faster and minimizes distortion, but will not be aligned to RGB/IR) void D435iCamera::project(const rs2::frame & depth_frame, cv::Mat & xyz_map) { const uint16_t * depth_data = (const uint16_t *)depth_frame.get_data(); rs2_intrinsics * dIntrin = &depthIntrinsics; const uint16_t * srcPtr; cv::Vec3f * destPtr; float srcPixel[2], destXYZ[3]; for (int r = 0; r < height; ++r) { srcPtr = depth_data + r * dIntrin->width; destPtr = xyz_map.ptr<Vec3f>(r); srcPixel[1] = r; for (int c = 0; c < width; ++c) { if (srcPtr[c] == 0) { memset(&destPtr[c], 0, 3 * sizeof(float)); continue; } srcPixel[0] = c; rs2_deproject_pixel_to_point(destXYZ, dIntrin, srcPixel, srcPtr[c]); memcpy(&destPtr[c], destXYZ, 3 * sizeof(float)); } } } const rs2_intrinsics &D435iCamera::getDepthIntrinsics() { return depthIntrinsics; } double D435iCamera::getDepthScale() { return scale; } } <|endoftext|>
<commit_before>//sys_init_policy.hpp chromatic universe 2017-2020 william k. johnson #include <memory> #include <string> //contrib #include "ace/Log_Msg.h" #include "ace/Trace.h" //cci #include <cci_time_utils.h> #include <cci_daemonize.h> using namespace cpp_real_stream; namespace cci_policy { // //system init policies // template<typename T> class runtime_sys_init { public : //ctor runtime_sys_init( T meta ) : m_tutils( std::make_unique<time_utils>() ) , m_meta( meta ) {} private : //attributes std::unique_ptr<std::string> m_runtime_data; std::unique_ptr<cpp_real_stream::time_utils> m_tutils; T m_meta; protected : //dtor ~runtime_sys_init() {} public : //accessors-inspctiors std::string runtime_data() const noexcept { return *m_runtime_data.get(); } cpp_real_stream::time_utils_ptr _t() { return m_tutils.get(); } //mutators void runtime_data( std::unique_ptr<std::string>& data ) { m_runtime_data = std::move( data ); } //services void configure_init ( T meta ) { cci_daemonize::daemon_proc dp = cci_daemonize::daemon_proc::dp_fork_background_proc; ACE_TRACE ("runtime_sys_init::configure_init"); while( dp != cci_daemonize::daemon_proc::dp_error ) { switch( dp ) { case cci_daemonize::daemon_proc::dp_fork_background_proc : { //become background process switch( fork() ) { case -1 : dp = cci_daemonize::daemon_proc::dp_error; break; case 0 : dp = cci_daemonize::daemon_proc::dp_make_session_leader; break; default: _exit( EXIT_SUCCESS ); } break; } case cci_daemonize::daemon_proc::dp_make_session_leader : { //become leader of new session setsid() == -1 ? dp = cci_daemonize::daemon_proc::dp_error : dp = cci_daemonize::daemon_proc::dp_fork_no_session_leader; break; } case cci_daemonize::daemon_proc::dp_fork_no_session_leader : { //ensure we are not session leader switch( fork() ) { case -1 : dp = cci_daemonize::daemon_proc::dp_error; break; case 0 : dp = cci_daemonize::daemon_proc::dp_daemonized; break; default: _exit( EXIT_SUCCESS ); } break; } default : break; } if ( dp == cci_daemonize::daemon_proc::dp_daemonized ) { break; } } } }; // template<typename T> class custom_sys_init { private : //attributes std::unique_ptr<std::string> m_runtime_data; protected : //dtor ~custom_sys_init() {} public : //accessors-inspctiors std::string runtime_data() const noexcept { return *m_runtime_data.get(); } //services void configure_init() { // } }; } <commit_msg>evening<commit_after>//sys_init_policy.hpp william k. johnon 2020 #include <memory> #include <string> //contrib #include "ace/Log_Msg.h" #include "ace/Trace.h" //cci #include <cci_time_utils.h> #include <cci_daemonize.h> using namespace cpp_real_stream; namespace cci_policy { // //system init policies // template<typename T> class runtime_sys_init { public : //ctor runtime_sys_init( T meta ) : m_tutils( std::make_unique<time_utils>() ) , m_meta( meta ) {} private : //attributes std::unique_ptr<std::string> m_runtime_data; std::unique_ptr<cpp_real_stream::time_utils> m_tutils; T m_meta; protected : //dtor ~runtime_sys_init() {} public : //accessors-inspctiors std::string runtime_data() const noexcept { return *m_runtime_data.get(); } cpp_real_stream::time_utils_ptr _t() { return m_tutils.get(); } //mutators void runtime_data( std::unique_ptr<std::string>& data ) { m_runtime_data = std::move( data ); } //services void configure_init ( T meta ) { cci_daemonize::daemon_proc dp = cci_daemonize::daemon_proc::dp_fork_background_proc; ACE_TRACE ("runtime_sys_init::configure_init"); while( dp != cci_daemonize::daemon_proc::dp_error ) { switch( dp ) { case cci_daemonize::daemon_proc::dp_fork_background_proc : { //become background process switch( fork() ) { case -1 : dp = cci_daemonize::daemon_proc::dp_error; break; case 0 : dp = cci_daemonize::daemon_proc::dp_make_session_leader; break; default: _exit( EXIT_SUCCESS ); } break; } case cci_daemonize::daemon_proc::dp_make_session_leader : { //become leader of new session setsid() == -1 ? dp = cci_daemonize::daemon_proc::dp_error : dp = cci_daemonize::daemon_proc::dp_fork_no_session_leader; break; } case cci_daemonize::daemon_proc::dp_fork_no_session_leader : { //ensure we are not session leader switch( fork() ) { case -1 : dp = cci_daemonize::daemon_proc::dp_error; break; case 0 : dp = cci_daemonize::daemon_proc::dp_daemonized; break; default: _exit( EXIT_SUCCESS ); } break; } } if ( dp == cci_daemonize::daemon_proc::dp_daemonized ) { break; } } } }; // template<typename T> class custom_sys_init { private : //attributes std::unique_ptr<std::string> m_runtime_data; protected : //dtor ~custom_sys_init() {} public : //accessors-inspctiors std::string runtime_data() const noexcept { return *m_runtime_data.get(); } //services void configure_init() { // } }; } <|endoftext|>
<commit_before>/* * Copyright 2016 Facebook, 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 <folly/portability/String.h> #if !FOLLY_HAVE_MEMRCHR extern "C" void* memrchr(const void* s, int c, size_t n) { for (auto p = ((const char*)s) + n - 1; p >= (const char*)s; p--) { if (*p == (char)c) { return (void*)p; } } return nullptr; } #endif #if defined(_WIN32) || defined(__APPLE__) || defined(__FreeBSD__) extern "C" char* strndup(const char* a, size_t len) { auto neededLen = strlen(a); if (neededLen > len) { neededLen = len; } char* buf = (char*)malloc((neededLen + 1) * sizeof(char)); if (!buf) { return nullptr; } memcpy(buf, a, neededLen); buf[neededLen] = '\0'; return buf; } #endif #ifdef _WIN32 extern "C" { void bzero(void* s, size_t n) { memset(s, 0, n); } int strcasecmp(const char* a, const char* b) { return _stricmp(a, b); } int strncasecmp(const char* a, const char* b, size_t c) { return _strnicmp(a, b, c); } char* strtok_r(char* str, char const* delim, char** ctx) { return strtok_s(str, delim, ctx); } } #endif <commit_msg>Forgot to fix the guard for String.cpp<commit_after>/* * Copyright 2016 Facebook, 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 <folly/portability/String.h> #if !FOLLY_HAVE_MEMRCHR extern "C" void* memrchr(const void* s, int c, size_t n) { for (auto p = ((const char*)s) + n - 1; p >= (const char*)s; p--) { if (*p == (char)c) { return (void*)p; } } return nullptr; } #endif #if defined(_WIN32) || defined(__FreeBSD__) extern "C" char* strndup(const char* a, size_t len) { auto neededLen = strlen(a); if (neededLen > len) { neededLen = len; } char* buf = (char*)malloc((neededLen + 1) * sizeof(char)); if (!buf) { return nullptr; } memcpy(buf, a, neededLen); buf[neededLen] = '\0'; return buf; } #endif #ifdef _WIN32 extern "C" { void bzero(void* s, size_t n) { memset(s, 0, n); } int strcasecmp(const char* a, const char* b) { return _stricmp(a, b); } int strncasecmp(const char* a, const char* b, size_t c) { return _strnicmp(a, b, c); } char* strtok_r(char* str, char const* delim, char** ctx) { return strtok_s(str, delim, ctx); } } #endif <|endoftext|>
<commit_before>/* ** Copyright 2011 Merethis ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <QFile> #include <rrd.h> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" #include "com/centreon/broker/rrd/lib.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; /************************************** * * * Public Methods * * * **************************************/ /** * Default constructor. */ lib::lib() {} /** * Copy constructor. * * @param[in] l Object to copy. */ lib::lib(lib const& l) : backend(l), _filename(l._filename), _metric(l._metric) {} /** * Destructor. */ lib::~lib() {} /** * Assignment operator. * * @param[in] l Object to copy. * * @return This object. */ lib& lib::operator=(lib const& l) { backend::operator=(l); _filename = l._filename; _metric = l._metric; return (*this); } /** * @brief Initiates the bulk load of multiple commands. * * With the librrd backend, this method does nothing. */ void lib::begin() { return ; } /** * Close the RRD file. */ void lib::close() { _filename.clear(); _metric.clear(); return ; } /** * @brief Commit transaction started with begin(). * * With the librrd backend, the method does nothing. */ void lib::commit() { return ; } /** * Normalize a metric name. * * @param[in] metric Metric name. * * @return Normalized metric name. */ QString lib::normalize_metric_name(QString const& metric) { QString normalized(metric); normalized.replace('.', '-'); normalized.replace(':', '-'); normalized.replace(',', '-'); normalized.replace('{', '-'); normalized.replace('}', '-'); normalized.replace('[', '-'); normalized.replace(']', '-'); normalized.replace(' ', '-'); normalized.replace("/", "_slash"); normalized.replace("\\", "_bslash"); return (normalized); } /** * Open a RRD file which already exists. * * @param[in] filename Path to the RRD file. * @param[in] metric Metric name. */ void lib::open(QString const& filename, QString const& metric) { // Close previous file. this->close(); // Check that the file exists. if (!QFile::exists(filename)) throw (exceptions::open() << "RRD: file '" << filename << "' does not exist"); // Remember information for further operations. _filename = filename; _metric = normalize_metric_name(metric); return ; } /** * Open a RRD file and create it if it does not exists. * * @param[in] filename Path to the RRD file. * @param[in] metric Metric name. * @param[in] length Number of recording in the RRD file. * @param[in] from Timestamp of the first record. * @param[in] interval Time interval between each record. */ void lib::open(QString const& filename, QString const& metric, unsigned int length, time_t from, time_t interval) { logging::debug << logging::HIGH << "RRD: opening file '" << filename << "'"; // Close previous file. this->close(); // Remember informations for further operations. _filename = filename; _metric = normalize_metric_name(metric); /* Find step of RRD file if already existing. */ /* XXX : why is it here ? rrd_info_t* rrdinfo(rrd_info_r(_filename)); time_t interval_offset(0); for (rrd_info_t* tmp = rrdinfo; tmp; tmp = tmp->next) if (!strcmp(rrdinfo->key, "step")) if (interval < static_cast<time_t>(rrdinfo->value.u_cnt)) interval_offset = rrdinfo->value.u_cnt / interval - 1; rrd_info_free(rrdinfo); */ /* Remove previous file. */ QFile::remove(_filename); /* Set parameters. */ std::ostringstream ds_oss; std::ostringstream rra1_oss; std::ostringstream rra2_oss; ds_oss << "DS:" << _metric.toStdString() << ":GAUGE:" << interval << ":U:U"; rra1_oss << "RRA:AVERAGE:0.5:1:" << length; rra2_oss << "RRA:AVERAGE:0.5:12:" << length; std::string ds(ds_oss.str()); std::string rra1(rra1_oss.str()); std::string rra2(rra2_oss.str()); char const* argv[4]; argv[0] = ds.c_str(); argv[1] = rra1.c_str(); argv[2] = rra2.c_str(); argv[3] = NULL; /* Create RRD file. */ rrd_clear_error(); if (rrd_create_r(_filename.toStdString().c_str(), interval, from, sizeof(argv) / sizeof(*argv) - 1, argv)) throw (exceptions::open() << "RRD: could not create file '" << _filename << "': " << rrd_get_error()); // XXX : is tuning really needed ? return ; } /** * Update the RRD file with new value. * * @param[in] t Timestamp of value. * @param[in] value Associated value. */ void lib::update(time_t t, QString const& value) { logging::debug << logging::HIGH << "RRD: updating file"; // Build argument string. std::string arg; { std::ostringstream oss; oss << t << ":" << value.toStdString(); arg = oss.str(); } // Set argument table. char const* argv[2]; argv[0] = arg.c_str(); argv[1] = NULL; // Update RRD file. rrd_clear_error(); if (rrd_update_r(_filename.toStdString().c_str(), _metric.toStdString().c_str(), sizeof(argv) / sizeof(*argv) - 1, argv)) throw (exceptions::update() << "RRD: failed to update value for " \ "metric " << _metric << ": " << rrd_get_error()); return ; } <commit_msg>Added locking to RRD files before update to avoid conflict with the rebuild process.<commit_after>/* ** Copyright 2011 Merethis ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <fcntl.h> #include <QFile> #include <rrd.h> #include <sstream> #include <string.h> #include <unistd.h> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" #include "com/centreon/broker/rrd/lib.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; /************************************** * * * Public Methods * * * **************************************/ /** * Default constructor. */ lib::lib() {} /** * Copy constructor. * * @param[in] l Object to copy. */ lib::lib(lib const& l) : backend(l), _filename(l._filename), _metric(l._metric) {} /** * Destructor. */ lib::~lib() {} /** * Assignment operator. * * @param[in] l Object to copy. * * @return This object. */ lib& lib::operator=(lib const& l) { backend::operator=(l); _filename = l._filename; _metric = l._metric; return (*this); } /** * @brief Initiates the bulk load of multiple commands. * * With the librrd backend, this method does nothing. */ void lib::begin() { return ; } /** * Close the RRD file. */ void lib::close() { _filename.clear(); _metric.clear(); return ; } /** * @brief Commit transaction started with begin(). * * With the librrd backend, the method does nothing. */ void lib::commit() { return ; } /** * Normalize a metric name. * * @param[in] metric Metric name. * * @return Normalized metric name. */ QString lib::normalize_metric_name(QString const& metric) { QString normalized(metric); normalized.replace('.', '-'); normalized.replace(':', '-'); normalized.replace(',', '-'); normalized.replace('{', '-'); normalized.replace('}', '-'); normalized.replace('[', '-'); normalized.replace(']', '-'); normalized.replace(' ', '-'); normalized.replace("/", "_slash"); normalized.replace("\\", "_bslash"); return (normalized); } /** * Open a RRD file which already exists. * * @param[in] filename Path to the RRD file. * @param[in] metric Metric name. */ void lib::open(QString const& filename, QString const& metric) { // Close previous file. this->close(); // Check that the file exists. if (!QFile::exists(filename)) throw (exceptions::open() << "RRD: file '" << filename << "' does not exist"); // Remember information for further operations. _filename = filename; _metric = normalize_metric_name(metric); return ; } /** * Open a RRD file and create it if it does not exists. * * @param[in] filename Path to the RRD file. * @param[in] metric Metric name. * @param[in] length Number of recording in the RRD file. * @param[in] from Timestamp of the first record. * @param[in] interval Time interval between each record. */ void lib::open(QString const& filename, QString const& metric, unsigned int length, time_t from, time_t interval) { logging::debug << logging::HIGH << "RRD: opening file '" << filename << "'"; // Close previous file. this->close(); // Remember informations for further operations. _filename = filename; _metric = normalize_metric_name(metric); /* Find step of RRD file if already existing. */ /* XXX : why is it here ? rrd_info_t* rrdinfo(rrd_info_r(_filename)); time_t interval_offset(0); for (rrd_info_t* tmp = rrdinfo; tmp; tmp = tmp->next) if (!strcmp(rrdinfo->key, "step")) if (interval < static_cast<time_t>(rrdinfo->value.u_cnt)) interval_offset = rrdinfo->value.u_cnt / interval - 1; rrd_info_free(rrdinfo); */ /* Remove previous file. */ QFile::remove(_filename); /* Set parameters. */ std::ostringstream ds_oss; std::ostringstream rra1_oss; std::ostringstream rra2_oss; ds_oss << "DS:" << _metric.toStdString() << ":GAUGE:" << interval << ":U:U"; rra1_oss << "RRA:AVERAGE:0.5:1:" << length; rra2_oss << "RRA:AVERAGE:0.5:12:" << length; std::string ds(ds_oss.str()); std::string rra1(rra1_oss.str()); std::string rra2(rra2_oss.str()); char const* argv[4]; argv[0] = ds.c_str(); argv[1] = rra1.c_str(); argv[2] = rra2.c_str(); argv[3] = NULL; /* Create RRD file. */ rrd_clear_error(); if (rrd_create_r(_filename.toStdString().c_str(), interval, from, sizeof(argv) / sizeof(*argv) - 1, argv)) throw (exceptions::open() << "RRD: could not create file '" << _filename << "': " << rrd_get_error()); // XXX : is tuning really needed ? return ; } /** * Update the RRD file with new value. * * @param[in] t Timestamp of value. * @param[in] value Associated value. */ void lib::update(time_t t, QString const& value) { logging::debug << logging::HIGH << "RRD: updating file"; // Build argument string. std::string arg; { std::ostringstream oss; oss << t << ":" << value.toStdString(); arg = oss.str(); } // Set argument table. char const* argv[2]; argv[0] = arg.c_str(); argv[1] = NULL; // Update RRD file. int fd(::open(_filename.toStdString().c_str(), O_WRONLY)); if (fd < 0) { char const* msg(strerror(errno)); logging::error << logging::MEDIUM << "RRD: could not open file '" << _filename << "': " << msg; } else { try { // Set lock. flock fl; memset(&fl, 0, sizeof(fl)); fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; if (-1 == fcntl(fd, F_SETLK, &fl)) { char const* msg(strerror(errno)); logging::error << logging::MEDIUM << "RRD: could not lock file '" << _filename << "': " << msg; } else { rrd_clear_error(); if (rrd_update_r(_filename.toStdString().c_str(), _metric.toStdString().c_str(), sizeof(argv) / sizeof(*argv) - 1, argv)) throw (exceptions::update() << "RRD: failed to update value for metric " << _metric << ": " << rrd_get_error()); } } catch (...) { ::close(fd); throw ; } ::close(fd); } return ; } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Daniel Strohmeier <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date March, 2018 * * @section LICENSE * * Copyright (C) 2018, Daniel Strohmeier and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Example of the computation of spectra, PSD and CSD * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <math.h> #include <disp/plot.h> #include <utils/spectral.h> #include <mne/mne.h> //************************************************************************************************************* //============================================================================================================= // Eigen //============================================================================================================= #include <Eigen/Core> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QApplication> #include <QtMath> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace DISPLIB; using namespace UTILSLIB; //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QApplication a(argc, argv); // Generate input data int iNSamples = 500; MatrixXd inputData = MatrixXd::Random(2, iNSamples); for (int n = 0; n < iNSamples; n++) { inputData(0, n) += 10.0 * sin(2.0 * M_PI * 10. * n / iNSamples ); inputData(0, n) += 10.0 * sin(2.0 * M_PI * 100. * n / iNSamples); inputData(0, n) += 10.0 * sin(2.0 * M_PI * 200. * n / iNSamples); inputData(1, n) += 10.0 * sin(2.0 * M_PI * 50. * n / iNSamples); inputData(1, n) += 10.0 * sin(2.0 * M_PI * 100. * n / iNSamples); inputData(1, n) += 10.0 * sin(2.0 * M_PI * 150. * n / iNSamples); } //Generate hanning window QPair<MatrixXd, VectorXd> tapers = Spectral::generateTapers(iNSamples, "hanning"); MatrixXd matTaps = tapers.first; VectorXd vecTapWeights = tapers.second; //Plot hanning window VectorXd hann = matTaps.row(0).transpose(); Plot plotWindow(hann); plotWindow.setTitle("Hanning window"); plotWindow.setXLabel("X Axes"); plotWindow.setYLabel("Y Axes"); plotWindow.setWindowTitle("Corresponding function to MATLABs plot"); plotWindow.show(); //Compute Spectrum of first row of input data int iNfft = iNSamples; MatrixXcd matTapSpectrumSeed = Spectral::computeTaperedSpectra(inputData.row(0), matTaps, iNfft); //Compute PSD RowVectorXd vecPsd = Spectral::psdFromTaperedSpectra(matTapSpectrumSeed, vecTapWeights, iNfft); //Plot PSD VectorXd psd = vecPsd.transpose(); Plot plotPsd(psd); plotPsd.setTitle("PSD of Row 0"); plotPsd.setXLabel("X Axes"); plotPsd.setYLabel("Y Axes"); plotPsd.setWindowTitle("Corresponding function to MATLABs plot"); plotPsd.show(); //Check PSD VectorXd psdTest = matTapSpectrumSeed.row(0).cwiseAbs2().transpose() / double(iNfft); psdTest *= 2.0; psdTest(0) /= 2.0; if (iNfft % 2 == 0){ psdTest.tail(1) /= 2.0; } //Plot PSDTest Plot plotPsdTest(psdTest); plotPsdTest.setTitle("PSD of Row 0"); plotPsdTest.setXLabel("X Axes"); plotPsdTest.setYLabel("Y Axes"); plotPsdTest.setWindowTitle("Corresponding function to MATLABs plot"); plotPsdTest.show(); //Compute CSD of matTapSpectrumSeed and matTapSpectrumSeed //The real part should be equivalent to the PSD of matTapSpectrumSeed) RowVectorXcd vecCsdSeed = Spectral::csdFromTaperedSpectra(matTapSpectrumSeed, matTapSpectrumSeed, vecTapWeights, vecTapWeights, iNfft); VectorXd psdTest2 = vecCsdSeed.real(); //Plot PSDTest2 Plot plotPsdTest2(psdTest2); plotPsdTest2.setTitle("PSD of Row 0"); plotPsdTest2.setXLabel("X Axes"); plotPsdTest2.setYLabel("Y Axes"); plotPsdTest2.setWindowTitle("Corresponding function to MATLABs plot"); plotPsdTest2.show(); //Check energy RowVectorXd data_hann = inputData.row(0).cwiseProduct(matTaps.row(0)); qDebug()<<"data0 energy"<<data_hann.row(0).cwiseAbs2().sum(); qDebug()<<"sum psd"<<psd.sum(); qDebug()<<"sum psdTest"<<psdTest.sum(); qDebug()<<"sum psdTest2"<<psdTest2.sum(); //Compute Spectrum of second row of input data MatrixXcd matTapSpectrumTarget = Spectral::computeTaperedSpectra(inputData.row(1), matTaps, iNfft); //Compute CSD between seed and target RowVectorXcd vecCsd = Spectral::csdFromTaperedSpectra(matTapSpectrumSeed, matTapSpectrumTarget, vecTapWeights, vecTapWeights, iNfft); //Plot real part of CSD VectorXd csd = vecCsd.transpose().real(); Plot plotCsd(csd); plotCsd.setTitle("Real part of the CSD of Row 0 and 1"); plotCsd.setXLabel("X Axes"); plotCsd.setYLabel("Y Axes"); plotCsd.setWindowTitle("Corresponding function to MATLABs plot"); plotCsd.show(); return a.exec(); } <commit_msg>example<commit_after>//============================================================================================================= /** * @file main.cpp * @author Daniel Strohmeier <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date March, 2018 * * @section LICENSE * * Copyright (C) 2018, Daniel Strohmeier and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Example of the computation of spectra, PSD and CSD * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <math.h> #include <disp/plot.h> #include <utils/spectral.h> #include <mne/mne.h> //************************************************************************************************************* //============================================================================================================= // Eigen //============================================================================================================= #include <Eigen/Core> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QApplication> #include <QtMath> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace DISPLIB; using namespace UTILSLIB; //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QApplication a(argc, argv); // Generate input data int iNSamples = 500; double dSampFreq = 23.0; MatrixXd inputData = MatrixXd::Random(2, iNSamples); for (int n = 0; n < iNSamples; n++) { inputData(0, n) += 10.0 * sin(2.0 * M_PI * 10. * n / iNSamples ); inputData(0, n) += 10.0 * sin(2.0 * M_PI * 100. * n / iNSamples); inputData(0, n) += 10.0 * sin(2.0 * M_PI * 200. * n / iNSamples); inputData(1, n) += 10.0 * sin(2.0 * M_PI * 50. * n / iNSamples); inputData(1, n) += 10.0 * sin(2.0 * M_PI * 100. * n / iNSamples); inputData(1, n) += 10.0 * sin(2.0 * M_PI * 150. * n / iNSamples); } //Generate hanning window QPair<MatrixXd, VectorXd> tapers = Spectral::generateTapers(iNSamples, "hanning"); MatrixXd matTaps = tapers.first; VectorXd vecTapWeights = tapers.second; //Plot hanning window VectorXd hann = matTaps.row(0).transpose(); Plot plotWindow(hann); plotWindow.setTitle("Hanning window"); plotWindow.setXLabel("X Axes"); plotWindow.setYLabel("Y Axes"); plotWindow.setWindowTitle("Corresponding function to MATLABs plot"); plotWindow.show(); //Compute Spectrum of first row of input data int iNfft = iNSamples; MatrixXcd matTapSpectrumSeed = Spectral::computeTaperedSpectra(inputData.row(0), matTaps, iNfft); //Compute PSD RowVectorXd vecPsd = Spectral::psdFromTaperedSpectra(matTapSpectrumSeed, vecTapWeights, iNfft, dSampFreq); //Plot PSD VectorXd psd = vecPsd.transpose(); Plot plotPsd(psd); plotPsd.setTitle("PSD of Row 0"); plotPsd.setXLabel("X Axes"); plotPsd.setYLabel("Y Axes"); plotPsd.setWindowTitle("Corresponding function to MATLABs plot"); plotPsd.show(); //Check PSD VectorXd psdTest = matTapSpectrumSeed.row(0).cwiseAbs2().transpose(); psdTest *= 2.0; psdTest(0) /= 2.0; if (iNfft % 2 == 0){ psdTest.tail(1) /= 2.0; } //Normalization psdTest /= dSampFreq; //Plot PSDTest Plot plotPsdTest(psdTest); plotPsdTest.setTitle("PSD of Row 0"); plotPsdTest.setXLabel("X Axes"); plotPsdTest.setYLabel("Y Axes"); plotPsdTest.setWindowTitle("Corresponding function to MATLABs plot"); plotPsdTest.show(); //Compute CSD of matTapSpectrumSeed and matTapSpectrumSeed //The real part should be equivalent to the PSD of matTapSpectrumSeed) RowVectorXcd vecCsdSeed = Spectral::csdFromTaperedSpectra(matTapSpectrumSeed, matTapSpectrumSeed, vecTapWeights, vecTapWeights, iNfft, dSampFreq); VectorXd psdTest2 = vecCsdSeed.real(); //Plot PSDTest2 Plot plotPsdTest2(psdTest2); plotPsdTest2.setTitle("PSD of Row 0"); plotPsdTest2.setXLabel("X Axes"); plotPsdTest2.setYLabel("Y Axes"); plotPsdTest2.setWindowTitle("Corresponding function to MATLABs plot"); plotPsdTest2.show(); //Check that sums of different psds of the same signal are equal qDebug()<<psd.sum(); qDebug()<<psdTest.sum(); qDebug()<<psdTest2.sum(); RowVectorXd data_hann = inputData.row(0).cwiseProduct(matTaps.row(0)); qDebug()<<data_hann.row(0).cwiseAbs2().sum() * double(iNSamples) / dSampFreq; //Compute Spectrum of second row of input data MatrixXcd matTapSpectrumTarget = Spectral::computeTaperedSpectra(inputData.row(1), matTaps, iNfft); //Compute CSD between seed and target RowVectorXcd vecCsd = Spectral::csdFromTaperedSpectra(matTapSpectrumSeed, matTapSpectrumTarget, vecTapWeights, vecTapWeights, iNfft, dSampFreq); //Plot real part of CSD VectorXd csd = vecCsd.transpose().real(); Plot plotCsd(csd); plotCsd.setTitle("Real part of the CSD of Row 0 and 1"); plotCsd.setXLabel("X Axes"); plotCsd.setYLabel("Y Axes"); plotCsd.setWindowTitle("Corresponding function to MATLABs plot"); plotCsd.show(); return a.exec(); } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2015 Michael G. Brehm // // 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 "stdafx.h" #include "Executable.h" #include <cctype> #include "LinuxException.h" #pragma warning(push, 4) // INTERPRETER_SCRIPT_MAGIC_ANSI // // Magic number present at the head of an ANSI interpreter script static uint8_t INTERPRETER_SCRIPT_MAGIC_ANSI[] = { 0x23, 0x21 }; // INTERPRETER_SCRIPT_MAGIC_UTF8 // // Magic number present at the head of a UTF-8 interpreter script static uint8_t INTERPRETER_SCRIPT_MAGIC_UTF8[] = { 0xEF, 0xBB, 0xBF, 0x23, 0x21 }; //----------------------------------------------------------------------------- // Executable Constructor (private) // // Arguments: // // arch - Executable architecture flag // format - Executable binary format flag // originalpath - Originally specified executable path // handle - Handle instance open against the target file // arguments - Processed command line arguments // environment - Processed environment variables Executable::Executable(enum class Architecture arch, enum class BinaryFormat format, const char_t* originalpath, std::shared_ptr<FileSystem::Handle> handle, string_vector_t&& arguments, string_vector_t&& environment) : m_architecture(arch), m_format(format), m_originalpath(originalpath), m_handle(std::move(handle)), m_arguments(std::move(arguments)), m_environment(std::move(environment)) { } //----------------------------------------------------------------------------- // Executable::getArchitecture // // Gets the architecture flag for the executable enum class Architecture Executable::getArchitecture(void) const { return m_architecture; } //----------------------------------------------------------------------------- // Executable::getFormat // // Gets the binary format of the executable enum class BinaryFormat Executable::getFormat(void) const { return m_format; } //----------------------------------------------------------------------------- // Executable::FromFile (static) // // Creates an executable instance from a file system file // // Arguments: // // ns - Namespace in which to operate // root - Root directory to assign to the process // current - Working directory to assign to the process // path - Path to the executable image std::unique_ptr<Executable> Executable::FromFile(std::shared_ptr<class Namespace> ns, std::shared_ptr<FileSystem::Path> root, std::shared_ptr<FileSystem::Path> current, const char_t* path) { if(path == nullptr) throw LinuxException{ LINUX_EFAULT }; // Provide empty vectors for the arguments and environment variables return FromFile(std::move(ns), std::move(root), std::move(current), path, path, string_vector_t(), string_vector_t()); } //----------------------------------------------------------------------------- // Executable::FromFile (static) // // Creates an executable instance from a file system file // // Arguments: // // ns - Namespace in which to operate // root - Root directory to assign to the process // current - Working directory to assign to the process // path - Path to the executable image // arguments - Array of command-line arguments // environment - Array of environment variables std::unique_ptr<Executable> Executable::FromFile(std::shared_ptr<class Namespace> ns, std::shared_ptr<FileSystem::Path> root, std::shared_ptr<FileSystem::Path> current, const char_t* path, const char_t* const* arguments, const char_t* const* environment) { if(path == nullptr) throw LinuxException{ LINUX_EFAULT }; // Convert the C-style string arrays into vector<string> containers return FromFile(std::move(ns), std::move(root), std::move(current), path, path, StringArrayToVector(arguments), StringArrayToVector(environment)); } //----------------------------------------------------------------------------- // Executable::FromFile (private, static) // // Creates an executable instance from a file system file // // Arguments: // // ns - Namespace in which to operate // root - Root directory to assign to the process // current - Working directory to assign to the process // originalpath - Original path provided for the executable // path - Path to the executable image // arguments - Vector of command-line arguments // environment - Vector of environment variables std::unique_ptr<Executable> Executable::FromFile(namespace_t ns, fspath_t root, fspath_t current, const char_t* originalpath, const char_t* path, string_vector_t&& arguments, string_vector_t&& environment) { if(originalpath == nullptr) throw LinuxException{ LINUX_EFAULT }; if(path == nullptr) throw LinuxException{ LINUX_EFAULT }; // Acquire an execute-only handle for the provided path auto handle = FileSystem::OpenExecutable(ns, root, current, path); // Read in enough data from the beginning of the file to determine the executable type uint8_t magic[LINUX_EI_NIDENT]; size_t read = handle->ReadAt(0, magic, LINUX_EI_NIDENT); // ELF BINARY // if((read >= LINUX_EI_NIDENT) && (memcmp(magic, LINUX_ELFMAG, LINUX_SELFMAG) == 0)) { // Move the file pointer back to the beginning of the file handle->Seek(0, LINUX_SEEK_SET); // This is a binary file, determine the architecture and complete the operation switch(magic[LINUX_EI_CLASS]) { // ELFCLASS32 --> Architecture::x86 case LINUX_ELFCLASS32: return std::make_unique<Executable>(Architecture::x86, BinaryFormat::ELF, originalpath, std::move(handle), std::move(arguments), std::move(environment)); #ifdef _M_X64 // ELFCLASS64: --> Architecture::x86_64 case LINUX_ELFCLASS64: return std::make_unique<Executable>(Architecture::x86_64, BinaryFormat::ELF, originalpath, std::move(handle), std::move(arguments), std::move(environment)); #endif // Unknown ELFCLASS --> ENOEXEC default: throw LinuxException{ LINUX_ENOEXEC }; } } // A.OUT BINARIES // // TODO - FUTURE (OMAGIC, NMAGIC, QMAGIC, etc) // INTERPRETER SCRIPT (UTF-8) // else if((read >= sizeof(INTERPRETER_SCRIPT_MAGIC_UTF8)) && (memcmp(magic, &INTERPRETER_SCRIPT_MAGIC_UTF8, sizeof(INTERPRETER_SCRIPT_MAGIC_UTF8)) == 0)) { return FromScript(std::move(ns), std::move(root), std::move(current), originalpath, std::move(handle), sizeof(INTERPRETER_SCRIPT_MAGIC_UTF8), std::move(arguments), std::move(environment)); } // INTERPRETER SCRIPT (ANSI) // else if((read >= sizeof(INTERPRETER_SCRIPT_MAGIC_ANSI)) && (memcmp(magic, &INTERPRETER_SCRIPT_MAGIC_ANSI, sizeof(INTERPRETER_SCRIPT_MAGIC_ANSI)) == 0)) { return FromScript(std::move(ns), std::move(root), std::move(current), originalpath, std::move(handle), sizeof(INTERPRETER_SCRIPT_MAGIC_ANSI), std::move(arguments), std::move(environment)); } // UNSUPPORTED FORMAT // else throw LinuxException{ LINUX_ENOEXEC }; } //----------------------------------------------------------------------------- // Executable::FromScript (private, static) // // Creates an executable instance from an interpreter script // // Arguments: // // ns - Namespace in which to operate // root - Root directory to assign to the process // current - Working directory to assign to the process // originalpath - Original path provided for the executable // scripthandle - Handle to the interpreter script // dataoffset - Offset of data within the interpreter script // arguments - Vector of command-line arguments // environment - Vector of environment variables std::unique_ptr<Executable> Executable::FromScript(namespace_t ns, fspath_t root, fspath_t current, const char_t* originalpath, fshandle_t scripthandle, size_t dataoffset, string_vector_t&& arguments, string_vector_t&& environment) { char_t buffer[MAX_PATH]; // Script data buffer if(originalpath == nullptr) throw LinuxException{ LINUX_EFAULT }; char_t *begin, *end; // String tokenizing pointers // Read up to MAX_PATH data from the interpreter script file char_t *eof = &buffer[0] + scripthandle->ReadAt(dataoffset, &buffer[0], sizeof(buffer)); // Find the interperter path, if not present the script is not a valid target for(begin = &buffer[0]; (begin < eof) && (*begin) && (*begin != '\n') && (std::isspace(*begin)); begin++); for(end = begin; (end < eof) && (*end) && (*end != '\n') && (!std::isspace(*end)); end++); if(begin == end) throw LinuxException{ LINUX_ENOEXEC }; std::string interpreter(begin, end); // Find the optional argument string that follows the interpreter path for(begin = end; (begin < eof) && (*begin) && (*begin != '\n') && (std::isspace(*begin)); begin++); for(end = begin; (end < eof) && (*end) && (*end != '\n') && (!std::isspace(*end)); end++); std::string argument(begin, end); // todo: recheck the old version, this doesn't look quite right, why am I replacing argv[0] // with the "filename" when it should already be set to that?? (arguments); (environment); throw LinuxException{ LINUX_ENOEXEC }; // [0] - INTERPRETER PATH // [1] - INTERPRETER ARGUMENTS <--- document why this is in this slot if it's right // [2] - PATH_TO_SCRIPT <--- shouldn't original argv[0] already have this? // [3] - ORIGINAL ARGV[1] ... [N] // OLD CODE HERE //// Create a new argument array to pass back in, using the parsed interpreter and argument //std::vector<const char_t*> newarguments; //newarguments.push_back(interpreter.c_str()); //if(argument.length()) newarguments.push_back(argument.c_str()); //newarguments.push_back(filename); //// Append the original argv[1] .. argv[n] pointers to the new argument array //if(arguments && (*arguments)) arguments++; //while((arguments) && (*arguments)) { newarguments.push_back(*arguments); arguments++; } //newarguments.push_back(nullptr); // Call back into FromFile with the interpreter path and modified arguments //return FromFile(ns, std::move(rootdir), std::move(workingdir), originalfilename, interpreter.c_str(), newarguments.data(), environment); } //----------------------------------------------------------------------------- // Executable::getHandle // // Gets a reference to the handle instance opened for the executable std::shared_ptr<FileSystem::Handle> Executable::getHandle(void) const { return m_handle; } //----------------------------------------------------------------------------- // Executable::getOriginalPath // // Gets the originally specified path of the executable const char_t* Executable::getOriginalPath(void) const { return m_originalpath.c_str(); } //----------------------------------------------------------------------------- // Executable::StringArrayToVector (static, private) // // Converts a null-terminated array of C-style strings into a vector<> // // Arguments: // // strings - Null-terminated array of C-style strings Executable::string_vector_t Executable::StringArrayToVector(const char_t* const* strings) { string_vector_t vec; while((strings) && (*strings)) { vec.push_back(*strings); strings++; } return vec; } //----------------------------------------------------------------------------- #pragma warning(pop) <commit_msg>Complete Executable::FromScript, the argument logic from the old version is indeed correct. argv[0] is the target binary, followed optionally by the argument, followed by the original script path, followed by the previous argv[1..n]<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2015 Michael G. Brehm // // 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 "stdafx.h" #include "Executable.h" #include <cctype> #include "LinuxException.h" #pragma warning(push, 4) // INTERPRETER_SCRIPT_MAGIC_ANSI // // Magic number present at the head of an ANSI interpreter script static uint8_t INTERPRETER_SCRIPT_MAGIC_ANSI[] = { 0x23, 0x21 }; // INTERPRETER_SCRIPT_MAGIC_UTF8 // // Magic number present at the head of a UTF-8 interpreter script static uint8_t INTERPRETER_SCRIPT_MAGIC_UTF8[] = { 0xEF, 0xBB, 0xBF, 0x23, 0x21 }; //----------------------------------------------------------------------------- // Executable Constructor (private) // // Arguments: // // arch - Executable architecture flag // format - Executable binary format flag // originalpath - Originally specified executable path // handle - Handle instance open against the target file // arguments - Processed command line arguments // environment - Processed environment variables Executable::Executable(enum class Architecture arch, enum class BinaryFormat format, const char_t* originalpath, std::shared_ptr<FileSystem::Handle> handle, string_vector_t&& arguments, string_vector_t&& environment) : m_architecture(arch), m_format(format), m_originalpath(originalpath), m_handle(std::move(handle)), m_arguments(std::move(arguments)), m_environment(std::move(environment)) { } //----------------------------------------------------------------------------- // Executable::getArchitecture // // Gets the architecture flag for the executable enum class Architecture Executable::getArchitecture(void) const { return m_architecture; } //----------------------------------------------------------------------------- // Executable::getFormat // // Gets the binary format of the executable enum class BinaryFormat Executable::getFormat(void) const { return m_format; } //----------------------------------------------------------------------------- // Executable::FromFile (static) // // Creates an executable instance from a file system file // // Arguments: // // ns - Namespace in which to operate // root - Root directory to assign to the process // current - Working directory to assign to the process // path - Path to the executable image std::unique_ptr<Executable> Executable::FromFile(std::shared_ptr<class Namespace> ns, std::shared_ptr<FileSystem::Path> root, std::shared_ptr<FileSystem::Path> current, const char_t* path) { if(path == nullptr) throw LinuxException{ LINUX_EFAULT }; // Provide empty vectors for the arguments and environment variables return FromFile(std::move(ns), std::move(root), std::move(current), path, path, string_vector_t(), string_vector_t()); } //----------------------------------------------------------------------------- // Executable::FromFile (static) // // Creates an executable instance from a file system file // // Arguments: // // ns - Namespace in which to operate // root - Root directory to assign to the process // current - Working directory to assign to the process // path - Path to the executable image // arguments - Array of command-line arguments // environment - Array of environment variables std::unique_ptr<Executable> Executable::FromFile(std::shared_ptr<class Namespace> ns, std::shared_ptr<FileSystem::Path> root, std::shared_ptr<FileSystem::Path> current, const char_t* path, const char_t* const* arguments, const char_t* const* environment) { if(path == nullptr) throw LinuxException{ LINUX_EFAULT }; // Convert the C-style string arrays into vector<string> containers return FromFile(std::move(ns), std::move(root), std::move(current), path, path, StringArrayToVector(arguments), StringArrayToVector(environment)); } //----------------------------------------------------------------------------- // Executable::FromFile (private, static) // // Creates an executable instance from a file system file // // Arguments: // // ns - Namespace in which to operate // root - Root directory to assign to the process // current - Working directory to assign to the process // originalpath - Original path provided for the executable // path - Path to the executable image // arguments - Vector of command-line arguments // environment - Vector of environment variables std::unique_ptr<Executable> Executable::FromFile(namespace_t ns, fspath_t root, fspath_t current, const char_t* originalpath, const char_t* path, string_vector_t&& arguments, string_vector_t&& environment) { if(originalpath == nullptr) throw LinuxException{ LINUX_EFAULT }; if(path == nullptr) throw LinuxException{ LINUX_EFAULT }; // Acquire an execute-only handle for the provided path auto handle = FileSystem::OpenExecutable(ns, root, current, path); // Read in enough data from the beginning of the file to determine the executable type uint8_t magic[LINUX_EI_NIDENT]; size_t read = handle->ReadAt(0, magic, LINUX_EI_NIDENT); // ELF BINARY // if((read >= LINUX_EI_NIDENT) && (memcmp(magic, LINUX_ELFMAG, LINUX_SELFMAG) == 0)) { // Move the file pointer back to the beginning of the file handle->Seek(0, LINUX_SEEK_SET); // This is a binary file, determine the architecture and complete the operation switch(magic[LINUX_EI_CLASS]) { // ELFCLASS32 --> Architecture::x86 case LINUX_ELFCLASS32: return std::make_unique<Executable>(Architecture::x86, BinaryFormat::ELF, originalpath, std::move(handle), std::move(arguments), std::move(environment)); #ifdef _M_X64 // ELFCLASS64: --> Architecture::x86_64 case LINUX_ELFCLASS64: return std::make_unique<Executable>(Architecture::x86_64, BinaryFormat::ELF, originalpath, std::move(handle), std::move(arguments), std::move(environment)); #endif // Unknown ELFCLASS --> ENOEXEC default: throw LinuxException{ LINUX_ENOEXEC }; } } // A.OUT BINARIES // // TODO - FUTURE (OMAGIC, NMAGIC, QMAGIC, etc) // INTERPRETER SCRIPT (UTF-8) // else if((read >= sizeof(INTERPRETER_SCRIPT_MAGIC_UTF8)) && (memcmp(magic, &INTERPRETER_SCRIPT_MAGIC_UTF8, sizeof(INTERPRETER_SCRIPT_MAGIC_UTF8)) == 0)) { return FromScript(std::move(ns), std::move(root), std::move(current), originalpath, std::move(handle), sizeof(INTERPRETER_SCRIPT_MAGIC_UTF8), std::move(arguments), std::move(environment)); } // INTERPRETER SCRIPT (ANSI) // else if((read >= sizeof(INTERPRETER_SCRIPT_MAGIC_ANSI)) && (memcmp(magic, &INTERPRETER_SCRIPT_MAGIC_ANSI, sizeof(INTERPRETER_SCRIPT_MAGIC_ANSI)) == 0)) { return FromScript(std::move(ns), std::move(root), std::move(current), originalpath, std::move(handle), sizeof(INTERPRETER_SCRIPT_MAGIC_ANSI), std::move(arguments), std::move(environment)); } // UNSUPPORTED FORMAT // else throw LinuxException{ LINUX_ENOEXEC }; } //----------------------------------------------------------------------------- // Executable::FromScript (private, static) // // Creates an executable instance from an interpreter script // // Arguments: // // ns - Namespace in which to operate // root - Root directory to assign to the process // current - Working directory to assign to the process // originalpath - Original path provided for the executable // scripthandle - Handle to the interpreter script // dataoffset - Offset of data within the interpreter script // arguments - Vector of command-line arguments // environment - Vector of environment variables std::unique_ptr<Executable> Executable::FromScript(namespace_t ns, fspath_t root, fspath_t current, const char_t* originalpath, fshandle_t scripthandle, size_t dataoffset, string_vector_t&& arguments, string_vector_t&& environment) { char_t buffer[MAX_PATH]; // Script data buffer string_vector_t newarguments; // New executable arguments if(originalpath == nullptr) throw LinuxException{ LINUX_EFAULT }; char_t *begin, *end; // String tokenizing pointers // Read up to MAX_PATH data from the interpreter script file char_t *eof = &buffer[0] + scripthandle->ReadAt(dataoffset, &buffer[0], sizeof(buffer)); // Find the interperter path, if not present the script is not a valid target for(begin = &buffer[0]; (begin < eof) && (*begin) && (*begin != '\n') && (std::isspace(*begin)); begin++); for(end = begin; (end < eof) && (*end) && (*end != '\n') && (!std::isspace(*end)); end++); if(begin == end) throw LinuxException{ LINUX_ENOEXEC }; std::string interpreter(begin, end); // Find the optional argument string that follows the interpreter path for(begin = end; (begin < eof) && (*begin) && (*begin != '\n') && (std::isspace(*begin)); begin++); for(end = begin; (end < eof) && (*end) && (*end != '\n') && (!std::isspace(*end)); end++); std::string argument(begin, end); // Create a new arguments vector for the target interpreter binary newarguments.push_back(interpreter); if(argument.length()) newarguments.push_back(std::move(argument)); newarguments.emplace_back(originalpath); if(!arguments.empty()) { // Append the original argv[1] .. argv[n] arguments to the new vector (argv[0] is discarded if present) for(auto iterator = arguments.begin() + 1; iterator != arguments.end(); iterator++) newarguments.push_back(*iterator); } // Call back into FromFile with the interpreter binary as the target and new arguments return FromFile(ns, std::move(root), std::move(current), originalpath, interpreter.c_str(), std::move(newarguments), std::move(environment)); } //----------------------------------------------------------------------------- // Executable::getHandle // // Gets a reference to the handle instance opened for the executable std::shared_ptr<FileSystem::Handle> Executable::getHandle(void) const { return m_handle; } //----------------------------------------------------------------------------- // Executable::getOriginalPath // // Gets the originally specified path of the executable const char_t* Executable::getOriginalPath(void) const { return m_originalpath.c_str(); } //----------------------------------------------------------------------------- // Executable::StringArrayToVector (static, private) // // Converts a null-terminated array of C-style strings into a vector<> // // Arguments: // // strings - Null-terminated array of C-style strings Executable::string_vector_t Executable::StringArrayToVector(const char_t* const* strings) { string_vector_t vec; while((strings) && (*strings)) { vec.push_back(*strings); strings++; } return vec; } //----------------------------------------------------------------------------- #pragma warning(pop) <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/llvm/compile_cache.h> #include <vespa/eval/eval/key_gen.h> #include <vespa/eval/eval/test/eval_spec.h> #include <vespa/vespalib/util/time.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <thread> #include <set> using namespace vespalib; using namespace vespalib::eval; //----------------------------------------------------------------------------- TEST("require that parameter passing selection affects function key") { EXPECT_NOT_EQUAL(gen_key(*Function::parse("a+b"), PassParams::SEPARATE), gen_key(*Function::parse("a+b"), PassParams::ARRAY)); } TEST("require that the number of parameters affects function key") { EXPECT_NOT_EQUAL(gen_key(*Function::parse({"a", "b"}, "a+b"), PassParams::SEPARATE), gen_key(*Function::parse({"a", "b", "c"}, "a+b"), PassParams::SEPARATE)); EXPECT_NOT_EQUAL(gen_key(*Function::parse({"a", "b"}, "a+b"), PassParams::ARRAY), gen_key(*Function::parse({"a", "b", "c"}, "a+b"), PassParams::ARRAY)); } TEST("require that implicit and explicit parameters give the same function key") { EXPECT_EQUAL(gen_key(*Function::parse({"a", "b"}, "a+b"), PassParams::SEPARATE), gen_key(*Function::parse("a+b"), PassParams::SEPARATE)); EXPECT_EQUAL(gen_key(*Function::parse({"a", "b"}, "a+b"), PassParams::ARRAY), gen_key(*Function::parse("a+b"), PassParams::ARRAY)); } TEST("require that symbol names does not affect function key") { EXPECT_EQUAL(gen_key(*Function::parse("a+b"), PassParams::SEPARATE), gen_key(*Function::parse("x+y"), PassParams::SEPARATE)); EXPECT_EQUAL(gen_key(*Function::parse("a+b"), PassParams::ARRAY), gen_key(*Function::parse("x+y"), PassParams::ARRAY)); } TEST("require that different values give different function keys") { EXPECT_NOT_EQUAL(gen_key(*Function::parse("1"), PassParams::SEPARATE), gen_key(*Function::parse("2"), PassParams::SEPARATE)); EXPECT_NOT_EQUAL(gen_key(*Function::parse("1"), PassParams::ARRAY), gen_key(*Function::parse("2"), PassParams::ARRAY)); } TEST("require that different strings give different function keys") { EXPECT_NOT_EQUAL(gen_key(*Function::parse("\"a\""), PassParams::SEPARATE), gen_key(*Function::parse("\"b\""), PassParams::SEPARATE)); EXPECT_NOT_EQUAL(gen_key(*Function::parse("\"a\""), PassParams::ARRAY), gen_key(*Function::parse("\"b\""), PassParams::ARRAY)); } //----------------------------------------------------------------------------- struct CheckKeys : test::EvalSpec::EvalTest { bool failed = false; std::set<vespalib::string> seen_keys; bool check_key(const vespalib::string &key) { bool seen = (seen_keys.count(key) > 0); seen_keys.insert(key); return seen; } virtual void next_expression(const std::vector<vespalib::string> &param_names, const vespalib::string &expression) override { auto function = Function::parse(param_names, expression); if (!CompiledFunction::detect_issues(*function)) { if (check_key(gen_key(*function, PassParams::ARRAY)) || check_key(gen_key(*function, PassParams::SEPARATE)) || check_key(gen_key(*function, PassParams::LAZY))) { failed = true; fprintf(stderr, "key collision for: %s\n", expression.c_str()); } } } virtual void handle_case(const std::vector<vespalib::string> &, const std::vector<double> &, const vespalib::string &, double) override {} }; TEST_FF("require that all conformance expressions have different function keys", CheckKeys(), test::EvalSpec()) { f2.add_all_cases(); f2.each_case(f1); EXPECT_TRUE(!f1.failed); EXPECT_GREATER(f1.seen_keys.size(), 100u); } //----------------------------------------------------------------------------- void verify_cache(size_t expect_cached, size_t expect_refs) { EXPECT_EQUAL(expect_cached, CompileCache::num_cached()); EXPECT_EQUAL(expect_refs, CompileCache::count_refs()); } TEST("require that cache is initially empty") { TEST_DO(verify_cache(0, 0)); } TEST("require that unused functions are evicted from the cache") { CompileCache::Token::UP token_a = CompileCache::compile(*Function::parse("x+y"), PassParams::ARRAY); TEST_DO(verify_cache(1, 1)); token_a.reset(); TEST_DO(verify_cache(0, 0)); } TEST("require that agents can have separate functions in the cache") { CompileCache::Token::UP token_a = CompileCache::compile(*Function::parse("x+y"), PassParams::ARRAY); CompileCache::Token::UP token_b = CompileCache::compile(*Function::parse("x*y"), PassParams::ARRAY); TEST_DO(verify_cache(2, 2)); } TEST("require that agents can share functions in the cache") { CompileCache::Token::UP token_a = CompileCache::compile(*Function::parse("x+y"), PassParams::ARRAY); CompileCache::Token::UP token_b = CompileCache::compile(*Function::parse("x+y"), PassParams::ARRAY); TEST_DO(verify_cache(1, 2)); } TEST("require that cache usage works") { TEST_DO(verify_cache(0, 0)); CompileCache::Token::UP token_a = CompileCache::compile(*Function::parse("x+y"), PassParams::SEPARATE); EXPECT_EQUAL(5.0, token_a->get().get_function<2>()(2.0, 3.0)); TEST_DO(verify_cache(1, 1)); CompileCache::Token::UP token_b = CompileCache::compile(*Function::parse("x*y"), PassParams::SEPARATE); EXPECT_EQUAL(6.0, token_b->get().get_function<2>()(2.0, 3.0)); TEST_DO(verify_cache(2, 2)); CompileCache::Token::UP token_c = CompileCache::compile(*Function::parse("x+y"), PassParams::SEPARATE); EXPECT_EQUAL(5.0, token_c->get().get_function<2>()(2.0, 3.0)); TEST_DO(verify_cache(2, 3)); token_a.reset(); TEST_DO(verify_cache(2, 2)); token_b.reset(); TEST_DO(verify_cache(1, 1)); token_c.reset(); TEST_DO(verify_cache(0, 0)); } struct CompileCheck : test::EvalSpec::EvalTest { struct Entry { CompileCache::Token::UP fun; std::vector<double> params; double expect; Entry(CompileCache::Token::UP fun_in, const std::vector<double> &params_in, double expect_in) : fun(std::move(fun_in)), params(params_in), expect(expect_in) {} }; std::vector<Entry> list; void next_expression(const std::vector<vespalib::string> &, const vespalib::string &) override {} void handle_case(const std::vector<vespalib::string> &param_names, const std::vector<double> &param_values, const vespalib::string &expression, double expected_result) override { auto function = Function::parse(param_names, expression); ASSERT_TRUE(!function->has_error()); bool has_issues = CompiledFunction::detect_issues(*function); if (!has_issues) { list.emplace_back(CompileCache::compile(*function, PassParams::ARRAY), param_values, expected_result); } } void verify() { for (const Entry &entry: list) { auto fun = entry.fun->get().get_function(); if (std::isnan(entry.expect)) { EXPECT_TRUE(std::isnan(fun(&entry.params[0]))); } else { EXPECT_EQUAL(fun(&entry.params[0]), entry.expect); } } } }; TEST_F("compile sequentially, then run all conformance tests", test::EvalSpec()) { f1.add_all_cases(); for (size_t i = 0; i < 4; ++i) { CompileCheck test; auto t0 = steady_clock::now(); f1.each_case(test); auto t1 = steady_clock::now(); auto t2 = steady_clock::now(); test.verify(); auto t3 = steady_clock::now(); fprintf(stderr, "sequential (run %zu): setup: %zu ms, wait: %zu ms, verify: %zu us, total: %zu ms\n", i, count_ms(t1 - t0), count_ms(t2 - t1), count_us(t3 - t2), count_ms(t3 - t0)); } } TEST_FF("compile concurrently (8 threads), then run all conformance tests", test::EvalSpec(), TimeBomb(60)) { f1.add_all_cases(); ThreadStackExecutor executor(8, 256*1024); CompileCache::attach_executor(executor); while (executor.num_idle_workers() < 8) { std::this_thread::sleep_for(1ms); } for (size_t i = 0; i < 4; ++i) { CompileCheck test; auto t0 = steady_clock::now(); f1.each_case(test); auto t1 = steady_clock::now(); executor.sync(); auto t2 = steady_clock::now(); test.verify(); auto t3 = steady_clock::now(); fprintf(stderr, "concurrent (run %zu): setup: %zu ms, wait: %zu ms, verify: %zu us, total: %zu ms\n", i, count_ms(t1 - t0), count_ms(t2 - t1), count_us(t3 - t2), count_ms(t3 - t0)); } CompileCache::detach_executor(); } //----------------------------------------------------------------------------- TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>give valgrind more time<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/llvm/compile_cache.h> #include <vespa/eval/eval/key_gen.h> #include <vespa/eval/eval/test/eval_spec.h> #include <vespa/vespalib/util/time.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <thread> #include <set> using namespace vespalib; using namespace vespalib::eval; //----------------------------------------------------------------------------- TEST("require that parameter passing selection affects function key") { EXPECT_NOT_EQUAL(gen_key(*Function::parse("a+b"), PassParams::SEPARATE), gen_key(*Function::parse("a+b"), PassParams::ARRAY)); } TEST("require that the number of parameters affects function key") { EXPECT_NOT_EQUAL(gen_key(*Function::parse({"a", "b"}, "a+b"), PassParams::SEPARATE), gen_key(*Function::parse({"a", "b", "c"}, "a+b"), PassParams::SEPARATE)); EXPECT_NOT_EQUAL(gen_key(*Function::parse({"a", "b"}, "a+b"), PassParams::ARRAY), gen_key(*Function::parse({"a", "b", "c"}, "a+b"), PassParams::ARRAY)); } TEST("require that implicit and explicit parameters give the same function key") { EXPECT_EQUAL(gen_key(*Function::parse({"a", "b"}, "a+b"), PassParams::SEPARATE), gen_key(*Function::parse("a+b"), PassParams::SEPARATE)); EXPECT_EQUAL(gen_key(*Function::parse({"a", "b"}, "a+b"), PassParams::ARRAY), gen_key(*Function::parse("a+b"), PassParams::ARRAY)); } TEST("require that symbol names does not affect function key") { EXPECT_EQUAL(gen_key(*Function::parse("a+b"), PassParams::SEPARATE), gen_key(*Function::parse("x+y"), PassParams::SEPARATE)); EXPECT_EQUAL(gen_key(*Function::parse("a+b"), PassParams::ARRAY), gen_key(*Function::parse("x+y"), PassParams::ARRAY)); } TEST("require that different values give different function keys") { EXPECT_NOT_EQUAL(gen_key(*Function::parse("1"), PassParams::SEPARATE), gen_key(*Function::parse("2"), PassParams::SEPARATE)); EXPECT_NOT_EQUAL(gen_key(*Function::parse("1"), PassParams::ARRAY), gen_key(*Function::parse("2"), PassParams::ARRAY)); } TEST("require that different strings give different function keys") { EXPECT_NOT_EQUAL(gen_key(*Function::parse("\"a\""), PassParams::SEPARATE), gen_key(*Function::parse("\"b\""), PassParams::SEPARATE)); EXPECT_NOT_EQUAL(gen_key(*Function::parse("\"a\""), PassParams::ARRAY), gen_key(*Function::parse("\"b\""), PassParams::ARRAY)); } //----------------------------------------------------------------------------- struct CheckKeys : test::EvalSpec::EvalTest { bool failed = false; std::set<vespalib::string> seen_keys; bool check_key(const vespalib::string &key) { bool seen = (seen_keys.count(key) > 0); seen_keys.insert(key); return seen; } virtual void next_expression(const std::vector<vespalib::string> &param_names, const vespalib::string &expression) override { auto function = Function::parse(param_names, expression); if (!CompiledFunction::detect_issues(*function)) { if (check_key(gen_key(*function, PassParams::ARRAY)) || check_key(gen_key(*function, PassParams::SEPARATE)) || check_key(gen_key(*function, PassParams::LAZY))) { failed = true; fprintf(stderr, "key collision for: %s\n", expression.c_str()); } } } virtual void handle_case(const std::vector<vespalib::string> &, const std::vector<double> &, const vespalib::string &, double) override {} }; TEST_FF("require that all conformance expressions have different function keys", CheckKeys(), test::EvalSpec()) { f2.add_all_cases(); f2.each_case(f1); EXPECT_TRUE(!f1.failed); EXPECT_GREATER(f1.seen_keys.size(), 100u); } //----------------------------------------------------------------------------- void verify_cache(size_t expect_cached, size_t expect_refs) { EXPECT_EQUAL(expect_cached, CompileCache::num_cached()); EXPECT_EQUAL(expect_refs, CompileCache::count_refs()); } TEST("require that cache is initially empty") { TEST_DO(verify_cache(0, 0)); } TEST("require that unused functions are evicted from the cache") { CompileCache::Token::UP token_a = CompileCache::compile(*Function::parse("x+y"), PassParams::ARRAY); TEST_DO(verify_cache(1, 1)); token_a.reset(); TEST_DO(verify_cache(0, 0)); } TEST("require that agents can have separate functions in the cache") { CompileCache::Token::UP token_a = CompileCache::compile(*Function::parse("x+y"), PassParams::ARRAY); CompileCache::Token::UP token_b = CompileCache::compile(*Function::parse("x*y"), PassParams::ARRAY); TEST_DO(verify_cache(2, 2)); } TEST("require that agents can share functions in the cache") { CompileCache::Token::UP token_a = CompileCache::compile(*Function::parse("x+y"), PassParams::ARRAY); CompileCache::Token::UP token_b = CompileCache::compile(*Function::parse("x+y"), PassParams::ARRAY); TEST_DO(verify_cache(1, 2)); } TEST("require that cache usage works") { TEST_DO(verify_cache(0, 0)); CompileCache::Token::UP token_a = CompileCache::compile(*Function::parse("x+y"), PassParams::SEPARATE); EXPECT_EQUAL(5.0, token_a->get().get_function<2>()(2.0, 3.0)); TEST_DO(verify_cache(1, 1)); CompileCache::Token::UP token_b = CompileCache::compile(*Function::parse("x*y"), PassParams::SEPARATE); EXPECT_EQUAL(6.0, token_b->get().get_function<2>()(2.0, 3.0)); TEST_DO(verify_cache(2, 2)); CompileCache::Token::UP token_c = CompileCache::compile(*Function::parse("x+y"), PassParams::SEPARATE); EXPECT_EQUAL(5.0, token_c->get().get_function<2>()(2.0, 3.0)); TEST_DO(verify_cache(2, 3)); token_a.reset(); TEST_DO(verify_cache(2, 2)); token_b.reset(); TEST_DO(verify_cache(1, 1)); token_c.reset(); TEST_DO(verify_cache(0, 0)); } struct CompileCheck : test::EvalSpec::EvalTest { struct Entry { CompileCache::Token::UP fun; std::vector<double> params; double expect; Entry(CompileCache::Token::UP fun_in, const std::vector<double> &params_in, double expect_in) : fun(std::move(fun_in)), params(params_in), expect(expect_in) {} }; std::vector<Entry> list; void next_expression(const std::vector<vespalib::string> &, const vespalib::string &) override {} void handle_case(const std::vector<vespalib::string> &param_names, const std::vector<double> &param_values, const vespalib::string &expression, double expected_result) override { auto function = Function::parse(param_names, expression); ASSERT_TRUE(!function->has_error()); bool has_issues = CompiledFunction::detect_issues(*function); if (!has_issues) { list.emplace_back(CompileCache::compile(*function, PassParams::ARRAY), param_values, expected_result); } } void verify() { for (const Entry &entry: list) { auto fun = entry.fun->get().get_function(); if (std::isnan(entry.expect)) { EXPECT_TRUE(std::isnan(fun(&entry.params[0]))); } else { EXPECT_EQUAL(fun(&entry.params[0]), entry.expect); } } } }; TEST_F("compile sequentially, then run all conformance tests", test::EvalSpec()) { f1.add_all_cases(); for (size_t i = 0; i < 4; ++i) { CompileCheck test; auto t0 = steady_clock::now(); f1.each_case(test); auto t1 = steady_clock::now(); auto t2 = steady_clock::now(); test.verify(); auto t3 = steady_clock::now(); fprintf(stderr, "sequential (run %zu): setup: %zu ms, wait: %zu ms, verify: %zu us, total: %zu ms\n", i, count_ms(t1 - t0), count_ms(t2 - t1), count_us(t3 - t2), count_ms(t3 - t0)); } } TEST_F("compile concurrently (8 threads), then run all conformance tests", test::EvalSpec()) { f1.add_all_cases(); ThreadStackExecutor executor(8, 256*1024); CompileCache::attach_executor(executor); while (executor.num_idle_workers() < 8) { std::this_thread::sleep_for(1ms); } for (size_t i = 0; i < 4; ++i) { CompileCheck test; auto t0 = steady_clock::now(); f1.each_case(test); auto t1 = steady_clock::now(); executor.sync(); auto t2 = steady_clock::now(); test.verify(); auto t3 = steady_clock::now(); fprintf(stderr, "concurrent (run %zu): setup: %zu ms, wait: %zu ms, verify: %zu us, total: %zu ms\n", i, count_ms(t1 - t0), count_ms(t2 - t1), count_us(t3 - t2), count_ms(t3 - t0)); } CompileCache::detach_executor(); } //----------------------------------------------------------------------------- TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>// Copyright (c) 2013-2016 mogemimi. Distributed under the MIT license. #include "SpriteFont.hpp" #include "TrueTypeFont.hpp" #include "SpriteBatchRenderer.hpp" #include "Pomdog/Math/Color.hpp" #include "Pomdog/Math/Matrix4x4.hpp" #include "Pomdog/Math/Vector2.hpp" #include "Pomdog/Math/Vector3.hpp" #include "Pomdog/Math/Radian.hpp" #include "Pomdog/Graphics/Texture2D.hpp" #include "Pomdog/Utility/Assert.hpp" #ifndef _MSC_VER #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif #include <utfcpp/source/utf8.h> #ifndef _MSC_VER #pragma clang diagnostic pop #endif #include <unordered_map> namespace Pomdog { namespace { std::vector<std::uint8_t> ConvertTextureDataByteToByte4(const std::uint8_t* source, size_t size) { std::vector<std::uint8_t> output; output.reserve(size * 4); for (size_t i = 0; i < size; ++i) { output.push_back(255); output.push_back(255); output.push_back(255); output.push_back(source[i]); } return std::move(output); } } // unnamed namespace // MARK: - SpriteFont::Impl class SpriteFont::Impl { public: typedef Detail::SpriteFonts::Glyph Glyph; static constexpr int TextureWidth = 512; static constexpr int TextureHeight = 512; std::unordered_map<char32_t, Glyph> spriteFontMap; char32_t defaultCharacter; float lineSpacing; std::uint16_t spacing; Impl( std::vector<std::shared_ptr<Texture2D>> && textures, const std::vector<Detail::SpriteFonts::Glyph>& glyphs, char32_t defaultCharacter, std::int16_t spacing, std::int16_t lineSpacing); Impl( const std::shared_ptr<GraphicsDevice>& graphicsDevice, const std::shared_ptr<TrueTypeFont>& font, char32_t defaultCharacter, std::int16_t lineSpacing); Vector2 MeasureString(const std::string& text) const; void Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color); void Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color, const Radian<float>& rotation, //const Vector2& originPivot, const Vector2& scale); void PrepareFonts(const std::string& text); private: std::vector<std::shared_ptr<Texture2D>> textures; std::shared_ptr<GraphicsDevice> graphicsDevice; std::shared_ptr<TrueTypeFont> font; std::vector<std::uint8_t> pixelData; Point2D currentPoint; int bottomY; }; constexpr int SpriteFont::Impl::TextureWidth; constexpr int SpriteFont::Impl::TextureHeight; SpriteFont::Impl::Impl( std::vector<std::shared_ptr<Texture2D>> && texturesIn, const std::vector<Detail::SpriteFonts::Glyph>& glyphsIn, char32_t defaultCharacterIn, std::int16_t spacingIn, std::int16_t lineSpacingIn) : textures(std::move(texturesIn)) , defaultCharacter(defaultCharacterIn) , spacing(spacingIn) , lineSpacing(lineSpacingIn) { for (auto & glyph: glyphsIn) { spriteFontMap.emplace(glyph.Character, glyph); } } SpriteFont::Impl::Impl( const std::shared_ptr<GraphicsDevice>& graphicsDeviceIn, const std::shared_ptr<TrueTypeFont>& fontIn, char32_t defaultCharacterIn, std::int16_t lineSpacingIn) : graphicsDevice(graphicsDeviceIn) , font(fontIn) , defaultCharacter(defaultCharacterIn) , spacing(0) , lineSpacing(lineSpacingIn) { POMDOG_ASSERT(font); pixelData.resize(TextureWidth * TextureHeight, 0); currentPoint = {1, 1}; bottomY = 1; auto texture = std::make_shared<Texture2D>(graphicsDevice, TextureWidth, TextureHeight, false, SurfaceFormat::R8G8B8A8_UNorm); textures.push_back(texture); } void SpriteFont::Impl::PrepareFonts(const std::string& text) { POMDOG_ASSERT(!text.empty()); if (!graphicsDevice || !font) { return; } float fontSize = lineSpacing; bool needToFetchPixelData = false; auto fetchTextureData = [&] { if (needToFetchPixelData) { auto texture = textures.back(); texture->SetData(ConvertTextureDataByteToByte4(pixelData.data(), pixelData.size()).data()); needToFetchPixelData = false; } }; auto textIter = std::begin(text); auto textIterEnd = std::end(text); while (textIter != textIterEnd) { const auto character = utf8::next(textIter, textIterEnd); if (spriteFontMap.find(character) != std::end(spriteFontMap)) { continue; } auto glyph = font->RasterizeGlyph(character, fontSize, TextureWidth, [&](int glyphWidth, int glyphHeight, Point2D & pointOut, std::uint8_t* & output) { if (currentPoint.X + glyphWidth + 1 >= TextureWidth) { // advance to next row currentPoint.Y = bottomY; currentPoint.X = 1; } if (currentPoint.Y + glyphHeight + 1 >= TextureHeight) { fetchTextureData(); std::fill(std::begin(pixelData), std::end(pixelData), 0); auto textureNew = std::make_shared<Texture2D>(graphicsDevice, TextureWidth, TextureHeight, false, SurfaceFormat::R8G8B8A8_UNorm); textures.push_back(textureNew); currentPoint = {1, 1}; bottomY = 1; } POMDOG_ASSERT(currentPoint.X + glyphWidth < TextureWidth); POMDOG_ASSERT(currentPoint.Y + glyphHeight < TextureHeight); pointOut = currentPoint; output = pixelData.data(); }); if (!glyph) { continue; } currentPoint.X = currentPoint.X + glyph->Subrect.Width + 1; bottomY = std::max(bottomY, currentPoint.Y + glyph->Subrect.Height + 1); POMDOG_ASSERT(!textures.empty() && textures.size() > 0); glyph->TexturePage = textures.size() - 1; spriteFontMap.emplace(glyph->Character, *glyph); needToFetchPixelData = true; } fetchTextureData(); } Vector2 SpriteFont::Impl::MeasureString(const std::string& text) const { POMDOG_ASSERT(!text.empty()); Vector2 result = Vector2::Zero; Vector2 currentPosition = Vector2::Zero; auto textIter = std::begin(text); auto textIterEnd = std::end(text); while (textIter != textIterEnd) { const auto character = utf8::next(textIter, textIterEnd); if (character == U'\n') { currentPosition.X = 0; currentPosition.Y -= lineSpacing; continue; } auto iter = spriteFontMap.find(character); if (iter == std::end(spriteFontMap)) { iter = spriteFontMap.find(defaultCharacter); POMDOG_ASSERT(iter != std::end(spriteFontMap)); } POMDOG_ASSERT(iter != std::end(spriteFontMap)); auto const & glyph = iter->second; currentPosition.X += (glyph.XAdvance - spacing); result.X = std::max(result.X, currentPosition.X); result.Y = std::max(result.Y, currentPosition.Y); } return std::move(result); } void SpriteFont::Impl::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color) { if (text.empty()) { return; } if (textures.empty()) { return; } Vector2 currentPosition = position; auto textIter = std::begin(text); auto textIterEnd = std::end(text); while (textIter != textIterEnd) { const auto character = utf8::next(textIter, textIterEnd); if (character == U'\n') { currentPosition.X = position.X; currentPosition.Y -= lineSpacing; continue; } auto iter = spriteFontMap.find(character); if (iter == std::end(spriteFontMap)) { iter = spriteFontMap.find(defaultCharacter); if (iter == std::end(spriteFontMap)) { continue; } } POMDOG_ASSERT(iter != std::end(spriteFontMap)); auto const & glyph = iter->second; if (glyph.Subrect.Width > 0 && glyph.Subrect.Height > 0) { POMDOG_ASSERT(glyph.TexturePage >= 0); POMDOG_ASSERT(glyph.TexturePage < static_cast<int>(textures.size())); spriteBatch.Draw(textures[glyph.TexturePage], currentPosition + Vector2(glyph.XOffset, -glyph.YOffset), glyph.Subrect, color, 0.0f, Vector2{0.0f, 1.0f}, Vector2{1.0f, 1.0f}); } currentPosition.X += (glyph.XAdvance - spacing); } } void SpriteFont::Impl::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color, const Radian<float>& rotation, //const Vector2& originPivot, const Vector2& scale) { if (text.empty()) { return; } if (textures.empty()) { return; } Vector2 currentPosition = position; auto textIter = std::begin(text); auto textIterEnd = std::end(text); while (textIter != textIterEnd) { const auto character = utf8::next(textIter, textIterEnd); if (character == U'\n') { currentPosition.X = position.X; currentPosition.Y -= lineSpacing * scale.Y; continue; } auto iter = spriteFontMap.find(character); if (iter == std::end(spriteFontMap)) { iter = spriteFontMap.find(defaultCharacter); if (iter == std::end(spriteFontMap)) { continue; } } POMDOG_ASSERT(iter != std::end(spriteFontMap)); auto const & glyph = iter->second; if (glyph.Subrect.Width > 0 && glyph.Subrect.Height > 0) { POMDOG_ASSERT(glyph.TexturePage >= 0); POMDOG_ASSERT(glyph.TexturePage < static_cast<int>(textures.size())); spriteBatch.Draw(textures[glyph.TexturePage], currentPosition + Vector2(glyph.XOffset, -glyph.YOffset) * scale, glyph.Subrect, color, 0.0f, Vector2{0.0f, 1.0f}, scale); } currentPosition.X += ((glyph.XAdvance - spacing) * scale.X); } } // MARK: - SpriteFont SpriteFont::SpriteFont( std::vector<std::shared_ptr<Texture2D>> && textures, const std::vector<Detail::SpriteFonts::Glyph>& glyphs, char32_t defaultCharacter, std::int16_t spacing, std::int16_t lineSpacing) : impl(std::make_unique<Impl>(std::move(textures), glyphs, defaultCharacter, spacing, lineSpacing)) { } SpriteFont::SpriteFont( const std::shared_ptr<GraphicsDevice>& graphicsDevice, const std::shared_ptr<TrueTypeFont>& font, char32_t defaultCharacter, std::int16_t lineSpacing) : impl(std::make_unique<Impl>(graphicsDevice, font, defaultCharacter, lineSpacing)) { } SpriteFont::~SpriteFont() = default; Vector2 SpriteFont::MeasureString(const std::string& utf8String) const { if (utf8String.empty()) { return Vector2::Zero; } return impl->MeasureString(utf8String); } char32_t SpriteFont::GetDefaultCharacter() const { POMDOG_ASSERT(impl); return impl->defaultCharacter; } void SpriteFont::SetDefaultCharacter(char32_t character) { POMDOG_ASSERT(impl); POMDOG_ASSERT(ContainsCharacter(character)); impl->defaultCharacter = character; } float SpriteFont::GetLineSpacing() const { POMDOG_ASSERT(impl); return impl->lineSpacing; } void SpriteFont::SetLineSpacing(float lineSpacingIn) { POMDOG_ASSERT(impl); impl->lineSpacing = lineSpacingIn; } bool SpriteFont::ContainsCharacter(char32_t character) const { POMDOG_ASSERT(impl); return impl->spriteFontMap.find(character) != std::end(impl->spriteFontMap); } void SpriteFont::Begin( const std::shared_ptr<GraphicsCommandList>& commandList, SpriteBatchRenderer & spriteBatch, const Matrix4x4& transformMatrix) { POMDOG_ASSERT(impl); POMDOG_ASSERT(commandList); spriteBatch.Begin(commandList, transformMatrix); // spriteBatch.Begin(SpriteSortMode::Deferred, Matrix4x4::CreateRotationZ(rotation) // * Matrix4x4::CreateScale({scale, 1.0f}) // * Matrix4x4::CreateTranslation({position, 0.0f}) // * transformMatrix); } void SpriteFont::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color) { if (text.empty()) { return; } impl->PrepareFonts(text); impl->Draw(spriteBatch, text, position, color); } void SpriteFont::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color, const Radian<float>& rotation, //const Vector2& originPivot, float scale) { this->Draw(spriteBatch, text, position, color, rotation, Vector2{scale, scale}); } void SpriteFont::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color, const Radian<float>& rotation, //const Vector2& originPivot, const Vector2& scale) { if (text.empty()) { return; } impl->PrepareFonts(text); impl->Draw(spriteBatch, text, position, color, rotation, scale); } void SpriteFont::End(SpriteBatchRenderer & spriteBatch) { spriteBatch.End(); } } // namespace Pomdog <commit_msg>Change font texture width to 1024<commit_after>// Copyright (c) 2013-2016 mogemimi. Distributed under the MIT license. #include "SpriteFont.hpp" #include "TrueTypeFont.hpp" #include "SpriteBatchRenderer.hpp" #include "Pomdog/Math/Color.hpp" #include "Pomdog/Math/Matrix4x4.hpp" #include "Pomdog/Math/Vector2.hpp" #include "Pomdog/Math/Vector3.hpp" #include "Pomdog/Math/Radian.hpp" #include "Pomdog/Graphics/Texture2D.hpp" #include "Pomdog/Utility/Assert.hpp" #ifndef _MSC_VER #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif #include <utfcpp/source/utf8.h> #ifndef _MSC_VER #pragma clang diagnostic pop #endif #include <unordered_map> namespace Pomdog { namespace { std::vector<std::uint8_t> ConvertTextureDataByteToByte4(const std::uint8_t* source, size_t size) { std::vector<std::uint8_t> output; output.reserve(size * 4); for (size_t i = 0; i < size; ++i) { output.push_back(255); output.push_back(255); output.push_back(255); output.push_back(source[i]); } return std::move(output); } } // unnamed namespace // MARK: - SpriteFont::Impl class SpriteFont::Impl { public: typedef Detail::SpriteFonts::Glyph Glyph; static constexpr int TextureWidth = 1024; static constexpr int TextureHeight = 1024; std::unordered_map<char32_t, Glyph> spriteFontMap; char32_t defaultCharacter; float lineSpacing; std::uint16_t spacing; Impl( std::vector<std::shared_ptr<Texture2D>> && textures, const std::vector<Detail::SpriteFonts::Glyph>& glyphs, char32_t defaultCharacter, std::int16_t spacing, std::int16_t lineSpacing); Impl( const std::shared_ptr<GraphicsDevice>& graphicsDevice, const std::shared_ptr<TrueTypeFont>& font, char32_t defaultCharacter, std::int16_t lineSpacing); Vector2 MeasureString(const std::string& text) const; void Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color); void Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color, const Radian<float>& rotation, //const Vector2& originPivot, const Vector2& scale); void PrepareFonts(const std::string& text); private: std::vector<std::shared_ptr<Texture2D>> textures; std::shared_ptr<GraphicsDevice> graphicsDevice; std::shared_ptr<TrueTypeFont> font; std::vector<std::uint8_t> pixelData; Point2D currentPoint; int bottomY; }; constexpr int SpriteFont::Impl::TextureWidth; constexpr int SpriteFont::Impl::TextureHeight; SpriteFont::Impl::Impl( std::vector<std::shared_ptr<Texture2D>> && texturesIn, const std::vector<Detail::SpriteFonts::Glyph>& glyphsIn, char32_t defaultCharacterIn, std::int16_t spacingIn, std::int16_t lineSpacingIn) : textures(std::move(texturesIn)) , defaultCharacter(defaultCharacterIn) , spacing(spacingIn) , lineSpacing(lineSpacingIn) { for (auto & glyph: glyphsIn) { spriteFontMap.emplace(glyph.Character, glyph); } } SpriteFont::Impl::Impl( const std::shared_ptr<GraphicsDevice>& graphicsDeviceIn, const std::shared_ptr<TrueTypeFont>& fontIn, char32_t defaultCharacterIn, std::int16_t lineSpacingIn) : graphicsDevice(graphicsDeviceIn) , font(fontIn) , defaultCharacter(defaultCharacterIn) , spacing(0) , lineSpacing(lineSpacingIn) { POMDOG_ASSERT(font); pixelData.resize(TextureWidth * TextureHeight, 0); currentPoint = {1, 1}; bottomY = 1; auto texture = std::make_shared<Texture2D>(graphicsDevice, TextureWidth, TextureHeight, false, SurfaceFormat::R8G8B8A8_UNorm); textures.push_back(texture); } void SpriteFont::Impl::PrepareFonts(const std::string& text) { POMDOG_ASSERT(!text.empty()); if (!graphicsDevice || !font) { return; } float fontSize = lineSpacing; bool needToFetchPixelData = false; auto fetchTextureData = [&] { if (needToFetchPixelData) { auto texture = textures.back(); texture->SetData(ConvertTextureDataByteToByte4(pixelData.data(), pixelData.size()).data()); needToFetchPixelData = false; } }; auto textIter = std::begin(text); auto textIterEnd = std::end(text); while (textIter != textIterEnd) { const auto character = utf8::next(textIter, textIterEnd); if (spriteFontMap.find(character) != std::end(spriteFontMap)) { continue; } auto glyph = font->RasterizeGlyph(character, fontSize, TextureWidth, [&](int glyphWidth, int glyphHeight, Point2D & pointOut, std::uint8_t* & output) { if (currentPoint.X + glyphWidth + 1 >= TextureWidth) { // advance to next row currentPoint.Y = bottomY; currentPoint.X = 1; } if (currentPoint.Y + glyphHeight + 1 >= TextureHeight) { fetchTextureData(); std::fill(std::begin(pixelData), std::end(pixelData), 0); auto textureNew = std::make_shared<Texture2D>(graphicsDevice, TextureWidth, TextureHeight, false, SurfaceFormat::R8G8B8A8_UNorm); textures.push_back(textureNew); currentPoint = {1, 1}; bottomY = 1; } POMDOG_ASSERT(currentPoint.X + glyphWidth < TextureWidth); POMDOG_ASSERT(currentPoint.Y + glyphHeight < TextureHeight); pointOut = currentPoint; output = pixelData.data(); }); if (!glyph) { continue; } currentPoint.X = currentPoint.X + glyph->Subrect.Width + 1; bottomY = std::max(bottomY, currentPoint.Y + glyph->Subrect.Height + 1); POMDOG_ASSERT(!textures.empty() && textures.size() > 0); glyph->TexturePage = textures.size() - 1; spriteFontMap.emplace(glyph->Character, *glyph); needToFetchPixelData = true; } fetchTextureData(); } Vector2 SpriteFont::Impl::MeasureString(const std::string& text) const { POMDOG_ASSERT(!text.empty()); Vector2 result = Vector2::Zero; Vector2 currentPosition = Vector2::Zero; auto textIter = std::begin(text); auto textIterEnd = std::end(text); while (textIter != textIterEnd) { const auto character = utf8::next(textIter, textIterEnd); if (character == U'\n') { currentPosition.X = 0; currentPosition.Y -= lineSpacing; continue; } auto iter = spriteFontMap.find(character); if (iter == std::end(spriteFontMap)) { iter = spriteFontMap.find(defaultCharacter); POMDOG_ASSERT(iter != std::end(spriteFontMap)); } POMDOG_ASSERT(iter != std::end(spriteFontMap)); auto const & glyph = iter->second; currentPosition.X += (glyph.XAdvance - spacing); result.X = std::max(result.X, currentPosition.X); result.Y = std::max(result.Y, currentPosition.Y); } return std::move(result); } void SpriteFont::Impl::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color) { if (text.empty()) { return; } if (textures.empty()) { return; } Vector2 currentPosition = position; auto textIter = std::begin(text); auto textIterEnd = std::end(text); while (textIter != textIterEnd) { const auto character = utf8::next(textIter, textIterEnd); if (character == U'\n') { currentPosition.X = position.X; currentPosition.Y -= lineSpacing; continue; } auto iter = spriteFontMap.find(character); if (iter == std::end(spriteFontMap)) { iter = spriteFontMap.find(defaultCharacter); if (iter == std::end(spriteFontMap)) { continue; } } POMDOG_ASSERT(iter != std::end(spriteFontMap)); auto const & glyph = iter->second; if (glyph.Subrect.Width > 0 && glyph.Subrect.Height > 0) { POMDOG_ASSERT(glyph.TexturePage >= 0); POMDOG_ASSERT(glyph.TexturePage < static_cast<int>(textures.size())); spriteBatch.Draw(textures[glyph.TexturePage], currentPosition + Vector2(glyph.XOffset, -glyph.YOffset), glyph.Subrect, color, 0.0f, Vector2{0.0f, 1.0f}, Vector2{1.0f, 1.0f}); } currentPosition.X += (glyph.XAdvance - spacing); } } void SpriteFont::Impl::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color, const Radian<float>& rotation, //const Vector2& originPivot, const Vector2& scale) { if (text.empty()) { return; } if (textures.empty()) { return; } Vector2 currentPosition = position; auto textIter = std::begin(text); auto textIterEnd = std::end(text); while (textIter != textIterEnd) { const auto character = utf8::next(textIter, textIterEnd); if (character == U'\n') { currentPosition.X = position.X; currentPosition.Y -= lineSpacing * scale.Y; continue; } auto iter = spriteFontMap.find(character); if (iter == std::end(spriteFontMap)) { iter = spriteFontMap.find(defaultCharacter); if (iter == std::end(spriteFontMap)) { continue; } } POMDOG_ASSERT(iter != std::end(spriteFontMap)); auto const & glyph = iter->second; if (glyph.Subrect.Width > 0 && glyph.Subrect.Height > 0) { POMDOG_ASSERT(glyph.TexturePage >= 0); POMDOG_ASSERT(glyph.TexturePage < static_cast<int>(textures.size())); spriteBatch.Draw(textures[glyph.TexturePage], currentPosition + Vector2(glyph.XOffset, -glyph.YOffset) * scale, glyph.Subrect, color, 0.0f, Vector2{0.0f, 1.0f}, scale); } currentPosition.X += ((glyph.XAdvance - spacing) * scale.X); } } // MARK: - SpriteFont SpriteFont::SpriteFont( std::vector<std::shared_ptr<Texture2D>> && textures, const std::vector<Detail::SpriteFonts::Glyph>& glyphs, char32_t defaultCharacter, std::int16_t spacing, std::int16_t lineSpacing) : impl(std::make_unique<Impl>(std::move(textures), glyphs, defaultCharacter, spacing, lineSpacing)) { } SpriteFont::SpriteFont( const std::shared_ptr<GraphicsDevice>& graphicsDevice, const std::shared_ptr<TrueTypeFont>& font, char32_t defaultCharacter, std::int16_t lineSpacing) : impl(std::make_unique<Impl>(graphicsDevice, font, defaultCharacter, lineSpacing)) { } SpriteFont::~SpriteFont() = default; Vector2 SpriteFont::MeasureString(const std::string& utf8String) const { if (utf8String.empty()) { return Vector2::Zero; } return impl->MeasureString(utf8String); } char32_t SpriteFont::GetDefaultCharacter() const { POMDOG_ASSERT(impl); return impl->defaultCharacter; } void SpriteFont::SetDefaultCharacter(char32_t character) { POMDOG_ASSERT(impl); POMDOG_ASSERT(ContainsCharacter(character)); impl->defaultCharacter = character; } float SpriteFont::GetLineSpacing() const { POMDOG_ASSERT(impl); return impl->lineSpacing; } void SpriteFont::SetLineSpacing(float lineSpacingIn) { POMDOG_ASSERT(impl); impl->lineSpacing = lineSpacingIn; } bool SpriteFont::ContainsCharacter(char32_t character) const { POMDOG_ASSERT(impl); return impl->spriteFontMap.find(character) != std::end(impl->spriteFontMap); } void SpriteFont::Begin( const std::shared_ptr<GraphicsCommandList>& commandList, SpriteBatchRenderer & spriteBatch, const Matrix4x4& transformMatrix) { POMDOG_ASSERT(impl); POMDOG_ASSERT(commandList); spriteBatch.Begin(commandList, transformMatrix); // spriteBatch.Begin(SpriteSortMode::Deferred, Matrix4x4::CreateRotationZ(rotation) // * Matrix4x4::CreateScale({scale, 1.0f}) // * Matrix4x4::CreateTranslation({position, 0.0f}) // * transformMatrix); } void SpriteFont::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color) { if (text.empty()) { return; } impl->PrepareFonts(text); impl->Draw(spriteBatch, text, position, color); } void SpriteFont::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color, const Radian<float>& rotation, //const Vector2& originPivot, float scale) { this->Draw(spriteBatch, text, position, color, rotation, Vector2{scale, scale}); } void SpriteFont::Draw( SpriteBatchRenderer & spriteBatch, const std::string& text, const Vector2& position, const Color& color, const Radian<float>& rotation, //const Vector2& originPivot, const Vector2& scale) { if (text.empty()) { return; } impl->PrepareFonts(text); impl->Draw(spriteBatch, text, position, color, rotation, scale); } void SpriteFont::End(SpriteBatchRenderer & spriteBatch) { spriteBatch.End(); } } // namespace Pomdog <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_eve /// Demonstrates usage of TEveBoxSet class. /// /// \image html eve_boxset.png /// \macro_code /// /// \author Matevz Tadel TEveBoxSet* boxset(Float_t x=0, Float_t y=0, Float_t z=0, Int_t num=100, Bool_t registerSet=kTRUE) { TEveManager::Create(); TRandom r(0); TEveRGBAPalette* pal = new TEveRGBAPalette(0, 130); TEveFrameBox* frm = new TEveFrameBox(); frm->SetAABoxCenterHalfSize(0, 0, 0, 12, 12, 12); frm->SetFrameColor(kCyan); frm->SetBackColorRGBA(120,120,120,20); frm->SetDrawBack(kTRUE); TEveBoxSet* q = new TEveBoxSet("BoxSet"); q->SetPalette(pal); q->SetFrame(frm); q->Reset(TEveBoxSet::kBT_AABox, kFALSE, 64); for (Int_t i=0; i<num; ++i) { q->AddBox(r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(0.2, 1), r.Uniform(0.2, 1), r.Uniform(0.2, 1)); q->DigitValue(r.Uniform(0, 130)); } q->RefitPlex(); TEveTrans& t = q->RefMainTrans(); t.SetPos(x, y, z); // Uncomment these two lines to get internal highlight / selection. // q->SetPickable(1); // q->SetAlwaysSecSelect(1); if (registerSet) { gEve->AddElement(q); gEve->Redraw3D(kTRUE); } return q; } TEveBoxSet* boxset_colisval(Float_t x=0, Float_t y=0, Float_t z=0, Int_t num=100, Bool_t registerSet=kTRUE) { TEveManager::Create(); TRandom r(0); TEveBoxSet* q = new TEveBoxSet("BoxSet"); q->Reset(TEveBoxSet::kBT_AABox, kTRUE, 64); for (Int_t i=0; i<num; ++i) { q->AddBox(r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(0.2, 1), r.Uniform(0.2, 1), r.Uniform(0.2, 1)); q->DigitColor(r.Uniform(20, 255), r.Uniform(20, 255), r.Uniform(20, 255), r.Uniform(20, 255)); } q->RefitPlex(); TEveTrans& t = q->RefMainTrans(); t.SetPos(x, y, z); if (registerSet) { gEve->AddElement(q); gEve->Redraw3D(kTRUE); } return q; } TEveBoxSet* boxset_single_color(Float_t x=0, Float_t y=0, Float_t z=0, Int_t num=100, Bool_t registerSet=kTRUE) { TEveManager::Create(); TRandom r(0); TEveBoxSet* q = new TEveBoxSet("BoxSet"); q->UseSingleColor(); q->SetMainColor(kCyan-2); q->SetMainTransparency(50); q->Reset(TEveBoxSet::kBT_AABox, kFALSE, 64); for (Int_t i=0; i<num; ++i) { q->AddBox(r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(0.2, 1), r.Uniform(0.2, 1), r.Uniform(0.2, 1)); } q->RefitPlex(); TEveTrans& t = q->RefMainTrans(); t.SetPos(x, y, z); if (registerSet) { gEve->AddElement(q); gEve->Redraw3D(kTRUE); } return q; } TEveBoxSet* boxset_freebox(Int_t num=100, Bool_t registerSet=kTRUE) { TEveManager::Create(); TRandom r(0); TEveRGBAPalette* pal = new TEveRGBAPalette(0, 130); TEveBoxSet* q = new TEveBoxSet("BoxSet"); q->SetPalette(pal); q->Reset(TEveBoxSet::kBT_FreeBox, kFALSE, 64); #define RND_BOX(x) (Float_t)r.Uniform(-(x), (x)) Float_t verts[24]; for (Int_t i=0; i<num; ++i) { Float_t x = RND_BOX(10); Float_t y = RND_BOX(10); Float_t z = RND_BOX(10); Float_t a = r.Uniform(0.2, 0.5); Float_t d = 0.05; Float_t verts[24] = { x - a + RND_BOX(d), y - a + RND_BOX(d), z - a + RND_BOX(d), x - a + RND_BOX(d), y + a + RND_BOX(d), z - a + RND_BOX(d), x + a + RND_BOX(d), y + a + RND_BOX(d), z - a + RND_BOX(d), x + a + RND_BOX(d), y - a + RND_BOX(d), z - a + RND_BOX(d), x - a + RND_BOX(d), y - a + RND_BOX(d), z + a + RND_BOX(d), x - a + RND_BOX(d), y + a + RND_BOX(d), z + a + RND_BOX(d), x + a + RND_BOX(d), y + a + RND_BOX(d), z + a + RND_BOX(d), x + a + RND_BOX(d), y - a + RND_BOX(d), z + a + RND_BOX(d) }; q->AddBox(verts); q->DigitValue(r.Uniform(0, 130)); } q->RefitPlex(); #undef RND_BOX // Uncomment these two lines to get internal highlight / selection. // q->SetPickable(1); // q->SetAlwaysSecSelect(1); if (registerSet) { gEve->AddElement(q); gEve->Redraw3D(kTRUE); } return q; } <commit_msg>- use auto<commit_after>/// \file /// \ingroup tutorial_eve /// Demonstrates usage of TEveBoxSet class. /// /// \image html eve_boxset.png /// \macro_code /// /// \author Matevz Tadel TEveBoxSet* boxset(Float_t x=0, Float_t y=0, Float_t z=0, Int_t num=100, Bool_t registerSet=kTRUE) { TEveManager::Create(); TRandom r(0); auto pal = new TEveRGBAPalette(0, 130); auto frm = new TEveFrameBox(); frm->SetAABoxCenterHalfSize(0, 0, 0, 12, 12, 12); frm->SetFrameColor(kCyan); frm->SetBackColorRGBA(120,120,120,20); frm->SetDrawBack(kTRUE); auto q = new TEveBoxSet("BoxSet"); q->SetPalette(pal); q->SetFrame(frm); q->Reset(TEveBoxSet::kBT_AABox, kFALSE, 64); for (Int_t i=0; i<num; ++i) { q->AddBox(r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(0.2, 1), r.Uniform(0.2, 1), r.Uniform(0.2, 1)); q->DigitValue(r.Uniform(0, 130)); } q->RefitPlex(); TEveTrans& t = q->RefMainTrans(); t.SetPos(x, y, z); // Uncomment these two lines to get internal highlight / selection. // q->SetPickable(1); // q->SetAlwaysSecSelect(1); if (registerSet) { gEve->AddElement(q); gEve->Redraw3D(kTRUE); } return q; } TEveBoxSet* boxset_colisval(Float_t x=0, Float_t y=0, Float_t z=0, Int_t num=100, Bool_t registerSet=kTRUE) { TEveManager::Create(); TRandom r(0); auto q = new TEveBoxSet("BoxSet"); q->Reset(TEveBoxSet::kBT_AABox, kTRUE, 64); for (Int_t i=0; i<num; ++i) { q->AddBox(r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(0.2, 1), r.Uniform(0.2, 1), r.Uniform(0.2, 1)); q->DigitColor(r.Uniform(20, 255), r.Uniform(20, 255), r.Uniform(20, 255), r.Uniform(20, 255)); } q->RefitPlex(); TEveTrans& t = q->RefMainTrans(); t.SetPos(x, y, z); if (registerSet) { gEve->AddElement(q); gEve->Redraw3D(kTRUE); } return q; } TEveBoxSet* boxset_single_color(Float_t x=0, Float_t y=0, Float_t z=0, Int_t num=100, Bool_t registerSet=kTRUE) { TEveManager::Create(); TRandom r(0); auto q = new TEveBoxSet("BoxSet"); q->UseSingleColor(); q->SetMainColor(kCyan-2); q->SetMainTransparency(50); q->Reset(TEveBoxSet::kBT_AABox, kFALSE, 64); for (Int_t i=0; i<num; ++i) { q->AddBox(r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(0.2, 1), r.Uniform(0.2, 1), r.Uniform(0.2, 1)); } q->RefitPlex(); TEveTrans& t = q->RefMainTrans(); t.SetPos(x, y, z); if (registerSet) { gEve->AddElement(q); gEve->Redraw3D(kTRUE); } return q; } TEveBoxSet* boxset_freebox(Int_t num=100, Bool_t registerSet=kTRUE) { TEveManager::Create(); TRandom r(0); auto pal = new TEveRGBAPalette(0, 130); auto q = new TEveBoxSet("BoxSet"); q->SetPalette(pal); q->Reset(TEveBoxSet::kBT_FreeBox, kFALSE, 64); #define RND_BOX(x) (Float_t)r.Uniform(-(x), (x)) Float_t verts[24]; for (Int_t i=0; i<num; ++i) { Float_t x = RND_BOX(10); Float_t y = RND_BOX(10); Float_t z = RND_BOX(10); Float_t a = r.Uniform(0.2, 0.5); Float_t d = 0.05; Float_t verts[24] = { x - a + RND_BOX(d), y - a + RND_BOX(d), z - a + RND_BOX(d), x - a + RND_BOX(d), y + a + RND_BOX(d), z - a + RND_BOX(d), x + a + RND_BOX(d), y + a + RND_BOX(d), z - a + RND_BOX(d), x + a + RND_BOX(d), y - a + RND_BOX(d), z - a + RND_BOX(d), x - a + RND_BOX(d), y - a + RND_BOX(d), z + a + RND_BOX(d), x - a + RND_BOX(d), y + a + RND_BOX(d), z + a + RND_BOX(d), x + a + RND_BOX(d), y + a + RND_BOX(d), z + a + RND_BOX(d), x + a + RND_BOX(d), y - a + RND_BOX(d), z + a + RND_BOX(d) }; q->AddBox(verts); q->DigitValue(r.Uniform(0, 130)); } q->RefitPlex(); #undef RND_BOX // Uncomment these two lines to get internal highlight / selection. // q->SetPickable(1); // q->SetAlwaysSecSelect(1); if (registerSet) { gEve->AddElement(q); gEve->Redraw3D(kTRUE); } return q; } <|endoftext|>
<commit_before>void loopdir() { // example of script to loop on all the objects of a ROOT file directory // and print on Postscript all TH1 derived objects // This script uses the file generated by tutorial hsimple.C //Author: Rene Brun TString dir = gSystem->UnixPathName(__FILE__); dir.ReplaceAll("loopdir.C","../hsimple.C"); dir.ReplaceAll("/./","/"); if (!gInterpreter->IsLoaded(dir.Data())) gInterpreter->LoadMacro(dir.Data()); TFile *f1 = (TFile*)gROOT->ProcessLineFast("hsimple(1)"); TIter next(f1->GetListOfKeys()); TKey *key; TCanvas c1; c1.Print("hsimple.ps["); while ((key = (TKey*)next())) { TClass *cl = gROOT->GetClass(key->GetClassName()); if (!cl->InheritsFrom("TH1")) continue; TH1 *h = (TH1*)key->ReadObj(); h->Draw(); c1.Print("hsimple.ps"); } c1.Print("hsimple.ps]"); } <commit_msg>Do not trigger the creation of hsimple.root, which may create clashes when running in parallel.<commit_after>void loopdir() { // example of script to loop on all the objects of a ROOT file directory // and print on Postscript all TH1 derived objects // This script uses the file generated by tutorial hsimple.C //Author: Rene Brun TFile *f1 = TFile::Open("hsimple.root"); TIter next(f1->GetListOfKeys()); TKey *key; TCanvas c1; c1.Print("hsimple.ps["); while ((key = (TKey*)next())) { TClass *cl = gROOT->GetClass(key->GetClassName()); if (!cl->InheritsFrom("TH1")) continue; TH1 *h = (TH1*)key->ReadObj(); h->Draw(); c1.Print("hsimple.ps"); } c1.Print("hsimple.ps]"); } <|endoftext|>
<commit_before>/** * 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. */ /* * XSEC * * DSIG_Reference := Class for checking and setting up reference nodes in a DSIG signature * * $Id$ * */ // High level include #include <xsec/framework/XSECDefs.hpp> // Xerces INcludes #include <xercesc/dom/DOM.hpp> #include <xercesc/dom/DOMNamedNodeMap.hpp> // XSEC Includes #include <xsec/utils/XSECSafeBufferFormatter.hpp> #include <xsec/dsig/DSIGTransform.hpp> #include <xsec/dsig/DSIGReferenceList.hpp> #include <xsec/dsig/DSIGConstants.hpp> class DSIGTransformList; class DSIGTransformBase64; class DSIGTransformC14n; class DSIGTransformEnvelope; class DSIGTransformXPath; class DSIGTransformXPathFilter; class DSIGTransformXSL; class DSIGSignature; class DSIGSignedInfo; class TXFMBase; class TXFMChain; class XSECBinTXFMInputStream; class XSECURIResolver; class XSECEnv; /** * @ingroup pubsig */ /** * @brief The class used for manipulating Reference Elements within a signature. * * <p>The DSIGReference class creates and manipulates (including hashing and validating) * \<Reference\> elements.</p> * */ class XSEC_EXPORT DSIGReference { public: /** @name Constructors and Destructors */ //@{ /** * \brief Contructor for use with existing XML signatures or templates. * * <p>Create a DSIGReference object based on an already existing * DSIG Reference XML node. It is assumed that the underlying * DOM structure is in place and works correctly.</p> * * @note DSIGReference structures should only ever be created via calls to a * DSIGSignature object. * * @param env The operating environment in which the Reference is operating * @param dom The DOM node (within doc) that is to be used as the base of the reference. * @see #load * @see DSIGSignature#createReference */ DSIGReference(const XSECEnv * env, XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *dom); /** * \brief Contructor for use when creating new Reference structures. * * <p>Create a DSIGReference object that can later be used to create * a new Reference structure in the DOM document.</p> * * @note DSIGReference structures should only ever be created via calls to a * DSIGSignature object. * * @param env The environment object for this reference. * @see #load * @see DSIGSignature#createReference */ DSIGReference(const XSECEnv * env); /** * \brief Destructor. * * @note Does not impact any created DOM structures when destroyed. * * @note DSIGReferences should <em>never</em> be destroyed/deleted by * applications. They are owned and managed by DSIGSignature structures. */ ~DSIGReference(); //@} /** @name Reference Construction and Manipulation */ //@{ /** * \brief Load a DSIGReference from an existing DOM structure. * * <p>This function will load a Reference structure from the owner * document.</p> * */ void load(); /** * \brief Create a Reference structure in the document. * * <p>This function will create a Reference structure in the owner * document. In some cases, a call to this function will be sufficient * to put the required Reference in place. In other cases, calls will * also need to be made to the various append*Transform methods.</p> * * @note The XSEC Library currently makes very little use of <em>type</em> * attributes in \<Reference\> Elements. However this may of use to calling * applications. * * @param URI The URI (data source) for this reference. Set to NULL for * an anonymous reference. * @param hashAlgorithmURI The type of Digest to be used (generally SHA-1) * @param type A type string (as defined by XML Signature). * @returns The root Reference element of the newly created DOM structure. */ XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * createBlankReference(const XMLCh * URI, const XMLCh * hashAlgorithmURI, const XMLCh * type); /** * \brief Append an Enveloped Signature Transform to the Reference. * * Appends a simple enveloped-signature transform to the list of transforms * in this element. * * @returns The newly created envelope transform. * */ DSIGTransformEnvelope * appendEnvelopedSignatureTransform(); /** * \brief Append a Base64 Transform to the Reference. * * @returns The newly created Base64 transform. */ DSIGTransformBase64 * appendBase64Transform(); /** * \brief Append an XPath Transform to the Reference. * * <p> Append an XPath transform. Namespaces can be added to the * transform directly using the returned <em>DSIGTransformXPath</em> * structure</p> * * @param expr The XPath expression to be placed in the transform. * @returns The newly created XPath transform */ DSIGTransformXPath * appendXPathTransform(const char * expr); /** * \brief Append an XPath-Filter2 Transform to the Reference. * * The returned DSIGTransformXPathFilter will have no actual filter * expressions loaded, but calls can be made to * DSIGTransformXPathFilter::appendTransform to add them. * * @returns The newly created XPath Filter transform */ DSIGTransformXPathFilter * appendXPathFilterTransform(void); /** * \brief Append an XSLT Transform to the Reference. * * <p>The caller must have already create the stylesheet and turned it into * a DOM structure that is passed in as the stylesheet parameter.</p> * * @param stylesheet The stylesheet DOM structure to be placed in the reference. * @returns The newly create XSLT transform */ DSIGTransformXSL * appendXSLTransform(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *stylesheet); /** * \brief Append a Canonicalization Transform to the Reference. * * @param canonicalizationAlgorithmURI The type of canonicalisation to be added. * @returns The newly create canonicalisation transform */ DSIGTransformC14n * appendCanonicalizationTransform( const XMLCh * canonicalizationAlgorithmURI ); /** * \brief Append a "debug" transformer. * * This method allows applications to provide a TXFM that will be appended * to the transform chain just prior to the application of the hash * algorithm. * * @note This is primarily for debugging. It should not be used to modify the * contents of the byte stream. * * @param t The TXFM element to insert. */ void setPreHashTXFM(TXFMBase * t); /** * \brief Set the Id attribute of the DSIGReference * * This method allows applications to set the Id attribute of the DSIGReference * as described in http://www.w3.org/TR/xmldsig-core/#sec-Reference. * * * @param id The value for this reference. */ void setId(const XMLCh *id); /** * \brief Set the Type attribute of the DSIGReference * * This method allows applications to set the Type attribute of the DSIGReference * as described in http://www.w3.org/TR/xmldsig-core/#sec-Reference. * * * @param type The value for this reference. */ void setType(const XMLCh *type); //@} /** @name Getting Information */ //@{ /** * \brief Create an input stream based on the digested byte stream. * * This method allows applications to read the fully canonicalised * byte stream that is hashed for a reference. * * All transforms are performed up to the point where they would * normally be fed into the Digest function. * * @returns A BinInputSource of the canonicalised SignedInfo */ XSECBinTXFMInputStream * makeBinInputStream(void) const; /** * \brief Return the URI string of the Reference. * * @returns A pointer to the buffer (owned by the Reference) containing * the value of the URI stored inthe reference */ const XMLCh * getURI() const; /** * \brief Get the Digest Algorithm URI * * @returns the URI associated with the Algorithm used to generate * the digest */ const XMLCh * getAlgorithmURI() const { return mp_algorithmURI; } /** * \brief Obtain the transforms for this reference * * Get the DSIGTransformList object for this reference. Can be used to * obtain information about the transforms and also change the the transforms */ DSIGTransformList * getTransforms(void) const { return mp_transformList; } /** * \brief Determine whether the reference is a manifest * * @returns true iff the Reference element is a Manifest reference */ bool isManifest() const; /** * \brief Get the Manifest * * @returns The ReferenceList containing the references in the Manifest * list of this reference element. */ DSIGReferenceList * getManifestReferenceList() const; // Return list of references for a manifest object //@} /** @name Message Digest/Hash manipulation */ //@{ /** * \brief Calculate the Hash value of a reference * * Takes the Reference URI, performs all the transforms and finally * calculates the Hash value of the data using the Digest algorithm * indicated in the reference * * @param toFill A Buffer that the raw hash will be copied into. * @param maxToFill Maximum number of bytes to place in the buffer * @returns The number of bytes copied into the buffer */ unsigned int calculateHash(XMLByte * toFill, unsigned int maxToFill) const; /** * \brief Read the hash from the Reference element. * * Reads the Base64 encoded element from the Reference element. * The hash is then translated from Base64 back into raw form and * written into the indicated buffer. * * @param toFill Pointer to the buffer where the raw hash will be written * @param maxToFill Maximum bytes to write to the buffer * @returns Number of bytes written */ unsigned int readHash(XMLByte *toFill, unsigned int maxToFill) const; /** * \brief Validate the Reference element * * Performs a #calculateHash() and a #readHash() and then compares the * results. * * @returns true iff the hash of the data matches the hash stored * in the reference. */ bool checkHash() const; /** * \brief Set the value of the hash in the Reference * * Hashes the data referenced by the element and then writes * the Base64 encoded hash value into the Reference. * */ void setHash(); //@} /** @name Helper (static) Functions */ //@{ /** * \brief Create a Transformer chain * * Given a TransformList create the corresponding TXFM chain to allow * the caller to read the reference byte stream * * @note This method is primarily for use within the XSEC library. * Users wishing to get the byte stream should use the #makeBinInputStream * method instead. * * @param input The input transformer to which the TXFMs will be applied to * This is generally created from the URI attribute of the reference. * @param lst The list of Transform elements from which to build the * transformer list. * @returns The <B>end</B> of the newly build TXFM chain. This can be * read from using TXFMBase::readBytes() to give the end result of the * transforms. */ static TXFMChain * createTXFMChainFromList(TXFMBase * input, DSIGTransformList * lst); /** * \brief Load a Transforms list from the \<Transforms\> DOMNode. * * Reads the data from the XML data stored in the DOM and create * the associated DSIGTrasnformList. * * @param transformsNode Starting node in the DOM * @param formatter The formatter to be used to move from XMLCh to strings * @param env Environment in which to operate * @returns A pointer to the created list. */ static DSIGTransformList * loadTransforms( XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *transformsNode, XSECSafeBufferFormatter * formatter, const XSECEnv * env); /** * \brief Create a starting point for a TXFM Chain. * * Uses the provided URI to find the base data that the Transformer chain * will be built upon. * * @param doc The document that the signature is based on (used for local URIs) * @param URI The URI to build the base from * @param env The environment the signature is operating in * @returns A base TXFM element. */ static TXFMBase * getURIBaseTXFM(XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument * doc, const XMLCh * URI, const XSECEnv * env); /** * \brief Load a series of references. * * Takes a series of \<Reference\> elements in a DOM structure * and creates the corresponding ReferenceList object. * * @note Internal function - meant for use by the library * * @param env The environment in which this reference resides * @param firstReference First reference in DOM structure * @returns the created list. */ static DSIGReferenceList *loadReferenceListFromXML(const XSECEnv * env, XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *firstReference); /** * \brief Validate a list of references. * * Runs through a reference list, calling verify() on each and * setting the ErrroStrings for any errors found * * @param lst The list to verify * @param errorStr The string to append any errors found to * @returns true iff all the references validate successfully. */ static bool verifyReferenceList(const DSIGReferenceList * lst, safeBuffer &errorStr); /** * \brief Hash a reference list * * Run through a list of references and calculate the hash value of each * element. Finally set the Base64 encoded string according to the newly * calcuated hash. * * @note This is an internal library function and should not be called directly. * * @param list The list of references * @param interlocking If set to false, the library will assume there * are no inter-related references. The algorithm for determining this * internally is very primitive and CPU intensive, so this is a method to * bypass the checks. */ static void hashReferenceList(const DSIGReferenceList * list, bool interlocking = true); //@} private: // Internal functions void createTransformList(void); void addTransform( DSIGTransform * txfm, XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * txfmElt ); XSECSafeBufferFormatter * mp_formatter; XERCES_CPP_NAMESPACE_QUALIFIER DOMNode * mp_referenceNode; // Points to start of document where reference node is mutable TXFMBase * mp_preHash; // To be used pre-hash DSIGReferenceList * mp_manifestList; // The list of references in a manifest const XMLCh * mp_URI; // The URI String bool m_isManifest; // Does this reference a manifest? XERCES_CPP_NAMESPACE_QUALIFIER DOMNode * mp_transformsNode; XERCES_CPP_NAMESPACE_QUALIFIER DOMNode * mp_hashValueNode; // Node where the Hash value is stored const XSECEnv * mp_env; DSIGTransformList * mp_transformList; // List of transforms const XMLCh * mp_algorithmURI; // Hash algorithm for this reference bool m_loaded; DSIGReference(); /*\@}*/ friend class DSIGSignedInfo; }; <commit_msg>SANTUARIO-568 - DSIGReference is missing a header guard<commit_after>/** * 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. */ /* * XSEC * * DSIG_Reference := Class for checking and setting up reference nodes in a DSIG signature * * $Id$ * */ #ifndef DSIGREFERENCE_INCLUDE #define DSIGREFERENCE_INCLUDE // High level include #include <xsec/framework/XSECDefs.hpp> // Xerces INcludes #include <xercesc/dom/DOM.hpp> #include <xercesc/dom/DOMNamedNodeMap.hpp> // XSEC Includes #include <xsec/utils/XSECSafeBufferFormatter.hpp> #include <xsec/dsig/DSIGTransform.hpp> #include <xsec/dsig/DSIGReferenceList.hpp> #include <xsec/dsig/DSIGConstants.hpp> class DSIGTransformList; class DSIGTransformBase64; class DSIGTransformC14n; class DSIGTransformEnvelope; class DSIGTransformXPath; class DSIGTransformXPathFilter; class DSIGTransformXSL; class DSIGSignature; class DSIGSignedInfo; class TXFMBase; class TXFMChain; class XSECBinTXFMInputStream; class XSECURIResolver; class XSECEnv; /** * @ingroup pubsig */ /** * @brief The class used for manipulating Reference Elements within a signature. * * <p>The DSIGReference class creates and manipulates (including hashing and validating) * \<Reference\> elements.</p> * */ class XSEC_EXPORT DSIGReference { public: /** @name Constructors and Destructors */ //@{ /** * \brief Contructor for use with existing XML signatures or templates. * * <p>Create a DSIGReference object based on an already existing * DSIG Reference XML node. It is assumed that the underlying * DOM structure is in place and works correctly.</p> * * @note DSIGReference structures should only ever be created via calls to a * DSIGSignature object. * * @param env The operating environment in which the Reference is operating * @param dom The DOM node (within doc) that is to be used as the base of the reference. * @see #load * @see DSIGSignature#createReference */ DSIGReference(const XSECEnv * env, XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *dom); /** * \brief Contructor for use when creating new Reference structures. * * <p>Create a DSIGReference object that can later be used to create * a new Reference structure in the DOM document.</p> * * @note DSIGReference structures should only ever be created via calls to a * DSIGSignature object. * * @param env The environment object for this reference. * @see #load * @see DSIGSignature#createReference */ DSIGReference(const XSECEnv * env); /** * \brief Destructor. * * @note Does not impact any created DOM structures when destroyed. * * @note DSIGReferences should <em>never</em> be destroyed/deleted by * applications. They are owned and managed by DSIGSignature structures. */ ~DSIGReference(); //@} /** @name Reference Construction and Manipulation */ //@{ /** * \brief Load a DSIGReference from an existing DOM structure. * * <p>This function will load a Reference structure from the owner * document.</p> * */ void load(); /** * \brief Create a Reference structure in the document. * * <p>This function will create a Reference structure in the owner * document. In some cases, a call to this function will be sufficient * to put the required Reference in place. In other cases, calls will * also need to be made to the various append*Transform methods.</p> * * @note The XSEC Library currently makes very little use of <em>type</em> * attributes in \<Reference\> Elements. However this may of use to calling * applications. * * @param URI The URI (data source) for this reference. Set to NULL for * an anonymous reference. * @param hashAlgorithmURI The type of Digest to be used (generally SHA-1) * @param type A type string (as defined by XML Signature). * @returns The root Reference element of the newly created DOM structure. */ XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * createBlankReference(const XMLCh * URI, const XMLCh * hashAlgorithmURI, const XMLCh * type); /** * \brief Append an Enveloped Signature Transform to the Reference. * * Appends a simple enveloped-signature transform to the list of transforms * in this element. * * @returns The newly created envelope transform. * */ DSIGTransformEnvelope * appendEnvelopedSignatureTransform(); /** * \brief Append a Base64 Transform to the Reference. * * @returns The newly created Base64 transform. */ DSIGTransformBase64 * appendBase64Transform(); /** * \brief Append an XPath Transform to the Reference. * * <p> Append an XPath transform. Namespaces can be added to the * transform directly using the returned <em>DSIGTransformXPath</em> * structure</p> * * @param expr The XPath expression to be placed in the transform. * @returns The newly created XPath transform */ DSIGTransformXPath * appendXPathTransform(const char * expr); /** * \brief Append an XPath-Filter2 Transform to the Reference. * * The returned DSIGTransformXPathFilter will have no actual filter * expressions loaded, but calls can be made to * DSIGTransformXPathFilter::appendTransform to add them. * * @returns The newly created XPath Filter transform */ DSIGTransformXPathFilter * appendXPathFilterTransform(void); /** * \brief Append an XSLT Transform to the Reference. * * <p>The caller must have already create the stylesheet and turned it into * a DOM structure that is passed in as the stylesheet parameter.</p> * * @param stylesheet The stylesheet DOM structure to be placed in the reference. * @returns The newly create XSLT transform */ DSIGTransformXSL * appendXSLTransform(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *stylesheet); /** * \brief Append a Canonicalization Transform to the Reference. * * @param canonicalizationAlgorithmURI The type of canonicalisation to be added. * @returns The newly create canonicalisation transform */ DSIGTransformC14n * appendCanonicalizationTransform( const XMLCh * canonicalizationAlgorithmURI ); /** * \brief Append a "debug" transformer. * * This method allows applications to provide a TXFM that will be appended * to the transform chain just prior to the application of the hash * algorithm. * * @note This is primarily for debugging. It should not be used to modify the * contents of the byte stream. * * @param t The TXFM element to insert. */ void setPreHashTXFM(TXFMBase * t); /** * \brief Set the Id attribute of the DSIGReference * * This method allows applications to set the Id attribute of the DSIGReference * as described in http://www.w3.org/TR/xmldsig-core/#sec-Reference. * * * @param id The value for this reference. */ void setId(const XMLCh *id); /** * \brief Set the Type attribute of the DSIGReference * * This method allows applications to set the Type attribute of the DSIGReference * as described in http://www.w3.org/TR/xmldsig-core/#sec-Reference. * * * @param type The value for this reference. */ void setType(const XMLCh *type); //@} /** @name Getting Information */ //@{ /** * \brief Create an input stream based on the digested byte stream. * * This method allows applications to read the fully canonicalised * byte stream that is hashed for a reference. * * All transforms are performed up to the point where they would * normally be fed into the Digest function. * * @returns A BinInputSource of the canonicalised SignedInfo */ XSECBinTXFMInputStream * makeBinInputStream(void) const; /** * \brief Return the URI string of the Reference. * * @returns A pointer to the buffer (owned by the Reference) containing * the value of the URI stored inthe reference */ const XMLCh * getURI() const; /** * \brief Get the Digest Algorithm URI * * @returns the URI associated with the Algorithm used to generate * the digest */ const XMLCh * getAlgorithmURI() const { return mp_algorithmURI; } /** * \brief Obtain the transforms for this reference * * Get the DSIGTransformList object for this reference. Can be used to * obtain information about the transforms and also change the the transforms */ DSIGTransformList * getTransforms(void) const { return mp_transformList; } /** * \brief Determine whether the reference is a manifest * * @returns true iff the Reference element is a Manifest reference */ bool isManifest() const; /** * \brief Get the Manifest * * @returns The ReferenceList containing the references in the Manifest * list of this reference element. */ DSIGReferenceList * getManifestReferenceList() const; // Return list of references for a manifest object //@} /** @name Message Digest/Hash manipulation */ //@{ /** * \brief Calculate the Hash value of a reference * * Takes the Reference URI, performs all the transforms and finally * calculates the Hash value of the data using the Digest algorithm * indicated in the reference * * @param toFill A Buffer that the raw hash will be copied into. * @param maxToFill Maximum number of bytes to place in the buffer * @returns The number of bytes copied into the buffer */ unsigned int calculateHash(XMLByte * toFill, unsigned int maxToFill) const; /** * \brief Read the hash from the Reference element. * * Reads the Base64 encoded element from the Reference element. * The hash is then translated from Base64 back into raw form and * written into the indicated buffer. * * @param toFill Pointer to the buffer where the raw hash will be written * @param maxToFill Maximum bytes to write to the buffer * @returns Number of bytes written */ unsigned int readHash(XMLByte *toFill, unsigned int maxToFill) const; /** * \brief Validate the Reference element * * Performs a #calculateHash() and a #readHash() and then compares the * results. * * @returns true iff the hash of the data matches the hash stored * in the reference. */ bool checkHash() const; /** * \brief Set the value of the hash in the Reference * * Hashes the data referenced by the element and then writes * the Base64 encoded hash value into the Reference. * */ void setHash(); //@} /** @name Helper (static) Functions */ //@{ /** * \brief Create a Transformer chain * * Given a TransformList create the corresponding TXFM chain to allow * the caller to read the reference byte stream * * @note This method is primarily for use within the XSEC library. * Users wishing to get the byte stream should use the #makeBinInputStream * method instead. * * @param input The input transformer to which the TXFMs will be applied to * This is generally created from the URI attribute of the reference. * @param lst The list of Transform elements from which to build the * transformer list. * @returns The <B>end</B> of the newly build TXFM chain. This can be * read from using TXFMBase::readBytes() to give the end result of the * transforms. */ static TXFMChain * createTXFMChainFromList(TXFMBase * input, DSIGTransformList * lst); /** * \brief Load a Transforms list from the \<Transforms\> DOMNode. * * Reads the data from the XML data stored in the DOM and create * the associated DSIGTrasnformList. * * @param transformsNode Starting node in the DOM * @param formatter The formatter to be used to move from XMLCh to strings * @param env Environment in which to operate * @returns A pointer to the created list. */ static DSIGTransformList * loadTransforms( XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *transformsNode, XSECSafeBufferFormatter * formatter, const XSECEnv * env); /** * \brief Create a starting point for a TXFM Chain. * * Uses the provided URI to find the base data that the Transformer chain * will be built upon. * * @param doc The document that the signature is based on (used for local URIs) * @param URI The URI to build the base from * @param env The environment the signature is operating in * @returns A base TXFM element. */ static TXFMBase * getURIBaseTXFM(XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument * doc, const XMLCh * URI, const XSECEnv * env); /** * \brief Load a series of references. * * Takes a series of \<Reference\> elements in a DOM structure * and creates the corresponding ReferenceList object. * * @note Internal function - meant for use by the library * * @param env The environment in which this reference resides * @param firstReference First reference in DOM structure * @returns the created list. */ static DSIGReferenceList *loadReferenceListFromXML(const XSECEnv * env, XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *firstReference); /** * \brief Validate a list of references. * * Runs through a reference list, calling verify() on each and * setting the ErrroStrings for any errors found * * @param lst The list to verify * @param errorStr The string to append any errors found to * @returns true iff all the references validate successfully. */ static bool verifyReferenceList(const DSIGReferenceList * lst, safeBuffer &errorStr); /** * \brief Hash a reference list * * Run through a list of references and calculate the hash value of each * element. Finally set the Base64 encoded string according to the newly * calcuated hash. * * @note This is an internal library function and should not be called directly. * * @param list The list of references * @param interlocking If set to false, the library will assume there * are no inter-related references. The algorithm for determining this * internally is very primitive and CPU intensive, so this is a method to * bypass the checks. */ static void hashReferenceList(const DSIGReferenceList * list, bool interlocking = true); //@} private: // Internal functions void createTransformList(void); void addTransform( DSIGTransform * txfm, XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * txfmElt ); XSECSafeBufferFormatter * mp_formatter; XERCES_CPP_NAMESPACE_QUALIFIER DOMNode * mp_referenceNode; // Points to start of document where reference node is mutable TXFMBase * mp_preHash; // To be used pre-hash DSIGReferenceList * mp_manifestList; // The list of references in a manifest const XMLCh * mp_URI; // The URI String bool m_isManifest; // Does this reference a manifest? XERCES_CPP_NAMESPACE_QUALIFIER DOMNode * mp_transformsNode; XERCES_CPP_NAMESPACE_QUALIFIER DOMNode * mp_hashValueNode; // Node where the Hash value is stored const XSECEnv * mp_env; DSIGTransformList * mp_transformList; // List of transforms const XMLCh * mp_algorithmURI; // Hash algorithm for this reference bool m_loaded; DSIGReference(); /*\@}*/ friend class DSIGSignedInfo; }; #endif /* #define DSIGREFERENCE_INCLUDE */ <|endoftext|>
<commit_before>/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/test/unit_test.hpp> #include "TestFunctions.hpp" #include "CoreConstants.hpp" #include "CoreGlobals.hpp" #include "Exception.hpp" #include "Model.hpp" #include "Changer.hpp" #include "Interpreter.hpp" typedef void (CheckerFunc) ( Implementation::Unit prev, Implementation::Unit curr, bool spec ); static void eatChecker( Implementation::Unit prev, Implementation::Unit curr, bool spec ) { if (spec) { int max_mass = prev.mass + RANDOM_MAX_ACTIONS * EAT_MASS; BOOST_REQUIRE(curr.mass >= prev.mass && curr.mass < max_mass); } else { BOOST_REQUIRE(curr.mass == (prev.mass + EAT_MASS)); } } static Implementation::Changer createChanger( ModelPtr model, bool spec, bool many_commands ) { int instructions; if (spec && many_commands) { // func; func r; func n instructions = 3; } else if (spec) { // func; func r instructions = 2; } else if (many_commands) { // func; func n instructions = 2; } else { // func instructions = 1; } return Implementation::Changer(model, 0, 0, instructions); } static void checkSpec( ModelPtr model, Implementation::Changer& changer, Implementation::ChangerMethod tested, CheckerFunc checker ) { Implementation::Unit prev = getFirstUnit(model); Abstract::Params params(-1, -1, true); changer.clearBeforeMove(); (changer.*tested)(&params, 0); Implementation::Unit curr = getFirstUnit(model); checker(prev, curr, true); } static void checkManyCommands( ModelPtr model, Implementation::Changer& changer, Implementation::ChangerMethod tested, CheckerFunc checker ) { int commands = 5; Abstract::Params params(commands, -1, false); for (int i = 0; i < commands; i++) { Implementation::Unit prev = getFirstUnit(model); changer.clearBeforeMove(); (changer.*tested)(&params, 0); Implementation::Unit curr = getFirstUnit(model); checker(prev, curr, false); } // range error params = Abstract::Params(10000, -1, false); changer.clearBeforeMove(); BOOST_REQUIRE_THROW((changer.*tested)(&params, 0), Exception); } static void checkLogicalMethod( Implementation::ChangerMethod tested, CheckerFunc checker, bool spec, bool many_commands ) { ModelPtr model(createBaseModel(1, 1)); Implementation::Changer changer = createChanger(model, spec, many_commands); Implementation::Unit prev = getFirstUnit(model); Abstract::Params params(-1, -1, false); (changer.*tested)(&params, 0); Implementation::Unit curr = getFirstUnit(model); checker(prev, curr, false); if (many_commands) { checkManyCommands(model, changer, tested, checker); } if (spec) { checkSpec(model, changer, tested, checker); } } BOOST_AUTO_TEST_CASE (get_bacteria_number_test) { ModelPtr model(createBaseModel(1, 1)); Implementation::Changer changer(model, 0, 0, 0); BOOST_REQUIRE(changer.getBacteriaNumber() == 1); } BOOST_AUTO_TEST_CASE (get_team_test) { ModelPtr model(createBaseModel(1, 1)); Implementation::Changer changer(model, 0, 0, 0); BOOST_REQUIRE(changer.getTeam() == 0); } BOOST_AUTO_TEST_CASE (changer_get_instruction_test) { ModelPtr model(createBaseModel(1, 1)); // total number of instructions is 2 Implementation::Changer changer(model, 0, 0, 2); // initial state BOOST_REQUIRE(changer.getInstruction(0) == 0); Abstract::Params params(-1, -1, false); changer.eat(&params, 0); // after execution of the first command BOOST_REQUIRE(changer.getInstruction(0) == 1); int commands = 5; params = Abstract::Params(commands, -1, false); for (int i = 0; i < commands; i++) { // it must execute the same command `commands` times BOOST_REQUIRE(changer.getInstruction(0) == 1); changer.clearBeforeMove(); changer.eat(&params, 0); } // cycle: after execution of all commands it returns to initial state BOOST_REQUIRE(changer.getInstruction(0) == 0); } BOOST_AUTO_TEST_CASE (eat_test) { ModelPtr model(createBaseModel(1, 1)); // number of instructions is 3: eat; eat 5; eat r Implementation::Changer changer(model, 0, 0, 3); Abstract::Params params(-1, -1, false); // eat changer.eat(&params, 0); BOOST_REQUIRE(model->getMass(0, 0) == DEFAULT_MASS + EAT_MASS); int commands = 5; params = Abstract::Params(commands, -1, false); for (int i = 0; i < commands; i++) { int expected_mass = EAT_MASS * (i + 1) + DEFAULT_MASS; BOOST_REQUIRE(model->getMass(0, 0) == expected_mass); changer.clearBeforeMove(); // eat 5 changer.eat(&params, 0); } int prev_mass = model->getMass(0, 0); params = Abstract::Params(-1, -1, true); changer.clearBeforeMove(); // eat r changer.eat(&params, 0); int curr_mass = model->getMass(0, 0); int max_mass = prev_mass + RANDOM_MAX_ACTIONS * EAT_MASS; BOOST_REQUIRE(curr_mass >= prev_mass && curr_mass < max_mass); // range error params = Abstract::Params(10000, -1, false); BOOST_REQUIRE_THROW(changer.eat(&params, 0), Exception); } <commit_msg>Unit tests (changer): use checkLogicalMethod() in eat_test<commit_after>/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/test/unit_test.hpp> #include "TestFunctions.hpp" #include "CoreConstants.hpp" #include "CoreGlobals.hpp" #include "Exception.hpp" #include "Model.hpp" #include "Changer.hpp" #include "Interpreter.hpp" typedef void (CheckerFunc) ( Implementation::Unit prev, Implementation::Unit curr, bool spec ); static void eatChecker( Implementation::Unit prev, Implementation::Unit curr, bool spec ) { if (spec) { int max_mass = prev.mass + RANDOM_MAX_ACTIONS * EAT_MASS; BOOST_REQUIRE(curr.mass >= prev.mass && curr.mass < max_mass); } else { BOOST_REQUIRE(curr.mass == (prev.mass + EAT_MASS)); } } static Implementation::Changer createChanger( ModelPtr model, bool spec, bool many_commands ) { int instructions; if (spec && many_commands) { // func; func r; func n instructions = 3; } else if (spec) { // func; func r instructions = 2; } else if (many_commands) { // func; func n instructions = 2; } else { // func instructions = 1; } return Implementation::Changer(model, 0, 0, instructions); } static void checkSpec( ModelPtr model, Implementation::Changer& changer, Implementation::ChangerMethod tested, CheckerFunc checker ) { Implementation::Unit prev = getFirstUnit(model); Abstract::Params params(-1, -1, true); changer.clearBeforeMove(); (changer.*tested)(&params, 0); Implementation::Unit curr = getFirstUnit(model); checker(prev, curr, true); } static void checkManyCommands( ModelPtr model, Implementation::Changer& changer, Implementation::ChangerMethod tested, CheckerFunc checker ) { int commands = 5; Abstract::Params params(commands, -1, false); for (int i = 0; i < commands; i++) { Implementation::Unit prev = getFirstUnit(model); changer.clearBeforeMove(); (changer.*tested)(&params, 0); Implementation::Unit curr = getFirstUnit(model); checker(prev, curr, false); } // range error params = Abstract::Params(10000, -1, false); changer.clearBeforeMove(); BOOST_REQUIRE_THROW((changer.*tested)(&params, 0), Exception); } static void checkLogicalMethod( Implementation::ChangerMethod tested, CheckerFunc checker, bool spec, bool many_commands ) { ModelPtr model(createBaseModel(1, 1)); Implementation::Changer changer = createChanger(model, spec, many_commands); Implementation::Unit prev = getFirstUnit(model); Abstract::Params params(-1, -1, false); (changer.*tested)(&params, 0); Implementation::Unit curr = getFirstUnit(model); checker(prev, curr, false); if (many_commands) { checkManyCommands(model, changer, tested, checker); } if (spec) { checkSpec(model, changer, tested, checker); } } BOOST_AUTO_TEST_CASE (get_bacteria_number_test) { ModelPtr model(createBaseModel(1, 1)); Implementation::Changer changer(model, 0, 0, 0); BOOST_REQUIRE(changer.getBacteriaNumber() == 1); } BOOST_AUTO_TEST_CASE (get_team_test) { ModelPtr model(createBaseModel(1, 1)); Implementation::Changer changer(model, 0, 0, 0); BOOST_REQUIRE(changer.getTeam() == 0); } BOOST_AUTO_TEST_CASE (changer_get_instruction_test) { ModelPtr model(createBaseModel(1, 1)); // total number of instructions is 2 Implementation::Changer changer(model, 0, 0, 2); // initial state BOOST_REQUIRE(changer.getInstruction(0) == 0); Abstract::Params params(-1, -1, false); changer.eat(&params, 0); // after execution of the first command BOOST_REQUIRE(changer.getInstruction(0) == 1); int commands = 5; params = Abstract::Params(commands, -1, false); for (int i = 0; i < commands; i++) { // it must execute the same command `commands` times BOOST_REQUIRE(changer.getInstruction(0) == 1); changer.clearBeforeMove(); changer.eat(&params, 0); } // cycle: after execution of all commands it returns to initial state BOOST_REQUIRE(changer.getInstruction(0) == 0); } BOOST_AUTO_TEST_CASE (eat_test) { checkLogicalMethod( &Abstract::Changer::eat, eatChecker, true, true ); } <|endoftext|>
<commit_before>/** * @version GrPPI v0.2 * @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved. * @license GNU/GPL, see LICENSE.txt * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You have received a copy of the GNU General Public License in LICENSE.txt * also available in <http://www.gnu.org/licenses/gpl.html>. * * See COPYRIGHT.txt for copyright notices and details. */ #include <atomic> #include <experimental/optional> #include <numeric> #include <gtest/gtest.h> #include "grppi.h" #include "dyn/dynamic_execution.h" #include "supported_executions.h" using namespace std; using namespace grppi; template <typename T> using optional = std::experimental::optional<T>; template <typename T> class context_test : public ::testing::Test { public: T execution_; dynamic_execution dyn_execution_{execution_}; sequential_execution seq_; parallel_execution_native thr_; #ifdef GRPPI_OMP parallel_execution_omp omp_; #endif parallel_execution_tbb tbb_; // Variables int out; int counter; // Vectors vector<int> v{}; vector<vector<int> > v2{}; // Invocation counter std::atomic<int> invocations_init{0}; std::atomic<int> invocations_last{0}; std::atomic<int> invocations_intermediate{0}; std::atomic<int> invocations_intermediate2{0}; void setup_three_stages() { counter = 5; out = 0; } template <typename E> void run_three_stages_farm_with_sequential(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->seq_, grppi::farm(2, [this](int x) { invocations_intermediate++; return x*2; } ) ), [this](int x) { invocations_last++; out += x; }); } template <typename E> void run_three_stages_farm_with_native(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->thr_, grppi::farm(2, [this](int x) { invocations_intermediate++; return x*2; } ) ), [this](int x) { invocations_last++; out += x; }); } template <typename E> void run_three_stages_farm_with_omp(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, #ifdef GRPPI_OMP grppi::run_with(this->omp_, grppi::farm(2, [this](int x) { invocations_intermediate++; return x*2; } ) ), #endif [this](int x) { invocations_last++; out += x; }); } template <typename E> void run_three_stages_farm_with_tbb(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->tbb_, grppi::farm(2, [this](int x) { invocations_intermediate++; return x*2; } ) ), [this](int x) { invocations_last++; out += x; }); } void check_three_stages() { EXPECT_EQ(6, invocations_init); EXPECT_EQ(5, invocations_last); EXPECT_EQ(5, invocations_intermediate); EXPECT_EQ(0, invocations_intermediate2); EXPECT_EQ(30, out); } void setup_composed() { counter = 5; out = 0; } template <typename E> void run_composed_pipeline_with_sequential(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->seq_, grppi::pipeline( [this](int x) { std::cerr << "squaring " << x << std::endl; invocations_intermediate++; std::cerr << "Incrementing\n"; return x*x; }, [this](int x) { invocations_intermediate2++; x *= 2; return x; } ) ), [this](int x) { invocations_last++; out +=x; }); } template <typename E> void run_composed_pipeline_with_native(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->thr_, grppi::pipeline( [this](int x) { std::cerr << "squaring " << x << std::endl; invocations_intermediate++; std::cerr << "Incrementing\n"; return x*x; }, [this](int x) { invocations_intermediate2++; x *= 2; return x; } ) ), [this](int x) { invocations_last++; out +=x; }); } template <typename E> void run_composed_pipeline_with_omp(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, #ifdef GRPPI_OMP grppi::run_with(this->omp_, grppi::pipeline( [this](int x) { std::cerr << "squaring " << x << std::endl; invocations_intermediate++; std::cerr << "Incrementing\n"; return x*x; }, [this](int x) { invocations_intermediate2++; x *= 2; return x; } ) ), #endif [this](int x) { invocations_last++; out +=x; }); } template <typename E> void run_composed_pipeline_with_tbb(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->tbb_, grppi::pipeline( [this](int x) { std::cerr << "squaring " << x << std::endl; invocations_intermediate++; std::cerr << "Incrementing\n"; return x*x; }, [this](int x) { invocations_intermediate2++; x *= 2; return x; } ) ), [this](int x) { invocations_last++; out +=x; }); } void check_composed() { EXPECT_EQ(6, invocations_init); EXPECT_EQ(5, invocations_last); EXPECT_EQ(5, invocations_intermediate); EXPECT_EQ(5, invocations_intermediate2); EXPECT_EQ(110, out); } }; // Test for execution policies defined in supported_executions.h TYPED_TEST_CASE(context_test, executions_noff); TYPED_TEST(context_test, static_three_stages_farm_seq) { this->setup_three_stages(); this->run_three_stages_farm_with_sequential(this->execution_); this->check_three_stages(); } TYPED_TEST(context_test, static_three_stages_farm_nat) { this->setup_three_stages(); this->run_three_stages_farm_with_native(this->execution_); this->check_three_stages(); } #ifdef GRPPI_OMP TYPED_TEST(context_test, static_three_stages_farm_omp) { this->setup_three_stages(); this->run_three_stages_farm_with_omp(this->execution_); this->check_three_stages(); } #endif TYPED_TEST(context_test, static_three_stages_farm_tbb) { this->setup_three_stages(); this->run_three_stages_farm_with_tbb(this->execution_); this->check_three_stages(); } TYPED_TEST(context_test, dyn_three_stages_farm_seq) { this->setup_three_stages(); this->run_three_stages_farm_with_sequential(this->dyn_execution_); this->check_three_stages(); } TYPED_TEST(context_test, dyn_three_stages_farm_nat) { this->setup_three_stages(); this->run_three_stages_farm_with_native(this->dyn_execution_); this->check_three_stages(); } #ifdef GRPPI_OMP TYPED_TEST(context_test, dyn_three_stages_farm_omp) { this->setup_three_stages(); this->run_three_stages_farm_with_omp(this->dyn_execution_); this->check_three_stages(); } #endif TYPED_TEST(context_test, dyn_three_stages_farm_tbb) { this->setup_three_stages(); this->run_three_stages_farm_with_tbb(this->dyn_execution_); this->check_three_stages(); } TYPED_TEST(context_test, static_composed_pipeline_seq) { this->setup_composed(); this->run_composed_pipeline_with_sequential(this->execution_); this->check_composed(); } TYPED_TEST(context_test, static_composed_pipeline_nat) { this->setup_composed(); this->run_composed_pipeline_with_native(this->execution_); this->check_composed(); } #ifdef GRPPI_OMP TYPED_TEST(context_test, static_composed_pipeline_omp) { this->setup_composed(); this->run_composed_pipeline_with_omp(this->execution_); this->check_composed(); } #endif TYPED_TEST(context_test, static_composed_pipeline_tbb) { this->setup_composed(); this->run_composed_pipeline_with_tbb(this->execution_); this->check_composed(); } TYPED_TEST(context_test, dyn_composed_pipeline_seq) { this->setup_composed(); this->run_composed_pipeline_with_sequential(this->dyn_execution_); this->check_composed(); } TYPED_TEST(context_test, dyn_composed_pipeline_nat) { this->setup_composed(); this->run_composed_pipeline_with_native(this->dyn_execution_); this->check_composed(); } #ifdef GRPPI_OMP TYPED_TEST(context_test, dyn_composed_pipeline_omp) { this->setup_composed(); this->run_composed_pipeline_with_omp(this->dyn_execution_); this->check_composed(); } #endif TYPED_TEST(context_test, dyn_composed_pipeline_tbb) { this->setup_composed(); this->run_composed_pipeline_with_tbb(this->dyn_execution_); this->check_composed(); } <commit_msg>Conditionally support testing of TBB<commit_after>/** * @version GrPPI v0.2 * @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved. * @license GNU/GPL, see LICENSE.txt * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You have received a copy of the GNU General Public License in LICENSE.txt * also available in <http://www.gnu.org/licenses/gpl.html>. * * See COPYRIGHT.txt for copyright notices and details. */ #include <atomic> #include <experimental/optional> #include <numeric> #include <gtest/gtest.h> #include "grppi.h" #include "dyn/dynamic_execution.h" #include "supported_executions.h" using namespace std; using namespace grppi; template <typename T> using optional = std::experimental::optional<T>; template <typename T> class context_test : public ::testing::Test { public: T execution_; dynamic_execution dyn_execution_{execution_}; sequential_execution seq_; parallel_execution_native thr_; #ifdef GRPPI_OMP parallel_execution_omp omp_; #endif #ifdef GRPPI_TBB parallel_execution_tbb tbb_; #endif // Variables int out; int counter; // Vectors vector<int> v{}; vector<vector<int> > v2{}; // Invocation counter std::atomic<int> invocations_init{0}; std::atomic<int> invocations_last{0}; std::atomic<int> invocations_intermediate{0}; std::atomic<int> invocations_intermediate2{0}; void setup_three_stages() { counter = 5; out = 0; } template <typename E> void run_three_stages_farm_with_sequential(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->seq_, grppi::farm(2, [this](int x) { invocations_intermediate++; return x*2; } ) ), [this](int x) { invocations_last++; out += x; }); } template <typename E> void run_three_stages_farm_with_native(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->thr_, grppi::farm(2, [this](int x) { invocations_intermediate++; return x*2; } ) ), [this](int x) { invocations_last++; out += x; }); } template <typename E> void run_three_stages_farm_with_omp(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, #ifdef GRPPI_OMP grppi::run_with(this->omp_, grppi::farm(2, [this](int x) { invocations_intermediate++; return x*2; } ) ), #endif [this](int x) { invocations_last++; out += x; }); } template <typename E> void run_three_stages_farm_with_tbb(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, #ifdef GRPPI_TBB grppi::run_with(this->tbb_, grppi::farm(2, [this](int x) { invocations_intermediate++; return x*2; } ) ), #endif [this](int x) { invocations_last++; out += x; }); } void check_three_stages() { EXPECT_EQ(6, invocations_init); EXPECT_EQ(5, invocations_last); EXPECT_EQ(5, invocations_intermediate); EXPECT_EQ(0, invocations_intermediate2); EXPECT_EQ(30, out); } void setup_composed() { counter = 5; out = 0; } template <typename E> void run_composed_pipeline_with_sequential(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->seq_, grppi::pipeline( [this](int x) { std::cerr << "squaring " << x << std::endl; invocations_intermediate++; std::cerr << "Incrementing\n"; return x*x; }, [this](int x) { invocations_intermediate2++; x *= 2; return x; } ) ), [this](int x) { invocations_last++; out +=x; }); } template <typename E> void run_composed_pipeline_with_native(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, grppi::run_with(this->thr_, grppi::pipeline( [this](int x) { std::cerr << "squaring " << x << std::endl; invocations_intermediate++; std::cerr << "Incrementing\n"; return x*x; }, [this](int x) { invocations_intermediate2++; x *= 2; return x; } ) ), [this](int x) { invocations_last++; out +=x; }); } template <typename E> void run_composed_pipeline_with_omp(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, #ifdef GRPPI_OMP grppi::run_with(this->omp_, grppi::pipeline( [this](int x) { std::cerr << "squaring " << x << std::endl; invocations_intermediate++; std::cerr << "Incrementing\n"; return x*x; }, [this](int x) { invocations_intermediate2++; x *= 2; return x; } ) ), #endif [this](int x) { invocations_last++; out +=x; }); } template <typename E> void run_composed_pipeline_with_tbb(const E & e) { grppi::pipeline(e, [this,i=0,max=counter]() mutable -> optional<int> { invocations_init++; if (++i<=max) return i; else return {}; }, #ifdef GRPPI_TBB grppi::run_with(this->tbb_, grppi::pipeline( [this](int x) { std::cerr << "squaring " << x << std::endl; invocations_intermediate++; std::cerr << "Incrementing\n"; return x*x; }, [this](int x) { invocations_intermediate2++; x *= 2; return x; } ) ), #endif [this](int x) { invocations_last++; out +=x; }); } void check_composed() { EXPECT_EQ(6, invocations_init); EXPECT_EQ(5, invocations_last); EXPECT_EQ(5, invocations_intermediate); EXPECT_EQ(5, invocations_intermediate2); EXPECT_EQ(110, out); } }; // Test for execution policies defined in supported_executions.h TYPED_TEST_CASE(context_test, executions_noff); TYPED_TEST(context_test, static_three_stages_farm_seq) { this->setup_three_stages(); this->run_three_stages_farm_with_sequential(this->execution_); this->check_three_stages(); } TYPED_TEST(context_test, static_three_stages_farm_nat) { this->setup_three_stages(); this->run_three_stages_farm_with_native(this->execution_); this->check_three_stages(); } #ifdef GRPPI_OMP TYPED_TEST(context_test, static_three_stages_farm_omp) { this->setup_three_stages(); this->run_three_stages_farm_with_omp(this->execution_); this->check_three_stages(); } #endif #ifdef GRPPI_TBB TYPED_TEST(context_test, static_three_stages_farm_tbb) { this->setup_three_stages(); this->run_three_stages_farm_with_tbb(this->execution_); this->check_three_stages(); } #endif TYPED_TEST(context_test, dyn_three_stages_farm_seq) { this->setup_three_stages(); this->run_three_stages_farm_with_sequential(this->dyn_execution_); this->check_three_stages(); } TYPED_TEST(context_test, dyn_three_stages_farm_nat) { this->setup_three_stages(); this->run_three_stages_farm_with_native(this->dyn_execution_); this->check_three_stages(); } #ifdef GRPPI_OMP TYPED_TEST(context_test, dyn_three_stages_farm_omp) { this->setup_three_stages(); this->run_three_stages_farm_with_omp(this->dyn_execution_); this->check_three_stages(); } #endif #ifdef GRPPI_TBB TYPED_TEST(context_test, dyn_three_stages_farm_tbb) { this->setup_three_stages(); this->run_three_stages_farm_with_tbb(this->dyn_execution_); this->check_three_stages(); } #endif TYPED_TEST(context_test, static_composed_pipeline_seq) { this->setup_composed(); this->run_composed_pipeline_with_sequential(this->execution_); this->check_composed(); } TYPED_TEST(context_test, static_composed_pipeline_nat) { this->setup_composed(); this->run_composed_pipeline_with_native(this->execution_); this->check_composed(); } #ifdef GRPPI_OMP TYPED_TEST(context_test, static_composed_pipeline_omp) { this->setup_composed(); this->run_composed_pipeline_with_omp(this->execution_); this->check_composed(); } #endif #ifdef GRPPI_TBB TYPED_TEST(context_test, static_composed_pipeline_tbb) { this->setup_composed(); this->run_composed_pipeline_with_tbb(this->execution_); this->check_composed(); } #endif TYPED_TEST(context_test, dyn_composed_pipeline_seq) { this->setup_composed(); this->run_composed_pipeline_with_sequential(this->dyn_execution_); this->check_composed(); } TYPED_TEST(context_test, dyn_composed_pipeline_nat) { this->setup_composed(); this->run_composed_pipeline_with_native(this->dyn_execution_); this->check_composed(); } #ifdef GRPPI_OMP TYPED_TEST(context_test, dyn_composed_pipeline_omp) { this->setup_composed(); this->run_composed_pipeline_with_omp(this->dyn_execution_); this->check_composed(); } #endif #ifdef GRPPI_TBB TYPED_TEST(context_test, dyn_composed_pipeline_tbb) { this->setup_composed(); this->run_composed_pipeline_with_tbb(this->dyn_execution_); this->check_composed(); } #endif <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D2.cpp * Author : Kazune Takahashi * Created : 2020/3/9 17:08:58 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- using shop = tuple<ll, ll>; ostream &operator<<(ostream &os, shop const &s) { return os << "(" << get<0>(s) << ", " << get<1>(s) << ")"; } class Solve { static constexpr int C{32}; int N, M, L; ll T; vector<shop> V; vector<shop> normal, zero; vector<ll> sum; vector<vector<ll>> dp; public: Solve(int N, ll T, vector<shop> V) : N{N}, T{T}, V(V) { make_normal_zero(); execute_dp(); cout << calc_ans() << endl; } private: static bool compare_normal(shop const &left, shop const &right) { return (get<0>(right) - 1) * get<1>(left) - (get<0>(left) - 1) * get<1>(right) < 0; } static bool compare_zero(shop const &left, shop const &right) { return get<1>(left) < get<1>(right); } ll f(int i, ll x) { return get<0>(normal[i]) * x + get<1>(normal[i]); } void make_normal_zero() { for (auto i = 0; i < N; ++i) { if (get<0>(V[i]) >= 2) { normal.push_back(V[i]); } else { zero.push_back(V[i]); } } M = normal.size(); L = zero.size(); sort(normal.begin(), normal.end(), compare_normal); sort(zero.begin(), zero.end(), compare_zero); exit(0); sum = vector<ll>(L + 1, 0); for (auto i = 0; i < L; ++i) { sum[i + 1] = sum[i] + get<1>(zero[i]); } } void execute_dp() { dp = vector<vector<ll>>(M + 1, vector<ll>(C, infty)); dp[0][0] = 0; for (auto i = 0; i < M; ++i) { dp[i + 1][0] = dp[i][0]; for (auto j = 1; j < C; ++j) { dp[i + 1][j] = min(dp[i][j], f(i, dp[i][j - 1])); } } } int calc_ans() { int ans{0}; for (auto i = 0; i < C; ++i) { ll remain{T - dp[M][i]}; if (remain < 0) { continue; } int z{static_cast<int>(upper_bound(sum.begin(), sum.end(), remain) - sum.begin()) - 1}; ch_max(ans, z + i); } return ans; } }; int main() { int N; ll T; cin >> N >> T; vector<shop> V(N); for (auto i = 0; i < N; ++i) { ll a, b; cin >> a >> b; V[i] = shop(a + 1, a + b + 1); } Solve solve(N, T, V); } <commit_msg>submit D2.cpp to 'D - Manga Market' (hitachi2020) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : D2.cpp * Author : Kazune Takahashi * Created : 2020/3/9 17:08:58 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- using shop = tuple<ll, ll>; ostream &operator<<(ostream &os, shop const &s) { return os << "(" << get<0>(s) << ", " << get<1>(s) << ")"; } class Solve { static constexpr int C{32}; int N, M, L; ll T; vector<shop> V; vector<shop> normal, zero; vector<ll> sum; vector<vector<ll>> dp; public: Solve(int N, ll T, vector<shop> V) : N{N}, T{T}, V(V) { make_normal_zero(); execute_dp(); cout << calc_ans() << endl; } private: static bool compare_normal(shop const &left, shop const &right) { return (get<0>(right) - 1) * get<1>(left) - (get<0>(left) - 1) * get<1>(right) < 0; } static bool compare_zero(shop const &left, shop const &right) { return get<1>(left) < get<1>(right); } ll f(int i, ll x) { return get<0>(normal[i]) * x + get<1>(normal[i]); } void make_normal_zero() { for (auto i = 0; i < N; ++i) { if (get<0>(V[i]) >= 2) { normal.push_back(V[i]); } else { zero.push_back(V[i]); } } M = normal.size(); L = zero.size(); sort(normal.begin(), normal.end(), compare_normal); sort(zero.begin(), zero.end(), compare_zero); sum = vector<ll>(L + 1, 0); for (auto i = 0; i < L; ++i) { sum[i + 1] = sum[i] + get<1>(zero[i]); } } void execute_dp() { dp = vector<vector<ll>>(M + 1, vector<ll>(C, infty)); dp[0][0] = 0; for (auto i = 0; i < M; ++i) { dp[i + 1][0] = dp[i][0]; for (auto j = 1; j < C; ++j) { dp[i + 1][j] = min(dp[i][j], f(i, dp[i][j - 1])); } } } int calc_ans() { int ans{0}; for (auto i = 0; i < C; ++i) { ll remain{T - dp[M][i]}; if (remain < 0) { continue; } int z{static_cast<int>(upper_bound(sum.begin(), sum.end(), remain) - sum.begin()) - 1}; ch_max(ans, z + i); } return ans; } }; int main() { int N; ll T; cin >> N >> T; vector<shop> V(N); for (auto i = 0; i < N; ++i) { ll a, b; cin >> a >> b; V[i] = shop(a + 1, a + b + 1); } Solve solve(N, T, V); } <|endoftext|>
<commit_before>#include "Commands.h" #include <unistd.h> #include <sys/wait.h> static const int STDIN_FD = 0; static const int STDOUT_FD = 1; Atomic::Atomic(const std::vector<std::string>& cmdline, const std::vector<Redirection*>& redirections, bool _background) : _cmdline(cmdline), _redirections(redirections), _background(_background) {} int Atomic::run() { if(_cmdline.empty()) { return 0; //} else if(_cmdline.front() == "cd") { } else { int oldstdin = dup(STDIN_FD); int oldstdout = dup(STDOUT_FD); for(Redirection* r : _redirections) { r->doRedirection(); } pid_t pid = fork(); if(pid == 0) { std::vector<char*> argv; argv.reserve(_cmdline.size()+1); std::string commandPath = "/usr/bin/" + _cmdline[0]; for(size_t i = 0; i < _cmdline.size(); ++i) { argv.push_back(const_cast<char*>(_cmdline[i].data())); } argv.push_back(nullptr); execv(commandPath.data(), reinterpret_cast<char * const *>(argv.data())); return 42; //make gcc happy } else { int res; wait(&res); dup2(oldstdin, STDIN_FD); dup2(oldstdout, STDOUT_FD); close(oldstdin); close(oldstdout); return res; } } } If::If(Command* cond, Command* ifcommand, Command* elsecommand) : _cond(cond), _ifcommand(ifcommand), _elsecommand(elsecommand) {} int If::run() { int condres = _cond->run(); if(condres == 0) { return _ifcommand->run(); } else { return _elsecommand->run(); } } Pipe::Pipe(Command* producer, Command* consumer) : _producer(producer), _consumer(consumer) {} int Pipe::run() { int pipes[2]; if(pipe(pipes) != 0) { perror("pipe"); return -1; } int pipeout = pipes[0]; int pipein = pipes[1]; pid_t pid = fork(); if(pid == 0) { //producer dup2(pipein, STDOUT_FD); close(pipeout); close(pipein); _producer->run(); exit(0); } else { //consumer int oldstdin = dup(STDIN_FD); dup2(pipeout, STDIN_FD); close(pipein); close(pipeout); int res = _consumer->run(); wait(nullptr); dup2(oldstdin, STDIN_FD); close(oldstdin); return res; } } And::And(Command* command1, Command* command2) : _command1(command1), _command2(command2) {} int And::run() { int res1 = _command1->run(); if(res1 == 0) { return _command2->run(); } else { return res1; } } Or::Or(Command* command1, Command* command2) : _command1(command1), _command2(command2) {} int Or::run() { int res1 = _command1->run(); if(res1 != 0) { return _command2->run(); } else { return res1; } } Seq::Seq(Command* command1, Command* command2) : _command1(command1), _command2(command2) {} int Seq::run() { _command1->run(); return _command2->run(); } <commit_msg>Improve ttsh<commit_after>#include "Commands.h" #include <unistd.h> #include <sys/wait.h> static const int STDIN_FD = 0; static const int STDOUT_FD = 1; Atomic::Atomic(const std::vector<std::string>& cmdline, const std::vector<Redirection*>& redirections, bool _background) : _cmdline(cmdline), _redirections(redirections), _background(_background) {} int Atomic::run() { if(_cmdline.empty()) { return 0; //} else if(_cmdline.front() == "cd") { } else { int oldstdin = dup(STDIN_FD); int oldstdout = dup(STDOUT_FD); for(Redirection* r : _redirections) { r->doRedirection(); } pid_t pid = fork(); if(pid == 0) { std::vector<char*> argv; argv.reserve(_cmdline.size()+1); bool hasSlash = false; for(size_t i = 0; i < _cmdline[0].size(); ++i) { hasSlash |= (_cmdline[0][i] == '/'); } std::string commandPath = hasSlash ? _cmdline[0] : ("/usr/bin/" + _cmdline[0]); for(size_t i = 0; i < _cmdline.size(); ++i) { argv.push_back(const_cast<char*>(_cmdline[i].data())); } argv.push_back(nullptr); if(execv(commandPath.data(), reinterpret_cast<char * const *>(argv.data()))) { perror("execv"); return -1; } return 42; //make gcc happy } else { int res; wait(&res); dup2(oldstdin, STDIN_FD); dup2(oldstdout, STDOUT_FD); close(oldstdin); close(oldstdout); return res; } } } If::If(Command* cond, Command* ifcommand, Command* elsecommand) : _cond(cond), _ifcommand(ifcommand), _elsecommand(elsecommand) {} int If::run() { int condres = _cond->run(); if(condres == 0) { return _ifcommand->run(); } else { return _elsecommand->run(); } } Pipe::Pipe(Command* producer, Command* consumer) : _producer(producer), _consumer(consumer) {} int Pipe::run() { int pipes[2]; if(pipe(pipes) != 0) { perror("pipe"); return -1; } int pipeout = pipes[0]; int pipein = pipes[1]; pid_t pid = fork(); if(pid == 0) { //producer dup2(pipein, STDOUT_FD); close(pipeout); close(pipein); _producer->run(); exit(0); } else { //consumer int oldstdin = dup(STDIN_FD); dup2(pipeout, STDIN_FD); close(pipein); close(pipeout); int res = _consumer->run(); wait(nullptr); dup2(oldstdin, STDIN_FD); close(oldstdin); return res; } } And::And(Command* command1, Command* command2) : _command1(command1), _command2(command2) {} int And::run() { int res1 = _command1->run(); if(res1 == 0) { return _command2->run(); } else { return res1; } } Or::Or(Command* command1, Command* command2) : _command1(command1), _command2(command2) {} int Or::run() { int res1 = _command1->run(); if(res1 != 0) { return _command2->run(); } else { return res1; } } Seq::Seq(Command* command1, Command* command2) : _command1(command1), _command2(command2) {} int Seq::run() { _command1->run(); return _command2->run(); } <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2015 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_COLLECTIONS_DETAIL_TRIE_ORDERED_MULTIMAP_HXX #define _ABACLADE_COLLECTIONS_DETAIL_TRIE_ORDERED_MULTIMAP_HXX #ifndef _ABACLADE_HXX #error "Please #include <abaclade.hxx> before this file" #endif #ifdef ABC_CXX_PRAGMA_ONCE #pragma once #endif #include <abaclade/collections/type_void_adapter.hxx> #include <abaclade/numeric.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// namespace abc { namespace collections { namespace detail { //! Implementation of abc::collections::trie_ordered_multimap for scalar key types. class ABACLADE_SYM scalar_keyed_trie_ordered_multimap_impl { private: /*! Determines the compactness of each level of the tree. Packing multiple bits on each level results in faster lookups and fewer memory allocations, at the cost of increased slack in each tree node. */ static unsigned const smc_cBitsPerLevel = 4; //! Count of children pointers that each tree node needs. static unsigned const smc_cBitPermutationsPerLevel = 1 << smc_cBitsPerLevel; static unsigned const smc_iTreeAnchorLevel = sizeof(std::uintmax_t /*TODO: TKey*/) * 8 /*TODO: CHAR_BIT*/ / smc_cBitsPerLevel - 1; protected: /*! Abstract node. Defined to avoid using void * in code where pointers’ type change depending on the level in the tree. */ class node { }; //! Stores a single value, as well as the doubly-linked list’s links. class list_node : public node { public: //! Constructor. list_node() : m_plnNext(nullptr), m_plnPrev(nullptr) { } void unlink_and_destruct(type_void_adapter const & type) const; /*! Returns a pointer to the contained value. @param type Adapter for the value’s type. @return Pointer to the contained value. */ void * value_ptr(type_void_adapter const & type) const; /*! Returns a typed pointer to the contained TValue. @return Pointer to the contained value. */ template <typename TValue> TValue * value_ptr() const { type_void_adapter typeValue; typeValue.set_align<TValue>(); return static_cast<TValue *>(value_ptr(typeValue)); } public: //! Pointer to the next node. list_node * m_plnNext; //! Pointer to the previous node. list_node * m_plnPrev; // The contained value of type T follow immediately, taking alignment into consideration. }; //! Non-leaf node. class tree_node : public node { public: //! Constructor. tree_node() { memory::clear(&m_apnChildren); } public: //! Child prefix pointers; one for each permutation of the bits mapped to this tree node. node * m_apnChildren[smc_cBitPermutationsPerLevel]; }; //! Anchors value lists to the tree, mapping the last bits of the key. class anchor_node : public tree_node { public: //! Constructor. anchor_node() { memory::clear(&m_aplnChildrenLasts); } public: //! Child lists end pointers; one for each permutation of the bits mapped to this tree node. list_node * m_aplnChildrenLasts[smc_cBitPermutationsPerLevel]; }; struct indexed_anchor { anchor_node * pan; unsigned iBitsPermutation; indexed_anchor(anchor_node * _pan, unsigned _iBitsPermutation) : pan(_pan), iBitsPermutation(_iBitsPermutation) { } }; //! Key/pointer-to-value pair. struct key_value_pair { std::uintmax_t iKey; list_node * pln; key_value_pair(std::uintmax_t _iKey, list_node * _pln) : iKey(_iKey), pln(_pln) { } }; public: /*! Constructor. @param tommi Source object. */ scalar_keyed_trie_ordered_multimap_impl() : m_pnRoot(nullptr), m_cValues(0) { } scalar_keyed_trie_ordered_multimap_impl(scalar_keyed_trie_ordered_multimap_impl && tommi); //! Destructor. ~scalar_keyed_trie_ordered_multimap_impl() { } /*! Adds a key/value pair to the map. @param typeValue Adapter for the value’s type. @param iKey Key to add. @param value Value to add. @param bMove true to move *pValue to the new node’s value, or false to copy it instead. @return Pointer to the newly-added list node. */ list_node * add( type_void_adapter const & typeValue, std::uintmax_t iKey, void const * pValue, bool bMove ); /*! Removes all elements from the map. @param typeValue Adapter for the value’s type. */ void clear(type_void_adapter const & typeValue); /*! Returns true if the map contains no elements. @return true if the map is empty, or false otherwise. */ bool empty() const { return m_cValues == 0; } /*! Searches the multimap for a specific key, returning a pointer to the first corresponding list node if found. @param iKey Key to search for. @return Pointer to the to the first matching list node, or nullptr if the key could not be found. */ list_node * find(std::uintmax_t iKey); /*! Returns a pointer to the first value in the map. @return Pointer to the first value in the map. */ key_value_pair front(); /*! Returns the count of values in the map. Note that this may be higher than the count of keys in the map. @return Count of values. */ std::size_t size() const { return m_cValues; } protected: void remove_value(type_void_adapter const & typeValue, std::uintmax_t iKey, list_node * pln); private: indexed_anchor descend_to_anchor(std::uintmax_t iKey) const; void destruct_list(type_void_adapter const & type, list_node * pln); void destruct_anchor_node(type_void_adapter const & typeValue, anchor_node * pan); void destruct_tree_node(type_void_adapter const & typeValue, tree_node * ptn, unsigned iLevel); private: /*! Pointer to the top-level node. The type should be tree_node *, but some code requires this to be the same as tree_node::m_apnChildren[0]. */ node * m_pnRoot; //! Count of values. This may be more than the count of keys. std::size_t m_cValues; }; }}} //namespace abc::collections::detail //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //ifndef _ABACLADE_COLLECTIONS_DETAIL_TRIE_ORDERED_MULTIMAP_HXX <commit_msg>Use CHAR_BIT instead of 8<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2015 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_COLLECTIONS_DETAIL_TRIE_ORDERED_MULTIMAP_HXX #define _ABACLADE_COLLECTIONS_DETAIL_TRIE_ORDERED_MULTIMAP_HXX #ifndef _ABACLADE_HXX #error "Please #include <abaclade.hxx> before this file" #endif #ifdef ABC_CXX_PRAGMA_ONCE #pragma once #endif #include <abaclade/collections/type_void_adapter.hxx> #include <abaclade/numeric.hxx> #include <climits> // CHAR_BIT //////////////////////////////////////////////////////////////////////////////////////////////////// namespace abc { namespace collections { namespace detail { //! Implementation of abc::collections::trie_ordered_multimap for scalar key types. class ABACLADE_SYM scalar_keyed_trie_ordered_multimap_impl { private: /*! Determines the compactness of each level of the tree. Packing multiple bits on each level results in faster lookups and fewer memory allocations, at the cost of increased slack in each tree node. */ static unsigned const smc_cBitsPerLevel = 4; //! Count of children pointers that each tree node needs. static unsigned const smc_cBitPermutationsPerLevel = 1 << smc_cBitsPerLevel; static unsigned const smc_iTreeAnchorLevel = sizeof(std::uintmax_t /*TODO: TKey*/) * CHAR_BIT / smc_cBitsPerLevel - 1; protected: /*! Abstract node. Defined to avoid using void * in code where pointers’ type change depending on the level in the tree. */ class node { }; //! Stores a single value, as well as the doubly-linked list’s links. class list_node : public node { public: //! Constructor. list_node() : m_plnNext(nullptr), m_plnPrev(nullptr) { } void unlink_and_destruct(type_void_adapter const & type) const; /*! Returns a pointer to the contained value. @param type Adapter for the value’s type. @return Pointer to the contained value. */ void * value_ptr(type_void_adapter const & type) const; /*! Returns a typed pointer to the contained TValue. @return Pointer to the contained value. */ template <typename TValue> TValue * value_ptr() const { type_void_adapter typeValue; typeValue.set_align<TValue>(); return static_cast<TValue *>(value_ptr(typeValue)); } public: //! Pointer to the next node. list_node * m_plnNext; //! Pointer to the previous node. list_node * m_plnPrev; // The contained value of type T follow immediately, taking alignment into consideration. }; //! Non-leaf node. class tree_node : public node { public: //! Constructor. tree_node() { memory::clear(&m_apnChildren); } public: //! Child prefix pointers; one for each permutation of the bits mapped to this tree node. node * m_apnChildren[smc_cBitPermutationsPerLevel]; }; //! Anchors value lists to the tree, mapping the last bits of the key. class anchor_node : public tree_node { public: //! Constructor. anchor_node() { memory::clear(&m_aplnChildrenLasts); } public: //! Child lists end pointers; one for each permutation of the bits mapped to this tree node. list_node * m_aplnChildrenLasts[smc_cBitPermutationsPerLevel]; }; struct indexed_anchor { anchor_node * pan; unsigned iBitsPermutation; indexed_anchor(anchor_node * _pan, unsigned _iBitsPermutation) : pan(_pan), iBitsPermutation(_iBitsPermutation) { } }; //! Key/pointer-to-value pair. struct key_value_pair { std::uintmax_t iKey; list_node * pln; key_value_pair(std::uintmax_t _iKey, list_node * _pln) : iKey(_iKey), pln(_pln) { } }; public: /*! Constructor. @param tommi Source object. */ scalar_keyed_trie_ordered_multimap_impl() : m_pnRoot(nullptr), m_cValues(0) { } scalar_keyed_trie_ordered_multimap_impl(scalar_keyed_trie_ordered_multimap_impl && tommi); //! Destructor. ~scalar_keyed_trie_ordered_multimap_impl() { } /*! Adds a key/value pair to the map. @param typeValue Adapter for the value’s type. @param iKey Key to add. @param value Value to add. @param bMove true to move *pValue to the new node’s value, or false to copy it instead. @return Pointer to the newly-added list node. */ list_node * add( type_void_adapter const & typeValue, std::uintmax_t iKey, void const * pValue, bool bMove ); /*! Removes all elements from the map. @param typeValue Adapter for the value’s type. */ void clear(type_void_adapter const & typeValue); /*! Returns true if the map contains no elements. @return true if the map is empty, or false otherwise. */ bool empty() const { return m_cValues == 0; } /*! Searches the multimap for a specific key, returning a pointer to the first corresponding list node if found. @param iKey Key to search for. @return Pointer to the to the first matching list node, or nullptr if the key could not be found. */ list_node * find(std::uintmax_t iKey); /*! Returns a pointer to the first value in the map. @return Pointer to the first value in the map. */ key_value_pair front(); /*! Returns the count of values in the map. Note that this may be higher than the count of keys in the map. @return Count of values. */ std::size_t size() const { return m_cValues; } protected: void remove_value(type_void_adapter const & typeValue, std::uintmax_t iKey, list_node * pln); private: indexed_anchor descend_to_anchor(std::uintmax_t iKey) const; void destruct_list(type_void_adapter const & type, list_node * pln); void destruct_anchor_node(type_void_adapter const & typeValue, anchor_node * pan); void destruct_tree_node(type_void_adapter const & typeValue, tree_node * ptn, unsigned iLevel); private: /*! Pointer to the top-level node. The type should be tree_node *, but some code requires this to be the same as tree_node::m_apnChildren[0]. */ node * m_pnRoot; //! Count of values. This may be more than the count of keys. std::size_t m_cValues; }; }}} //namespace abc::collections::detail //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //ifndef _ABACLADE_COLLECTIONS_DETAIL_TRIE_ORDERED_MULTIMAP_HXX <|endoftext|>
<commit_before>/** @file iterativeSolvers.cpp @brief Example on how the solve a system of linear equation with the MINRES and CG method. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): J. Sogn */ #include <iostream> #include <gismo.h> using std::cout; using std::endl; using namespace gismo; int main(int argc, char *argv[]) { //Size of linear system index_t N = 200; if (argc >= 2) N = atoi(argv[1]); gsMatrix<> mat; gsMatrix<> rhs; mat.setZero(N,N); rhs.setRandom(N,1); //Create a tri-diagonal matrix with -1 of the off diagonals and 2 in the diagonal. //This matrix is equivalent to discretizing the 1D Poisson equation with homogenius //Dirichlet boundary condition using a finit difference schema. It is a SPD matrix. mat(0,0) = 2; mat(0,1) = -1; mat(N-1, N-1) = 2; mat(N-1, N-2) = -1; for (index_t k = 1; k < N-1; ++k) { mat(k,k) = 2; mat(k,k-1) = -1; mat(k,k+1) = -1; } //The minimal residual implementation requires a preconditioner. //We initialize an Identity preconditioner (does nothing). gsIdentityPreconditioner preConMat(N); //Set maximum number of iterations index_t maxIters = 1000; //Set tolerance real_t tol = 1e-08; //Initialize the MinRes solver gsMinimalResidual MinRes(mat,maxIters,tol); //Create the initial guess gsMatrix<> x0; x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "MinRes: Before solve" << std::endl; MinRes.solve(rhs,x0,preConMat); gsInfo << "MinRes: After solve" << std::endl; gsInfo << "MinRes: Solved a system of size " << N << "\n"; gsInfo << "MinRes: Tolerance: " << tol << "\n"; gsInfo << "MinRes: Residual error: " << MinRes.error() << "\n"; gsInfo << "MinRes: Number of iterations: " << MinRes.iterations() << "\n"; //Initialize the CG solver gsConjugateGradient CGSolver(mat,maxIters,tol); //Set the initial guess to zero x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nCG: Before solve" << std::endl; CGSolver.solve(rhs,x0,preConMat); gsInfo << "CG: After solve" << std::endl; gsInfo << "CG: Solved a system of size " << N << "\n"; gsInfo << "CG: Tolerance: " << tol << "\n"; gsInfo << "CG: Residual error: " << CGSolver.error() << "\n"; gsInfo << "CG: Number of iterations: " << CGSolver.iterations() << "\n"; int result = (MinRes.error()<tol)?0:1; result += (CGSolver.error()<tol)?0:1; return result; } <commit_msg>Updated example to include GMRes<commit_after>/** @file iterativeSolvers.cpp @brief Example on how the solve a system of linear equation with the MINRES and CG method. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): J. Sogn */ #include <iostream> #include <gismo.h> using std::cout; using std::endl; using namespace gismo; int main(int argc, char *argv[]) { //Size of linear system index_t N = 200; if (argc >= 2) N = atoi(argv[1]); gsMatrix<> mat; gsMatrix<> rhs; mat.setZero(N,N); rhs.setRandom(N,1); //Create a tri-diagonal matrix with -1 of the off diagonals and 2 in the diagonal. //This matrix is equivalent to discretizing the 1D Poisson equation with homogenius //Dirichlet boundary condition using a finit difference schema. It is a SPD matrix. mat(0,0) = 2; mat(0,1) = -1; mat(N-1, N-1) = 2; mat(N-1, N-2) = -1; for (index_t k = 1; k < N-1; ++k) { mat(k,k) = 2; mat(k,k-1) = -1; mat(k,k+1) = -1; } //The minimal residual implementation requires a preconditioner. //We initialize an Identity preconditioner (does nothing). gsIdentityPreconditioner preConMat(N); //Set maximum number of iterations index_t maxIters = 1000; //Set tolerance real_t tol = 1e-08; //Initialize the MinRes solver gsMinimalResidual MinRes(mat,maxIters,tol); //Create the initial guess gsMatrix<> x0; x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nMinRes: Before solve" << std::endl; MinRes.solve(rhs,x0,preConMat); gsInfo << "MinRes: After solve" << std::endl; gsInfo << "MinRes: Solved a system of size " << N << "\n"; gsInfo << "MinRes: Tolerance: " << tol << "\n"; gsInfo << "MinRes: Residual error: " << MinRes.error() << "\n"; gsInfo << "MinRes: Number of iterations: " << MinRes.iterations() << "\n"; //Initialize the CG solver gsGMRes GMResSolver(mat,maxIters,tol); //Set the initial guess to zero x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nGMRes: Before solve" << std::endl; GMResSolver.solve(rhs,x0,preConMat); gsInfo << "GMRes: After solve" << std::endl; gsInfo << "GMRes: Solved a system of size " << N << "\n"; gsInfo << "GMRes: Tolerance: " << tol << "\n"; gsInfo << "GMRes: Residual error: " << GMResSolver.error() << "\n"; gsInfo << "GMRes: Number of iterations: " << GMResSolver.iterations() << "\n"; //Initialize the CG solver gsConjugateGradient CGSolver(mat,maxIters,tol); //Set the initial guess to zero x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nCG: Before solve" << std::endl; CGSolver.solve(rhs,x0,preConMat); gsInfo << "CG: After solve" << std::endl; gsInfo << "CG: Solved a system of size " << N << "\n"; gsInfo << "CG: Tolerance: " << tol << "\n"; gsInfo << "CG: Residual error: " << CGSolver.error() << "\n"; gsInfo << "CG: Number of iterations: " << CGSolver.iterations() << "\n"; int result = (MinRes.error()<tol)?0:1; result += (CGSolver.error()<tol)?0:1; return result; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <exception> #include <algorithm> #include <iostream> using std::endl ; #include <vector> using std::vector ; #include <sofa/helper/logging/Messaging.h> using sofa::helper::logging::MessageDispatcher ; #include <sofa/helper/logging/MessageHandler.h> using sofa::helper::logging::MessageHandler ; #include <sofa/helper/logging/Message.h> using sofa::helper::logging::Message ; #include <sofa/core/objectmodel/BaseObject.h> #include <sofa/core/ObjectFactory.h> class MyMessageHandler : public MessageHandler { vector<Message> m_messages ; public: virtual void process(Message& m){ m_messages.push_back(m); if( !m.sender().empty() ) std::cerr<<m<<std::endl; } int numMessages(){ return m_messages.size() ; } const vector<Message>& messages() const { return m_messages; } const Message& lastMessage() const { return m_messages.back(); } } ; class MyComponent : public sofa::core::objectmodel::BaseObject { public: SOFA_CLASS( MyComponent, sofa::core::objectmodel::BaseObject ); MyComponent() { f_printLog.setValue(true); // to print sout serr<<"regular serr"<<sendl; sout<<"regular sout"<<sendl; serr<<SOFA_FILE_INFO<<"serr with fileinfo"<<sendl; sout<<SOFA_FILE_INFO<<"sout with fileinfo"<<sendl; } }; SOFA_DECL_CLASS(MyComponent) int MyComponentClass = sofa::core::RegisterObject("MyComponent") .add< MyComponent >(); TEST(LoggingTest, noHandler) { MessageDispatcher::clearHandlers() ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; } TEST(LoggingTest, oneHandler) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; // add is expected to return the handler ID. Here is it the o'th EXPECT_TRUE(MessageDispatcher::addHandler(&h) == 0 ) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3 ) ; } TEST(LoggingTest, duplicatedHandler) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; // First add is expected to return the handler ID. EXPECT_TRUE(MessageDispatcher::addHandler(&h) == 0) ; // Second is supposed to fail to add and thus return -1. EXPECT_TRUE(MessageDispatcher::addHandler(&h) == -1) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3) ; } TEST(LoggingTest, withoutDevMode) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; nmsg_info("") << " null info message with conversion" << 1.5 << "\n" ; nmsg_warning("") << " null warning message with conversion "<< 1.5 << "\n" ; nmsg_error("") << " null error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3 ) ; } //TEST(LoggingTest, speedTest) //{ // MessageDispatcher::clearHandlers() ; // MyMessageHandler h; // MessageDispatcher::addHandler(&h) ; // for(unsigned int i=0;i<10000;i++){ // msg_info("") << " info message with conversion" << 1.5 << "\n" ; // msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; // msg_error("") << " error message with conversion" << 1.5 << "\n" ; // } //} TEST(LoggingTest, BaseObject) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; MyComponent c; EXPECT_EQ( h.numMessages(), 4 ) ; if( h.numMessages() < 4 ) return; // not to crash c.serr<<"regular external serr"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Warning ); c.serr<<sofa::helper::logging::Message::Error<<"external serr as Error"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Error ); c.sout<<"regular external sout"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Info ); c.sout<<sofa::helper::logging::Message::Error<<"external sout as Error"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Error ); c.serr<<SOFA_FILE_INFO<<"external serr with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); c.sout<<SOFA_FILE_INFO<<"external sout with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); c.serr<<SOFA_FILE_INFO<<sofa::helper::logging::Message::Error<<"external serr as Error with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Error ); c.sout<<sofa::helper::logging::Message::Error<<SOFA_FILE_INFO<<"external sout as Error with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Error ); c.serr<<"serr with sendl that comes in a second time"; c.serr<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Warning ); c.serr<<"\n serr with \n end of "<<std::endl<<" lines"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Warning ); EXPECT_EQ( h.numMessages(), 14 ) ; } #undef MESSAGING_H #define WITH_SOFA_DEVTOOLS #undef dmsg_info #undef dmsg_error #undef dmsg_warning #undef dmsg_fatal #include <sofa/helper/logging/Messaging.h> TEST(LoggingTest, withDevMode) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; nmsg_info("") << " null info message with conversion" << 1.5 << "\n" ; nmsg_warning("") << " null warning message with conversion "<< 1.5 << "\n" ; nmsg_error("") << " null error message with conversion" << 1.5 << "\n" ; dmsg_info("") << " debug info message with conversion" << 1.5 << "\n" ; dmsg_warning("") << " debug warning message with conversion "<< 1.5 << "\n" ; dmsg_error("") << " debug error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 6 ) ; } <commit_msg>[logger] a bit more details on the failing test<commit_after>#include <gtest/gtest.h> #include <exception> #include <algorithm> #include <iostream> using std::endl ; #include <vector> using std::vector ; #include <sofa/helper/logging/Messaging.h> using sofa::helper::logging::MessageDispatcher ; #include <sofa/helper/logging/MessageHandler.h> using sofa::helper::logging::MessageHandler ; #include <sofa/helper/logging/Message.h> using sofa::helper::logging::Message ; #include <sofa/core/objectmodel/BaseObject.h> #include <sofa/core/ObjectFactory.h> class MyMessageHandler : public MessageHandler { vector<Message> m_messages ; public: virtual void process(Message& m){ m_messages.push_back(m); if( !m.sender().empty() ) std::cerr<<m<<std::endl; } int numMessages(){ return m_messages.size() ; } const vector<Message>& messages() const { return m_messages; } const Message& lastMessage() const { return m_messages.back(); } } ; class MyComponent : public sofa::core::objectmodel::BaseObject { public: SOFA_CLASS( MyComponent, sofa::core::objectmodel::BaseObject ); MyComponent() { f_printLog.setValue(true); // to print sout serr<<"regular serr"<<sendl; sout<<"regular sout"<<sendl; serr<<SOFA_FILE_INFO<<"serr with fileinfo"<<sendl; sout<<SOFA_FILE_INFO<<"sout with fileinfo"<<sendl; } }; SOFA_DECL_CLASS(MyComponent) int MyComponentClass = sofa::core::RegisterObject("MyComponent") .add< MyComponent >(); TEST(LoggingTest, noHandler) { MessageDispatcher::clearHandlers() ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; } TEST(LoggingTest, oneHandler) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; // add is expected to return the handler ID. Here is it the o'th EXPECT_TRUE(MessageDispatcher::addHandler(&h) == 0 ) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3 ) ; } TEST(LoggingTest, duplicatedHandler) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; // First add is expected to return the handler ID. EXPECT_TRUE(MessageDispatcher::addHandler(&h) == 0) ; // Second is supposed to fail to add and thus return -1. EXPECT_TRUE(MessageDispatcher::addHandler(&h) == -1) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3) ; } TEST(LoggingTest, withoutDevMode) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; nmsg_info("") << " null info message with conversion" << 1.5 << "\n" ; nmsg_warning("") << " null warning message with conversion "<< 1.5 << "\n" ; nmsg_error("") << " null error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3 ) ; } //TEST(LoggingTest, speedTest) //{ // MessageDispatcher::clearHandlers() ; // MyMessageHandler h; // MessageDispatcher::addHandler(&h) ; // for(unsigned int i=0;i<10000;i++){ // msg_info("") << " info message with conversion" << 1.5 << "\n" ; // msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; // msg_error("") << " error message with conversion" << 1.5 << "\n" ; // } //} TEST(LoggingTest, BaseObject) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; MyComponent c; /// the constructor is sending 4 messages EXPECT_EQ( h.numMessages(), 4 ) ; if( h.numMessages() == 4 ) // not to crash { c.serr<<"regular external serr"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Warning ); c.serr<<sofa::helper::logging::Message::Error<<"external serr as Error"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Error ); c.sout<<"regular external sout"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Info ); c.sout<<sofa::helper::logging::Message::Error<<"external sout as Error"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Error ); } c.serr<<SOFA_FILE_INFO<<"external serr with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); c.sout<<SOFA_FILE_INFO<<"external sout with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); c.serr<<SOFA_FILE_INFO<<sofa::helper::logging::Message::Error<<"external serr as Error with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Error ); c.sout<<sofa::helper::logging::Message::Error<<SOFA_FILE_INFO<<"external sout as Error with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Error ); c.serr<<"serr with sendl that comes in a second time"; c.serr<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Warning ); c.serr<<"\n serr with \n end of "<<std::endl<<" lines"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); EXPECT_EQ( h.lastMessage().type(), sofa::helper::logging::Message::Warning ); EXPECT_EQ( h.numMessages(), 14 ) ; } #undef MESSAGING_H #define WITH_SOFA_DEVTOOLS #undef dmsg_info #undef dmsg_error #undef dmsg_warning #undef dmsg_fatal #include <sofa/helper/logging/Messaging.h> TEST(LoggingTest, withDevMode) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; nmsg_info("") << " null info message with conversion" << 1.5 << "\n" ; nmsg_warning("") << " null warning message with conversion "<< 1.5 << "\n" ; nmsg_error("") << " null error message with conversion" << 1.5 << "\n" ; dmsg_info("") << " debug info message with conversion" << 1.5 << "\n" ; dmsg_warning("") << " debug warning message with conversion "<< 1.5 << "\n" ; dmsg_error("") << " debug error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 6 ) ; } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "AddSideSetsFromBoundingBox.h" #include "Conversion.h" #include "MooseMesh.h" #include "MooseTypes.h" registerMooseObject("MooseApp", AddSideSetsFromBoundingBox); template <> InputParameters validParams<AddSideSetsFromBoundingBox>() { InputParameters params = validParams<MeshModifier>(); params.addClassDescription("Find sidesets with given boundary ids in bounding box and add new " "boundary id. This can be done by finding all required boundary " "and adding the new boundary id to those sidesets. Alternatively, " "a number of boundary ids can be provided and all nodes within the " "bounding box that have all the required boundary ids will have a new" "boundary id added."); MooseEnum location("INSIDE OUTSIDE", "INSIDE"); params.addRequiredParam<RealVectorValue>( "bottom_left", "The bottom left point (in x,y,z with spaces in-between)."); params.addRequiredParam<RealVectorValue>( "top_right", "The bottom left point (in x,y,z with spaces in-between)."); params.addRequiredParam<SubdomainID>("block_id", "Subdomain id to set for inside/outside the bounding box"); params.addRequiredParam<std::vector<BoundaryName>>( "boundary_id_old", "Boundary id on specified block within the bounding box to select"); params.addRequiredParam<boundary_id_type>( "boundary_id_new", "Boundary id on specified block within the bounding box to assign"); params.addParam<bool>("boundary_id_overlap", false, "Set to true if boundaries need to overlap on sideset to be detected."); params.addParam<MooseEnum>( "location", location, "Control of where the subdomain id is to be set"); return params; } AddSideSetsFromBoundingBox::AddSideSetsFromBoundingBox(const InputParameters & parameters) : MeshModifier(parameters), _location(parameters.get<MooseEnum>("location")), _block_id(parameters.get<SubdomainID>("block_id")), _boundary_id_old(parameters.get<std::vector<BoundaryName>>("boundary_id_old")), _boundary_id_new(parameters.get<boundary_id_type>("boundary_id_new")), _bounding_box(parameters.get<RealVectorValue>("bottom_left"), parameters.get<RealVectorValue>("top_right")), _boundary_id_overlap(parameters.get<bool>("boundary_id_overlap")) { } void AddSideSetsFromBoundingBox::modify() { // this modifier is not designed for working with distributed mesh _mesh_ptr->errorIfDistributedMesh("BreakBoundaryOnSubdomain"); // Check that we have access to the mesh if (!_mesh_ptr) mooseError("_mesh_ptr must be initialized before calling SubdomainBoundingBox::modify()"); // Reference the the libMesh::MeshBase MeshBase & mesh = _mesh_ptr->getMesh(); // Get a reference to our BoundaryInfo object for later use BoundaryInfo & boundary_info = mesh.get_boundary_info(); bool found_element = false; bool found_side_sets = false; if (!_boundary_id_overlap) { // Loop over the elements for (const auto & elem : mesh.active_element_ptr_range()) { // boolean if element centroid is in bounding box bool contains = _bounding_box.contains_point(elem->centroid()); // check if active elements are found in the bounding box if (contains) { found_element = true; // loop over sides of elements within bounding box for (unsigned int side = 0; side < elem->n_sides(); side++) // loop over provided boundary vector to check all side sets for all boundary ids for (unsigned int boundary_id_number = 0; boundary_id_number < _boundary_id_old.size(); boundary_id_number++) // check if side has same boundary id that you are looking for if (boundary_info.has_boundary_id( elem, side, boundary_info.get_id_by_name(_boundary_id_old[boundary_id_number]))) { // assign new boundary value to boundary which meets meshmodifier criteria boundary_info.add_side(elem, side, _boundary_id_new); found_side_sets = true; } } } if (!found_element) mooseError("No elements found within the bounding box"); if (!found_side_sets) mooseError("No side sets found on active elements within the bounding box"); } else if (_boundary_id_overlap) { if (_boundary_id_old.size() < 2) mooseError("boundary_id_old out of bounds: ", _boundary_id_old.size(), " Must be 2 boundary inputs or more."); bool found_node = false; const bool inside = (_location == "INSIDE"); // Loop over the elements and assign node set id to nodes within the bounding box for (auto node = mesh.active_nodes_begin(); node != mesh.active_nodes_end(); ++node) { // check if nodes are inside of bounding box if (_bounding_box.contains_point(**node) == inside) { // read out boundary ids for nodes std::vector<short int> boundary_id_list = boundary_info.boundary_ids(*node); std::vector<boundary_id_type> boundary_id_old_list = _mesh_ptr->getBoundaryIDs(_boundary_id_old); // sort boundary ids on node and sort boundary ids provided in input file std::sort(boundary_id_list.begin(), boundary_id_list.end()); std::sort(boundary_id_old_list.begin(), boundary_id_old_list.end()); // check if input boundary ids are all contained in the node // if true, write new boundary id on respective node if (std::includes(boundary_id_list.begin(), boundary_id_list.end(), boundary_id_old_list.begin(), boundary_id_old_list.end())) { boundary_info.add_node(*node, _boundary_id_new); found_node = true; } } } if (!found_node) mooseError("No nodes found within the bounding box"); } } <commit_msg>Use boundary_id_type instead of 'short int'.<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "AddSideSetsFromBoundingBox.h" #include "Conversion.h" #include "MooseMesh.h" #include "MooseTypes.h" registerMooseObject("MooseApp", AddSideSetsFromBoundingBox); template <> InputParameters validParams<AddSideSetsFromBoundingBox>() { InputParameters params = validParams<MeshModifier>(); params.addClassDescription("Find sidesets with given boundary ids in bounding box and add new " "boundary id. This can be done by finding all required boundary " "and adding the new boundary id to those sidesets. Alternatively, " "a number of boundary ids can be provided and all nodes within the " "bounding box that have all the required boundary ids will have a new" "boundary id added."); MooseEnum location("INSIDE OUTSIDE", "INSIDE"); params.addRequiredParam<RealVectorValue>( "bottom_left", "The bottom left point (in x,y,z with spaces in-between)."); params.addRequiredParam<RealVectorValue>( "top_right", "The bottom left point (in x,y,z with spaces in-between)."); params.addRequiredParam<SubdomainID>("block_id", "Subdomain id to set for inside/outside the bounding box"); params.addRequiredParam<std::vector<BoundaryName>>( "boundary_id_old", "Boundary id on specified block within the bounding box to select"); params.addRequiredParam<boundary_id_type>( "boundary_id_new", "Boundary id on specified block within the bounding box to assign"); params.addParam<bool>("boundary_id_overlap", false, "Set to true if boundaries need to overlap on sideset to be detected."); params.addParam<MooseEnum>( "location", location, "Control of where the subdomain id is to be set"); return params; } AddSideSetsFromBoundingBox::AddSideSetsFromBoundingBox(const InputParameters & parameters) : MeshModifier(parameters), _location(parameters.get<MooseEnum>("location")), _block_id(parameters.get<SubdomainID>("block_id")), _boundary_id_old(parameters.get<std::vector<BoundaryName>>("boundary_id_old")), _boundary_id_new(parameters.get<boundary_id_type>("boundary_id_new")), _bounding_box(parameters.get<RealVectorValue>("bottom_left"), parameters.get<RealVectorValue>("top_right")), _boundary_id_overlap(parameters.get<bool>("boundary_id_overlap")) { } void AddSideSetsFromBoundingBox::modify() { // this modifier is not designed for working with distributed mesh _mesh_ptr->errorIfDistributedMesh("BreakBoundaryOnSubdomain"); // Check that we have access to the mesh if (!_mesh_ptr) mooseError("_mesh_ptr must be initialized before calling SubdomainBoundingBox::modify()"); // Reference the the libMesh::MeshBase MeshBase & mesh = _mesh_ptr->getMesh(); // Get a reference to our BoundaryInfo object for later use BoundaryInfo & boundary_info = mesh.get_boundary_info(); bool found_element = false; bool found_side_sets = false; if (!_boundary_id_overlap) { // Loop over the elements for (const auto & elem : mesh.active_element_ptr_range()) { // boolean if element centroid is in bounding box bool contains = _bounding_box.contains_point(elem->centroid()); // check if active elements are found in the bounding box if (contains) { found_element = true; // loop over sides of elements within bounding box for (unsigned int side = 0; side < elem->n_sides(); side++) // loop over provided boundary vector to check all side sets for all boundary ids for (unsigned int boundary_id_number = 0; boundary_id_number < _boundary_id_old.size(); boundary_id_number++) // check if side has same boundary id that you are looking for if (boundary_info.has_boundary_id( elem, side, boundary_info.get_id_by_name(_boundary_id_old[boundary_id_number]))) { // assign new boundary value to boundary which meets meshmodifier criteria boundary_info.add_side(elem, side, _boundary_id_new); found_side_sets = true; } } } if (!found_element) mooseError("No elements found within the bounding box"); if (!found_side_sets) mooseError("No side sets found on active elements within the bounding box"); } else if (_boundary_id_overlap) { if (_boundary_id_old.size() < 2) mooseError("boundary_id_old out of bounds: ", _boundary_id_old.size(), " Must be 2 boundary inputs or more."); bool found_node = false; const bool inside = (_location == "INSIDE"); // Loop over the elements and assign node set id to nodes within the bounding box for (auto node = mesh.active_nodes_begin(); node != mesh.active_nodes_end(); ++node) { // check if nodes are inside of bounding box if (_bounding_box.contains_point(**node) == inside) { // read out boundary ids for nodes std::vector<boundary_id_type> boundary_id_list = boundary_info.boundary_ids(*node); std::vector<boundary_id_type> boundary_id_old_list = _mesh_ptr->getBoundaryIDs(_boundary_id_old); // sort boundary ids on node and sort boundary ids provided in input file std::sort(boundary_id_list.begin(), boundary_id_list.end()); std::sort(boundary_id_old_list.begin(), boundary_id_old_list.end()); // check if input boundary ids are all contained in the node // if true, write new boundary id on respective node if (std::includes(boundary_id_list.begin(), boundary_id_list.end(), boundary_id_old_list.begin(), boundary_id_old_list.end())) { boundary_info.add_node(*node, _boundary_id_new); found_node = true; } } } if (!found_node) mooseError("No nodes found within the bounding box"); } } <|endoftext|>
<commit_before>/** * * Graph * * Undirected, weighted graph * https://github.com/kdzlvaids/algorithm_and_practice-pknu-2016 * */ #ifndef ALGORITHM_GRAPH_HPP_ #define ALGORITHM_GRAPH_HPP_ 1 /** Includes */ #include <cstddef> /** size_t definition */ #include <vector> /** Containers */ #include <forward_list> /** Containers */ namespace algorithm { /** Undirected, weighted graph class \note Vertex deletion is not implemented \note Edge deletion is not implemented \note Cannot use double as WeightType */ template< class ValueType, /**< Vertex value type; operator== should be defined */ class WeightType = unsigned int, /**< Weight type */ WeightType WeightDefaultValue = 0 /**< Default value of weight */ > class Graph { public: typedef size_t SizeType; typedef unsigned int KeyType; /**< Key type, used to access an array */ /** Test if two keys are equal \return Return true if two keys are equal; otherwise return false \param[in] key_first First key to compare \param[in] key_second Second key to compare */ bool IsKeyEqual(const KeyType & key_first, const KeyType & key_second) const { return key_first == key_second; } /** Vertex class Each vertex has an array for its edges as a member. */ struct VertexNode { const KeyType key; /**< Key of vertex; same with index in graph_ */ ValueType value; /**< Value of vertex */ std::forward_list< std::pair<const KeyType, WeightType> > edges; /**< Edges of vertex \param KeyType key_dest \param WeightType weight */ SizeType edges_size; /**< Count of edges; forward_list not support size() function */ /** Constructor */ VertexNode(const KeyType & key, const ValueType & value) : key(key) , value(value) , edges_size(0) { } /** Test if two values are equal \return Return true if two values are equal; otherwise return false \param[in] value Value to compare */ bool IsValueEqual(const ValueType & value) const { return this->value == value; } }; private: std::vector<VertexNode> graph_; /**< Graph */ public: /** Test whether there is an edge from the vertices src to dest \return Return true if the edge exists; otherwise return false \param[in] key_src Key of source (src) \param[in] key_dest Key of destination (dest) */ bool Adjacent(const KeyType & key_src, const KeyType & key_dest) { for(auto & edge : graph_.at(key_src)->edges) { if(IsKeyEqual(edge.first, key_dest) == true) /** Found */ return true; } return false; /** Not found */ } /** Add a vertex, if a graph not have the vertex with specified value already \return Return the key of vertex if added successfully; otherwise return -1 \param[in] value_of_vertex Value of vertex */ KeyType AddVertex(const ValueType & value_of_vertex) { KeyType key_of_vertex = GetVertexKey(value_of_vertex); if(key_of_vertex == GetVertexCount()) /** Not found */ graph_.push_back(VertexNode(key_of_vertex, value_of_vertex)); return key_of_vertex; } /** Add an edge to connect two vertices \param[in] key_src Key of source (src) \param[in] key_dest Key of destination (dest) \param[in] weight Weight of the edge */ void AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue) { graph_.at(key_src).edges.push_front( std::make_pair<const KeyType, WeightType> (KeyType(key_dest), WeightType(weight)) ); ++graph_.at(key_src).edges_size; } /** Get a key of the vertex with specified value from a graph If failed to add, return the size of graph which is an invalid key (maximum key + 1). \return Return the key of vertex if added successfully; otherwise return the size of graph \param[in] value_of_vertex Value of vertex */ KeyType GetVertexKey(const ValueType & value_of_vertex) { for(const VertexNode & vertex : graph_) { if(vertex.IsValueEqual(value_of_vertex) == true) return vertex.key; } return GetVertexCount(); } /** Get a value of the vertex with specified key from a graph \return Return the value \param[in] key_of_vertex Key of vertex */ inline ValueType GetVertexValue(const KeyType & key_of_vertex) const { return graph_.at(key_of_vertex).value; } /** Set a value of the vertex with specified key from a graph \param[in] key_of_vertex Key of vertex \param[in] value_of_vertex Value of vertex */ inline void SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex) { graph_.at(key_of_vertex).value = value_of_vertex; } /** Get a count of vertices \return Count of vertices */ inline SizeType GetVertexCount(void) const { return graph_.size(); } /** Get a count of edges \return Count of edges \param[in] key_of_vertex Key of vertex */ inline SizeType GetVertexEdgeCount(const KeyType & key_of_vertex) const { return graph_.at(key_of_vertex).edges_size; } }; } /** ns: algorithm */ #endif /** ! ALGORITHM_GRAPH_HPP_ */ <commit_msg>Change the container for edges to Map<commit_after>/** * * Graph * * Undirected, weighted graph * https://github.com/kdzlvaids/algorithm_and_practice-pknu-2016 * */ #ifndef ALGORITHM_GRAPH_HPP_ #define ALGORITHM_GRAPH_HPP_ 1 /** Includes */ #include <cstddef> /** size_t definition */ #include <vector> /** Containers */ #include <map> /** Containers */ namespace algorithm { /** Undirected, weighted graph class \note Vertex deletion is not implemented \note Edge deletion is not implemented \note Cannot use double as WeightType */ template< class ValueType, /**< Vertex value type; operator== should be defined */ class WeightType = unsigned int, /**< Weight type */ WeightType WeightDefaultValue = 0 /**< Default value of weight */ > class Graph { public: typedef size_t SizeType; typedef std::map<const KeyType, WeightType> EdgeType; /**< Edges of vertex \param KeyType key_dest \param WeightType weight */ /** Test if two keys are equal \return Return true if two keys are equal; otherwise return false \param[in] key_first First key to compare \param[in] key_second Second key to compare */ bool IsKeyEqual(const KeyType & key_first, const KeyType & key_second) const { return key_first == key_second; } /** Vertex class Each vertex has an array for its edges as a member. */ struct VertexNode { const KeyType key; /**< Key of vertex; same with index in graph_ */ ValueType value; /**< Value of vertex */ EdgeType edges; //SizeType edges_size; /**< Count of edges; forward_list not support size() function */ /** Constructor */ VertexNode(const KeyType & key, const ValueType & value) : key(key) , value(value) { } /** Test if two values are equal \return Return true if two values are equal; otherwise return false \param[in] value Value to compare */ bool IsValueEqual(const ValueType & value) const { return this->value == value; } }; private: std::vector<VertexNode> graph_; /**< Graph */ public: /** Test whether there is an edge from the vertices src to dest \return Return true if the edge exists; otherwise return false \param[in] key_src Key of source (src) \param[in] key_dest Key of destination (dest) */ bool Adjacent(const KeyType & key_src, const KeyType & key_dest) { for(auto & edge : graph_.at(key_src)->edges) { if(IsKeyEqual(edge.first, key_dest) == true) /** Found */ return true; } return false; /** Not found */ } /** Add a vertex, if a graph not have the vertex with specified value already \return Return the key of vertex if added successfully; otherwise return -1 \param[in] value_of_vertex Value of vertex */ KeyType AddVertex(const ValueType & value_of_vertex) { KeyType key_of_vertex = GetVertexKey(value_of_vertex); if(key_of_vertex == GetVertexCount()) /** Not found */ graph_.push_back(VertexNode(key_of_vertex, value_of_vertex)); return key_of_vertex; } /** Add an edge to connect two vertices \param[in] key_src Key of source (src) \param[in] key_dest Key of destination (dest) \param[in] weight Weight of the edge */ void AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue) { graph_.at(key_src).edges.insert( std::make_pair<const KeyType, WeightType> (KeyType(key_dest), WeightType(weight)) ); } /** Get a key of the vertex with specified value from a graph If failed to add, return the size of graph which is an invalid key (maximum key + 1). \return Return the key of vertex if added successfully; otherwise return the size of graph \param[in] value_of_vertex Value of vertex */ KeyType GetVertexKey(const ValueType & value_of_vertex) { for(const VertexNode & vertex : graph_) { if(vertex.IsValueEqual(value_of_vertex) == true) return vertex.key; } return GetVertexCount(); } /** Get a value of the vertex with specified key from a graph \return Return the value \param[in] key_of_vertex Key of vertex */ inline ValueType GetVertexValue(const KeyType & key_of_vertex) const { return graph_.at(key_of_vertex).value; } /** Set a value of the vertex with specified key from a graph \param[in] key_of_vertex Key of vertex \param[in] value_of_vertex Value of vertex */ inline void SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex) { graph_.at(key_of_vertex).value = value_of_vertex; } /** Get a count of vertices \return Count of vertices */ inline SizeType GetVertexCount(void) const { return graph_.size(); } /** Get a count of edges \return Count of edges \param[in] key_of_vertex Key of vertex */ inline SizeType GetVertexEdgeCount(const KeyType & key_of_vertex) const { return graph_.at(key_of_vertex).edges.size(); } }; } /** ns: algorithm */ #endif /** ! ALGORITHM_GRAPH_HPP_ */ <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "PINSFVRhieChowInterpolator.h" #include "Reconstructions.h" #include "NS.h" #include "Assembly.h" registerMooseObject("NavierStokesApp", PINSFVRhieChowInterpolator); InputParameters PINSFVRhieChowInterpolator::validParams() { auto params = INSFVRhieChowInterpolator::validParams(); params.addClassDescription("Performs interpolations and reconstructions of body forces and " "porosity and computes the Rhie-Chow face velocities."); params.addRequiredParam<MooseFunctorName>(NS::porosity, "The porosity"); params.addParam<unsigned short>( "smoothing_layers", 0, "The number of interpolation-reconstruction operations to perform on the porosity"); params.addRelationshipManager( "ElementSideNeighborLayers", Moose::RelationshipManagerType::GEOMETRIC, [](const InputParameters & obj_params, InputParameters & rm_params) { // We need one additional layer for the case that we have an extrapolated boundary face rm_params.set<unsigned short>("layers") = obj_params.get<unsigned short>("smoothing_layers") + 1; rm_params.set<bool>("use_displaced_mesh") = obj_params.get<bool>("use_displaced_mesh"); }); return params; } PINSFVRhieChowInterpolator::PINSFVRhieChowInterpolator(const InputParameters & params) : INSFVRhieChowInterpolator(params), _eps(const_cast<Moose::Functor<ADReal> &>(getFunctor<ADReal>(NS::porosity))), _epss(libMesh::n_threads(), nullptr), _smoothing_layers(getParam<unsigned short>("smoothing_layers")), _smoothed_eps(_moose_mesh) { if (_smoothing_layers && _eps.wrapsType<MooseVariableBase>()) paramError( NS::porosity, "If we are reconstructing porosity, then the input porosity to this user object cannot " "be a Moose variable. There are issues with reconstructing Moose variables: 1) initial " "conditions are run after user objects initial setup 2) reconstructing from a variable " "requires ghosting the solution vectors 3) it's difficult to restrict the face " "informations we evaluate interpolations and reconstructions on such that we never query " "an algebraically remote element due to things like two-term extrapolated boundary faces " "which trigger gradient evaluations which trigger neighbor element evaluation"); const auto porosity_name = deduceFunctorName(NS::porosity); for (const auto tid : make_range(libMesh::n_threads())) _epss[tid] = &UserObject::_subproblem.getFunctor<ADReal>(porosity_name, tid, name()); } void PINSFVRhieChowInterpolator::meshChanged() { insfvSetup(); pinsfvSetup(); } void PINSFVRhieChowInterpolator::residualSetup() { if (!_initial_setup_done) { insfvSetup(); pinsfvSetup(); } _initial_setup_done = true; } void PINSFVRhieChowInterpolator::pinsfvSetup() { if (!_smoothing_layers) return; const auto & all_fi = _moose_mesh.allFaceInfo(); _geometric_fi.reserve(all_fi.size()); for (const auto & fi : all_fi) if (isFaceGeometricallyRelevant(fi)) _geometric_fi.push_back(&fi); _geometric_fi.shrink_to_fit(); const auto saved_do_derivatives = ADReal::do_derivatives; ADReal::do_derivatives = true; Moose::FV::interpolateReconstruct( _smoothed_eps, _eps, _smoothing_layers, false, _geometric_fi, *this); ADReal::do_derivatives = saved_do_derivatives; _eps.assign(_smoothed_eps); const auto porosity_name = deduceFunctorName(NS::porosity); for (const auto tid : make_range((unsigned int)(1), libMesh::n_threads())) { auto & other_epss = const_cast<Moose::Functor<ADReal> &>( UserObject::_subproblem.getFunctor<ADReal>(porosity_name, tid, name())); other_epss.assign(_smoothed_eps); } } <commit_msg>Try decreasing ghosting for porosity<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "PINSFVRhieChowInterpolator.h" #include "Reconstructions.h" #include "NS.h" #include "Assembly.h" registerMooseObject("NavierStokesApp", PINSFVRhieChowInterpolator); InputParameters PINSFVRhieChowInterpolator::validParams() { auto params = INSFVRhieChowInterpolator::validParams(); params.addClassDescription("Performs interpolations and reconstructions of body forces and " "porosity and computes the Rhie-Chow face velocities."); params.addRequiredParam<MooseFunctorName>(NS::porosity, "The porosity"); params.addParam<unsigned short>( "smoothing_layers", 0, "The number of interpolation-reconstruction operations to perform on the porosity"); params.addRelationshipManager( "ElementSideNeighborLayers", Moose::RelationshipManagerType::GEOMETRIC, [](const InputParameters & obj_params, InputParameters & rm_params) { rm_params.set<unsigned short>("layers") = obj_params.get<unsigned short>("smoothing_layers"); rm_params.set<bool>("use_displaced_mesh") = obj_params.get<bool>("use_displaced_mesh"); }); return params; } PINSFVRhieChowInterpolator::PINSFVRhieChowInterpolator(const InputParameters & params) : INSFVRhieChowInterpolator(params), _eps(const_cast<Moose::Functor<ADReal> &>(getFunctor<ADReal>(NS::porosity))), _epss(libMesh::n_threads(), nullptr), _smoothing_layers(getParam<unsigned short>("smoothing_layers")), _smoothed_eps(_moose_mesh) { if (_smoothing_layers && _eps.wrapsType<MooseVariableBase>()) paramError( NS::porosity, "If we are reconstructing porosity, then the input porosity to this user object cannot " "be a Moose variable. There are issues with reconstructing Moose variables: 1) initial " "conditions are run after user objects initial setup 2) reconstructing from a variable " "requires ghosting the solution vectors 3) it's difficult to restrict the face " "informations we evaluate interpolations and reconstructions on such that we never query " "an algebraically remote element due to things like two-term extrapolated boundary faces " "which trigger gradient evaluations which trigger neighbor element evaluation"); const auto porosity_name = deduceFunctorName(NS::porosity); for (const auto tid : make_range(libMesh::n_threads())) _epss[tid] = &UserObject::_subproblem.getFunctor<ADReal>(porosity_name, tid, name()); } void PINSFVRhieChowInterpolator::meshChanged() { insfvSetup(); pinsfvSetup(); } void PINSFVRhieChowInterpolator::residualSetup() { if (!_initial_setup_done) { insfvSetup(); pinsfvSetup(); } _initial_setup_done = true; } void PINSFVRhieChowInterpolator::pinsfvSetup() { if (!_smoothing_layers) return; const auto & all_fi = _moose_mesh.allFaceInfo(); _geometric_fi.reserve(all_fi.size()); for (const auto & fi : all_fi) if (isFaceGeometricallyRelevant(fi)) _geometric_fi.push_back(&fi); _geometric_fi.shrink_to_fit(); const auto saved_do_derivatives = ADReal::do_derivatives; ADReal::do_derivatives = true; Moose::FV::interpolateReconstruct( _smoothed_eps, _eps, _smoothing_layers, false, _geometric_fi, *this); ADReal::do_derivatives = saved_do_derivatives; _eps.assign(_smoothed_eps); const auto porosity_name = deduceFunctorName(NS::porosity); for (const auto tid : make_range((unsigned int)(1), libMesh::n_threads())) { auto & other_epss = const_cast<Moose::Functor<ADReal> &>( UserObject::_subproblem.getFunctor<ADReal>(porosity_name, tid, name())); other_epss.assign(_smoothed_eps); } } <|endoftext|>
<commit_before>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "DerivativeFunctionMaterialBase.h" template<> InputParameters validParams<DerivativeFunctionMaterialBase>() { InputParameters params = validParams<FunctionMaterialBase>(); params.addClassDescription("Material to provide a function (such as a free energy) and its derivatives w.r.t. the coupled variables"); params.addParam<bool>("third_derivatives", true, "Calculate third derivatoves of the free energy"); return params; } DerivativeFunctionMaterialBase::DerivativeFunctionMaterialBase(const std::string & name, InputParameters parameters) : FunctionMaterialBase(name, parameters), _third_derivatives(getParam<bool>("third_derivatives")) { // loop counters unsigned int i, j, k; // reserve space for material properties and explicitly initialize to NULL _prop_dF.resize(_nargs, NULL); _prop_d2F.resize(_nargs); _prop_d3F.resize(_nargs); for (i = 0; i < _nargs; ++i) { _prop_d2F[i].resize(_nargs, NULL); if (_third_derivatives) { _prop_d3F[i].resize(_nargs); for (j = 0; j < _nargs; ++j) _prop_d3F[i][j].resize(_nargs, NULL); } } // initialize derivatives for (i = 0; i < _nargs; ++i) { // skip all derivatives w.r.t. auxiliary variables if (_arg_numbers[i] >= _number_of_nl_variables) continue; // first derivatives _prop_dF[i] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i]); // second derivatives for (j = i; j < _nargs; ++j) { // skip all derivatives w.r.t. auxiliary variables if (_arg_numbers[j] >= _number_of_nl_variables) continue; _prop_d2F[i][j] = _prop_d2F[j][i] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i], _arg_names[j]); // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) { // skip all derivatives w.r.t. auxiliary variables if (_arg_numbers[k] >= _number_of_nl_variables) continue; // filling all permutations does not cost us much and simplifies access // (no need to check i<=j<=k) _prop_d3F[i][j][k] = _prop_d3F[k][i][j] = _prop_d3F[j][k][i] = _prop_d3F[k][j][i] = _prop_d3F[j][i][k] = _prop_d3F[i][k][j] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]); } } } } } void DerivativeFunctionMaterialBase::initialSetup() { // set the _prop_* pointers of all material properties that are not beeing used back to NULL unsigned int i, j, k; bool needs_third_derivatives = false; if (!_fe_problem.isMatPropRequested(_F_name)) _prop_F = NULL; for (i = 0; i < _nargs; ++i) { if (!_fe_problem.isMatPropRequested(propertyNameFirst(_F_name, _arg_names[i]))) _prop_dF[i] = NULL; // second derivatives for (j = i; j < _nargs; ++j) { if (!_fe_problem.isMatPropRequested(propertyNameSecond(_F_name, _arg_names[i], _arg_names[j]))) _prop_d2F[i][j] = _prop_d2F[j][i] = NULL; // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) { if (!_fe_problem.isMatPropRequested(propertyNameThird(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]))) _prop_d3F[i][j][k] = _prop_d3F[k][i][j] = _prop_d3F[j][k][i] = _prop_d3F[k][j][i] = _prop_d3F[j][i][k] = _prop_d3F[i][k][j] = NULL; else needs_third_derivatives = true; } if (!needs_third_derivatives) mooseWarning("This simulation does not actually need the third derivatives of DerivativeFunctionMaterialBase " + _name); } } } } void DerivativeFunctionMaterialBase::computeProperties() { unsigned int i, j, k; for (_qp = 0; _qp < _qrule->n_points(); _qp++) { // set function value if (_prop_F) (*_prop_F)[_qp] = computeF(); for (i = 0; i < _nargs; ++i) { // set first derivatives if (_prop_dF[i]) (*_prop_dF[i])[_qp] = computeDF(_arg_numbers[i]); // second derivatives for (j = i; j < _nargs; ++j) { if (_prop_d2F[i][j]) (*_prop_d2F[i][j])[_qp] = computeD2F(_arg_numbers[i], _arg_numbers[j]); // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) if (_prop_d3F[i][j][k]) (*_prop_d3F[i][j][k])[_qp] = computeD3F(_arg_numbers[i], _arg_numbers[j], _arg_numbers[k]); } } } } } <commit_msg>Deprecate third_derivatives (#4725)<commit_after>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "DerivativeFunctionMaterialBase.h" template<> InputParameters validParams<DerivativeFunctionMaterialBase>() { InputParameters params = validParams<FunctionMaterialBase>(); params.addClassDescription("Material to provide a function (such as a free energy) and its derivatives w.r.t. the coupled variables"); params.addDeprecatedParam<bool>("third_derivatives", "Flag to indicate if third derivatives are needed", "Use derivative_order instead."); params.addRangeCheckedParam<unsigned int>("derivative_order", 3, "derivative_order>=2 & derivative_order<=3", "Maximum order of derivatives taken (2 or 3)"); return params; } DerivativeFunctionMaterialBase::DerivativeFunctionMaterialBase(const std::string & name, InputParameters parameters) : FunctionMaterialBase(name, parameters), _third_derivatives(isParamValid("third_derivatives") ? getParam<bool>("third_derivatives") : (getParam<unsigned int>("derivative_order")==3)) { // loop counters unsigned int i, j, k; // reserve space for material properties and explicitly initialize to NULL _prop_dF.resize(_nargs, NULL); _prop_d2F.resize(_nargs); _prop_d3F.resize(_nargs); for (i = 0; i < _nargs; ++i) { _prop_d2F[i].resize(_nargs, NULL); if (_third_derivatives) { _prop_d3F[i].resize(_nargs); for (j = 0; j < _nargs; ++j) _prop_d3F[i][j].resize(_nargs, NULL); } } // initialize derivatives for (i = 0; i < _nargs; ++i) { // skip all derivatives w.r.t. auxiliary variables if (_arg_numbers[i] >= _number_of_nl_variables) continue; // first derivatives _prop_dF[i] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i]); // second derivatives for (j = i; j < _nargs; ++j) { // skip all derivatives w.r.t. auxiliary variables if (_arg_numbers[j] >= _number_of_nl_variables) continue; _prop_d2F[i][j] = _prop_d2F[j][i] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i], _arg_names[j]); // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) { // skip all derivatives w.r.t. auxiliary variables if (_arg_numbers[k] >= _number_of_nl_variables) continue; // filling all permutations does not cost us much and simplifies access // (no need to check i<=j<=k) _prop_d3F[i][j][k] = _prop_d3F[k][i][j] = _prop_d3F[j][k][i] = _prop_d3F[k][j][i] = _prop_d3F[j][i][k] = _prop_d3F[i][k][j] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]); } } } } } void DerivativeFunctionMaterialBase::initialSetup() { // set the _prop_* pointers of all material properties that are not beeing used back to NULL unsigned int i, j, k; bool needs_third_derivatives = false; if (!_fe_problem.isMatPropRequested(_F_name)) _prop_F = NULL; for (i = 0; i < _nargs; ++i) { if (!_fe_problem.isMatPropRequested(propertyNameFirst(_F_name, _arg_names[i]))) _prop_dF[i] = NULL; // second derivatives for (j = i; j < _nargs; ++j) { if (!_fe_problem.isMatPropRequested(propertyNameSecond(_F_name, _arg_names[i], _arg_names[j]))) _prop_d2F[i][j] = _prop_d2F[j][i] = NULL; // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) { if (!_fe_problem.isMatPropRequested(propertyNameThird(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]))) _prop_d3F[i][j][k] = _prop_d3F[k][i][j] = _prop_d3F[j][k][i] = _prop_d3F[k][j][i] = _prop_d3F[j][i][k] = _prop_d3F[i][k][j] = NULL; else needs_third_derivatives = true; } if (!needs_third_derivatives) mooseWarning("This simulation does not actually need the third derivatives of DerivativeFunctionMaterialBase " + _name); } } } } void DerivativeFunctionMaterialBase::computeProperties() { unsigned int i, j, k; for (_qp = 0; _qp < _qrule->n_points(); _qp++) { // set function value if (_prop_F) (*_prop_F)[_qp] = computeF(); for (i = 0; i < _nargs; ++i) { // set first derivatives if (_prop_dF[i]) (*_prop_dF[i])[_qp] = computeDF(_arg_numbers[i]); // second derivatives for (j = i; j < _nargs; ++j) { if (_prop_d2F[i][j]) (*_prop_d2F[i][j])[_qp] = computeD2F(_arg_numbers[i], _arg_numbers[j]); // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) if (_prop_d3F[i][j][k]) (*_prop_d3F[i][j][k])[_qp] = computeD3F(_arg_numbers[i], _arg_numbers[j], _arg_numbers[k]); } } } } } <|endoftext|>
<commit_before><commit_msg>delete comments<commit_after><|endoftext|>
<commit_before>/** Copyright 2015 Joachim Wolff Master Thesis Tutors: Milad Miladi, Fabrizio Costa Winter semester 2015/2016 Chair of Bioinformatics Department of Computer Science Faculty of Engineering Albert-Ludwig-University Freiburg im Breisgau **/ #include <Python.h> #include "../minHash.h" #include "../parsePythonToCpp.h" static neighborhood* neighborhoodComputation(size_t pMinHashAddress, PyObject* pInstancesListObj,PyObject* pFeaturesListObj,PyObject* pDataListObj, size_t pMaxNumberOfInstances, size_t pMaxNumberOfFeatures, size_t pNneighbors, int pFast, int pSimilarity) { // std::cout << "20" << std::endl; SparseMatrixFloat* originalDataMatrix = NULL; if (pMaxNumberOfInstances != 0) { originalDataMatrix = parseRawData(pInstancesListObj, pFeaturesListObj, pDataListObj, pMaxNumberOfInstances, pMaxNumberOfFeatures); } MinHash* minHash = reinterpret_cast<MinHash* >(pMinHashAddress); // compute the k-nearest neighbors return minHash->kneighbors(originalDataMatrix, pNneighbors, pFast, pSimilarity); } static neighborhood* fitNeighborhoodComputation(size_t pMinHashAddress, PyObject* pInstancesListObj,PyObject* pFeaturesListObj,PyObject* pDataListObj, size_t pMaxNumberOfInstances, size_t pMaxNumberOfFeatures, size_t pNneighbors, int pFast, int pSimilarity) { SparseMatrixFloat* originalDataMatrix = parseRawData(pInstancesListObj, pFeaturesListObj, pDataListObj, pMaxNumberOfInstances, pMaxNumberOfFeatures); // get pointer to the minhash object MinHash* minHash = reinterpret_cast<MinHash* >(pMinHashAddress); minHash->set_mOriginalData(originalDataMatrix); minHash->fit(originalDataMatrix); SparseMatrixFloat* emptyMatrix = NULL; neighborhood* neighborhood_ = minHash->kneighbors(emptyMatrix, pNneighbors, pFast, pSimilarity); // delete emptyMatrix; return neighborhood_; } static PyObject* createObject(PyObject* self, PyObject* args) { size_t numberOfHashFunctions, blockSize, numberOfCores, chunkSize, nNeighbors, minimalBlocksInCommon, maxBinSize, maximalNumberOfHashCollisions, excessFactor, bloomierFilter; int fast, similarity; if (!PyArg_ParseTuple(args, "kkkkkkkkkiik", &numberOfHashFunctions, &blockSize, &numberOfCores, &chunkSize, &nNeighbors, &minimalBlocksInCommon, &maxBinSize, &maximalNumberOfHashCollisions, &excessFactor, &fast, &similarity, &bloomierFilter)) return NULL; MinHash* minHash = new MinHash (numberOfHashFunctions, blockSize, numberOfCores, chunkSize, maxBinSize, nNeighbors, minimalBlocksInCommon, excessFactor, maximalNumberOfHashCollisions, fast, similarity, bloomierFilter); size_t adressMinHashObject = reinterpret_cast<size_t>(minHash); PyObject* pointerToInverseIndex = Py_BuildValue("k", adressMinHashObject); return pointerToInverseIndex; } static PyObject* deleteObject(PyObject* self, PyObject* args) { size_t addressMinHashObject; if (!PyArg_ParseTuple(args, "k", &addressMinHashObject)) return Py_BuildValue("i", 1);; MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); delete minHash; return Py_BuildValue("i", 0); } static PyObject* fit(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkk", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &addressMinHashObject)) return NULL; // std::cout << "86" << std::endl; // parse from python list to a c++ map<size_t, vector<size_t> > // where key == instance id and vector<size_t> == non null feature ids SparseMatrixFloat* originalDataMatrix = parseRawData(instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures); // std::cout << "91" << std::endl; // get pointer to the minhash object // std::cout << "94" << std::endl; MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); minHash->set_mOriginalData(originalDataMatrix); // std::cout << "98" << std::endl; minHash->fit(originalDataMatrix); // std::cout << "101" << std::endl; addressMinHashObject = reinterpret_cast<size_t>(minHash); PyObject * pointerToInverseIndex = Py_BuildValue("k", addressMinHashObject); return pointerToInverseIndex; } static PyObject* partialFit(PyObject* self, PyObject* args) { return fit(self, args); } static PyObject* kneighbors(PyObject* self, PyObject* args) { size_t addressMinHashObject, nNeighbors, maxNumberOfInstances, maxNumberOfFeatures, returnDistance; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkiik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &nNeighbors, &returnDistance, &fast, &similarity, &addressMinHashObject)) return NULL; // std::cout << "125" << std::endl; // compute the k-nearest neighbors neighborhood* neighborhood_ = neighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, fast, similarity); // std::cout << "130" << std::endl; size_t cutFirstValue = 0; if (PyList_Size(instancesListObj) == 0) { cutFirstValue = 1; } if (nNeighbors == 0) { MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); nNeighbors = minHash->getNneighbors(); } // std::cout << "140" << std::endl; return bringNeighborhoodInShape(neighborhood_, nNeighbors, cutFirstValue, returnDistance); } static PyObject* kneighborsGraph(PyObject* self, PyObject* args) { size_t addressMinHashObject, nNeighbors, maxNumberOfInstances, maxNumberOfFeatures, returnDistance, symmetric; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkikik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &nNeighbors, &returnDistance, &fast, &symmetric, &similarity, &addressMinHashObject)) return NULL; // compute the k-nearest neighbors neighborhood* neighborhood_ = neighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, fast, similarity); if (nNeighbors == 0) { MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); nNeighbors = minHash->getNneighbors(); } return buildGraph(neighborhood_, nNeighbors, returnDistance, symmetric); } static PyObject* radiusNeighbors(PyObject* self, PyObject* args) { size_t addressMinHashObject, radius, maxNumberOfInstances, maxNumberOfFeatures, returnDistance, similarity; int fast; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkiik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &radius, &returnDistance, &fast,&similarity, &addressMinHashObject)) return NULL; // compute the k-nearest neighbors neighborhood* neighborhood_ = neighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, MAX_VALUE, fast, similarity); size_t cutFirstValue = 0; if (PyList_Size(instancesListObj) == 0) { cutFirstValue = 1; } return radiusNeighborhood(neighborhood_, radius, cutFirstValue, returnDistance); } static PyObject* radiusNeighborsGraph(PyObject* self, PyObject* args) { size_t addressMinHashObject, radius, maxNumberOfInstances, maxNumberOfFeatures, returnDistance, symmetric; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkikik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &radius, &returnDistance, &fast, &symmetric, &similarity, &addressMinHashObject)) return NULL; // compute the k-nearest neighbors neighborhood* neighborhood_ = neighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, MAX_VALUE, fast, similarity); return radiusNeighborhoodGraph(neighborhood_, radius, returnDistance, symmetric); } static PyObject* fitKneighbors(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, returnDistance; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkiik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &nNeighbors, &returnDistance, &fast, &similarity, &addressMinHashObject)) return NULL; neighborhood* neighborhood_ = fitNeighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, fast, similarity); size_t cutFirstValue = 1; if (nNeighbors == 0) { MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); nNeighbors = minHash->getNneighbors(); } return bringNeighborhoodInShape(neighborhood_, nNeighbors, cutFirstValue, returnDistance); } static PyObject* fitKneighborsGraph(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, returnDistance, symmetric; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkikik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &nNeighbors, &returnDistance, &fast, &symmetric, &similarity, &addressMinHashObject)) return NULL; neighborhood* neighborhood_ = fitNeighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, fast, similarity); if (nNeighbors == 0) { MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); nNeighbors = minHash->getNneighbors(); } return buildGraph(neighborhood_, nNeighbors, returnDistance, symmetric); } static PyObject* fitRadiusNeighbors(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures, radius, returnDistance; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkiik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &radius, &returnDistance, &fast, &similarity, &addressMinHashObject)) return NULL; neighborhood* neighborhood_ = fitNeighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, MAX_VALUE, fast, similarity); size_t cutFirstValue = 1; return radiusNeighborhood(neighborhood_, radius, cutFirstValue, returnDistance); } static PyObject* fitRadiusNeighborsGraph(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures, radius, returnDistance, symmetric; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkikik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &radius, &returnDistance, &fast, &symmetric, &similarity, &addressMinHashObject)) return NULL; neighborhood* neighborhood_ = fitNeighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, MAX_VALUE, fast, similarity); return radiusNeighborhoodGraph(neighborhood_, radius, returnDistance, symmetric); } // definition of avaible functions for python and which function parsing fucntion in c++ should be called. static PyMethodDef minHashFunctions[] = { {"fit", fit, METH_VARARGS, "Calculate the inverse index for the given instances."}, {"partial_fit", partialFit, METH_VARARGS, "Extend the inverse index with the given instances."}, {"kneighbors", kneighbors, METH_VARARGS, "Calculate k-nearest neighbors."}, {"kneighbors_graph", kneighborsGraph, METH_VARARGS, "Calculate k-nearest neighbors as a graph."}, {"radius_neighbors", radiusNeighbors, METH_VARARGS, "Calculate the neighbors inside a given radius."}, {"radius_neighbors_graph", radiusNeighborsGraph, METH_VARARGS, "Calculate the neighbors inside a given radius as a graph."}, {"fit_kneighbors", fitKneighbors, METH_VARARGS, "Fits and calculates k-nearest neighbors."}, {"fit_kneighbors_graph", fitKneighborsGraph, METH_VARARGS, "Fits and calculates k-nearest neighbors as a graph."}, {"fit_radius_neighbors", fitRadiusNeighbors, METH_VARARGS, "Fits and calculates the neighbors inside a given radius."}, {"fit_radius_neighbors_graph", fitRadiusNeighborsGraph, METH_VARARGS, "Fits and calculates the neighbors inside a given radius as a graph."}, {"create_object", createObject, METH_VARARGS, "Create the c++ object."}, {"delete_object", deleteObject, METH_VARARGS, "Delete the c++ object by calling the destructor."}, {NULL, NULL, 0, NULL} }; // definition of the module for python PyMODINIT_FUNC init_minHash(void) { (void) Py_InitModule("_minHash", minHashFunctions); }<commit_msg>Added debugging lines<commit_after>/** Copyright 2015 Joachim Wolff Master Thesis Tutors: Milad Miladi, Fabrizio Costa Winter semester 2015/2016 Chair of Bioinformatics Department of Computer Science Faculty of Engineering Albert-Ludwig-University Freiburg im Breisgau **/ #include <Python.h> #include "../minHash.h" #include "../parsePythonToCpp.h" static neighborhood* neighborhoodComputation(size_t pMinHashAddress, PyObject* pInstancesListObj,PyObject* pFeaturesListObj,PyObject* pDataListObj, size_t pMaxNumberOfInstances, size_t pMaxNumberOfFeatures, size_t pNneighbors, int pFast, int pSimilarity) { // std::cout << "20" << std::endl; SparseMatrixFloat* originalDataMatrix = NULL; if (pMaxNumberOfInstances != 0) { originalDataMatrix = parseRawData(pInstancesListObj, pFeaturesListObj, pDataListObj, pMaxNumberOfInstances, pMaxNumberOfFeatures); } MinHash* minHash = reinterpret_cast<MinHash* >(pMinHashAddress); // compute the k-nearest neighbors return minHash->kneighbors(originalDataMatrix, pNneighbors, pFast, pSimilarity); } static neighborhood* fitNeighborhoodComputation(size_t pMinHashAddress, PyObject* pInstancesListObj,PyObject* pFeaturesListObj,PyObject* pDataListObj, size_t pMaxNumberOfInstances, size_t pMaxNumberOfFeatures, size_t pNneighbors, int pFast, int pSimilarity) { SparseMatrixFloat* originalDataMatrix = parseRawData(pInstancesListObj, pFeaturesListObj, pDataListObj, pMaxNumberOfInstances, pMaxNumberOfFeatures); // get pointer to the minhash object MinHash* minHash = reinterpret_cast<MinHash* >(pMinHashAddress); minHash->set_mOriginalData(originalDataMatrix); minHash->fit(originalDataMatrix); SparseMatrixFloat* emptyMatrix = NULL; neighborhood* neighborhood_ = minHash->kneighbors(emptyMatrix, pNneighbors, pFast, pSimilarity); // delete emptyMatrix; return neighborhood_; } static PyObject* createObject(PyObject* self, PyObject* args) { std::cout << "create" << std::endl; size_t numberOfHashFunctions, blockSize, numberOfCores, chunkSize, nNeighbors, minimalBlocksInCommon, maxBinSize, maximalNumberOfHashCollisions, excessFactor, bloomierFilter; int fast, similarity; if (!PyArg_ParseTuple(args, "kkkkkkkkkiik", &numberOfHashFunctions, &blockSize, &numberOfCores, &chunkSize, &nNeighbors, &minimalBlocksInCommon, &maxBinSize, &maximalNumberOfHashCollisions, &excessFactor, &fast, &similarity, &bloomierFilter)) return NULL; MinHash* minHash = new MinHash (numberOfHashFunctions, blockSize, numberOfCores, chunkSize, maxBinSize, nNeighbors, minimalBlocksInCommon, excessFactor, maximalNumberOfHashCollisions, fast, similarity, bloomierFilter); size_t adressMinHashObject = reinterpret_cast<size_t>(minHash); PyObject* pointerToInverseIndex = Py_BuildValue("k", adressMinHashObject); return pointerToInverseIndex; } static PyObject* deleteObject(PyObject* self, PyObject* args) { size_t addressMinHashObject; if (!PyArg_ParseTuple(args, "k", &addressMinHashObject)) return Py_BuildValue("i", 1);; MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); delete minHash; return Py_BuildValue("i", 0); } static PyObject* fit(PyObject* self, PyObject* args) { std::cout << "fit" << std::endl; size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkk", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &addressMinHashObject)) return NULL; // std::cout << "86" << std::endl; // parse from python list to a c++ map<size_t, vector<size_t> > // where key == instance id and vector<size_t> == non null feature ids std::cout << "96" << std::endl; SparseMatrixFloat* originalDataMatrix = parseRawData(instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures); // std::cout << "91" << std::endl; // get pointer to the minhash object // std::cout << "94" << std::endl; std::cout << "103" << std::endl; MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); std::cout << "105" << std::endl; minHash->set_mOriginalData(originalDataMatrix); // std::cout << "98" << std::endl; std::cout << "109" << std::endl; minHash->fit(originalDataMatrix); // std::cout << "101" << std::endl; std::cout << "113" << std::endl; addressMinHashObject = reinterpret_cast<size_t>(minHash); PyObject * pointerToInverseIndex = Py_BuildValue("k", addressMinHashObject); return pointerToInverseIndex; } static PyObject* partialFit(PyObject* self, PyObject* args) { return fit(self, args); } static PyObject* kneighbors(PyObject* self, PyObject* args) { std::cout << "kneighbors" << std::endl; size_t addressMinHashObject, nNeighbors, maxNumberOfInstances, maxNumberOfFeatures, returnDistance; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkiik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &nNeighbors, &returnDistance, &fast, &similarity, &addressMinHashObject)) return NULL; // std::cout << "125" << std::endl; // compute the k-nearest neighbors neighborhood* neighborhood_ = neighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, fast, similarity); // std::cout << "130" << std::endl; size_t cutFirstValue = 0; if (PyList_Size(instancesListObj) == 0) { cutFirstValue = 1; } if (nNeighbors == 0) { MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); nNeighbors = minHash->getNneighbors(); } // std::cout << "140" << std::endl; return bringNeighborhoodInShape(neighborhood_, nNeighbors, cutFirstValue, returnDistance); } static PyObject* kneighborsGraph(PyObject* self, PyObject* args) { size_t addressMinHashObject, nNeighbors, maxNumberOfInstances, maxNumberOfFeatures, returnDistance, symmetric; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkikik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &nNeighbors, &returnDistance, &fast, &symmetric, &similarity, &addressMinHashObject)) return NULL; // compute the k-nearest neighbors neighborhood* neighborhood_ = neighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, fast, similarity); if (nNeighbors == 0) { MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); nNeighbors = minHash->getNneighbors(); } return buildGraph(neighborhood_, nNeighbors, returnDistance, symmetric); } static PyObject* radiusNeighbors(PyObject* self, PyObject* args) { size_t addressMinHashObject, radius, maxNumberOfInstances, maxNumberOfFeatures, returnDistance, similarity; int fast; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkiik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &radius, &returnDistance, &fast,&similarity, &addressMinHashObject)) return NULL; // compute the k-nearest neighbors neighborhood* neighborhood_ = neighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, MAX_VALUE, fast, similarity); size_t cutFirstValue = 0; if (PyList_Size(instancesListObj) == 0) { cutFirstValue = 1; } return radiusNeighborhood(neighborhood_, radius, cutFirstValue, returnDistance); } static PyObject* radiusNeighborsGraph(PyObject* self, PyObject* args) { size_t addressMinHashObject, radius, maxNumberOfInstances, maxNumberOfFeatures, returnDistance, symmetric; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkikik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &radius, &returnDistance, &fast, &symmetric, &similarity, &addressMinHashObject)) return NULL; // compute the k-nearest neighbors neighborhood* neighborhood_ = neighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, MAX_VALUE, fast, similarity); return radiusNeighborhoodGraph(neighborhood_, radius, returnDistance, symmetric); } static PyObject* fitKneighbors(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, returnDistance; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkiik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &nNeighbors, &returnDistance, &fast, &similarity, &addressMinHashObject)) return NULL; neighborhood* neighborhood_ = fitNeighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, fast, similarity); size_t cutFirstValue = 1; if (nNeighbors == 0) { MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); nNeighbors = minHash->getNneighbors(); } return bringNeighborhoodInShape(neighborhood_, nNeighbors, cutFirstValue, returnDistance); } static PyObject* fitKneighborsGraph(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, returnDistance, symmetric; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkikik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &nNeighbors, &returnDistance, &fast, &symmetric, &similarity, &addressMinHashObject)) return NULL; neighborhood* neighborhood_ = fitNeighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, nNeighbors, fast, similarity); if (nNeighbors == 0) { MinHash* minHash = reinterpret_cast<MinHash* >(addressMinHashObject); nNeighbors = minHash->getNneighbors(); } return buildGraph(neighborhood_, nNeighbors, returnDistance, symmetric); } static PyObject* fitRadiusNeighbors(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures, radius, returnDistance; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkiik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &radius, &returnDistance, &fast, &similarity, &addressMinHashObject)) return NULL; neighborhood* neighborhood_ = fitNeighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, MAX_VALUE, fast, similarity); size_t cutFirstValue = 1; return radiusNeighborhood(neighborhood_, radius, cutFirstValue, returnDistance); } static PyObject* fitRadiusNeighborsGraph(PyObject* self, PyObject* args) { size_t addressMinHashObject, maxNumberOfInstances, maxNumberOfFeatures, radius, returnDistance, symmetric; int fast, similarity; PyObject* instancesListObj, *featuresListObj, *dataListObj; if (!PyArg_ParseTuple(args, "O!O!O!kkkkikik", &PyList_Type, &instancesListObj, &PyList_Type, &featuresListObj, &PyList_Type, &dataListObj, &maxNumberOfInstances, &maxNumberOfFeatures, &radius, &returnDistance, &fast, &symmetric, &similarity, &addressMinHashObject)) return NULL; neighborhood* neighborhood_ = fitNeighborhoodComputation(addressMinHashObject, instancesListObj, featuresListObj, dataListObj, maxNumberOfInstances, maxNumberOfFeatures, MAX_VALUE, fast, similarity); return radiusNeighborhoodGraph(neighborhood_, radius, returnDistance, symmetric); } // definition of avaible functions for python and which function parsing fucntion in c++ should be called. static PyMethodDef minHashFunctions[] = { {"fit", fit, METH_VARARGS, "Calculate the inverse index for the given instances."}, {"partial_fit", partialFit, METH_VARARGS, "Extend the inverse index with the given instances."}, {"kneighbors", kneighbors, METH_VARARGS, "Calculate k-nearest neighbors."}, {"kneighbors_graph", kneighborsGraph, METH_VARARGS, "Calculate k-nearest neighbors as a graph."}, {"radius_neighbors", radiusNeighbors, METH_VARARGS, "Calculate the neighbors inside a given radius."}, {"radius_neighbors_graph", radiusNeighborsGraph, METH_VARARGS, "Calculate the neighbors inside a given radius as a graph."}, {"fit_kneighbors", fitKneighbors, METH_VARARGS, "Fits and calculates k-nearest neighbors."}, {"fit_kneighbors_graph", fitKneighborsGraph, METH_VARARGS, "Fits and calculates k-nearest neighbors as a graph."}, {"fit_radius_neighbors", fitRadiusNeighbors, METH_VARARGS, "Fits and calculates the neighbors inside a given radius."}, {"fit_radius_neighbors_graph", fitRadiusNeighborsGraph, METH_VARARGS, "Fits and calculates the neighbors inside a given radius as a graph."}, {"create_object", createObject, METH_VARARGS, "Create the c++ object."}, {"delete_object", deleteObject, METH_VARARGS, "Delete the c++ object by calling the destructor."}, {NULL, NULL, 0, NULL} }; // definition of the module for python PyMODINIT_FUNC init_minHash(void) { (void) Py_InitModule("_minHash", minHashFunctions); }<|endoftext|>
<commit_before>// Licence 2 #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include "dart_api.h" //#include "dart_native_api.h" struct termios tio; struct termios stdio; struct termios old_stdio; int tty_fd; /* Called the first time a native function with a given name is called, to resolve the Dart name of the native function into a C function pointer. */ Dart_NativeFunction ResolveName(Dart_Handle name, int argc); /* Called when the extension is loaded. */ DART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) { if (Dart_IsError(parent_library)) { return parent_library; } Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName); if (Dart_IsError(result_code)) return result_code; return Dart_Null(); } Dart_Handle HandleError(Dart_Handle handle) { if (Dart_IsError(handle)) Dart_PropagateError(handle); return handle; } void SystemOpen(Dart_NativeArguments arguments) { Dart_EnterScope(); // START opening tcgetattr(STDOUT_FILENO,&old_stdio); const char *portname = "/dev/tty.usbmodemfd131"; memset(&stdio,0,sizeof(stdio)); stdio.c_iflag=0; stdio.c_oflag=0; stdio.c_cflag=0; stdio.c_lflag=0; stdio.c_cc[VMIN]=1; stdio.c_cc[VTIME]=0; tcsetattr(STDOUT_FILENO,TCSANOW,&stdio); tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio); fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking memset(&tio,0,sizeof(tio)); tio.c_iflag=0; tio.c_oflag=0; tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information tio.c_lflag=0; tio.c_cc[VMIN]=1; tio.c_cc[VTIME]=5; tty_fd=open(portname, O_RDWR | O_NONBLOCK); bool success = (tty_fd != -1); // END Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(success))); Dart_ExitScope(); } void SystemClose(Dart_NativeArguments arguments){ Dart_EnterScope(); close(tty_fd); tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio); Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(true))); Dart_ExitScope(); } Dart_NativeFunction ResolveName(Dart_Handle name, int argc) { // If we fail, we return NULL, and Dart throws an exception. if (!Dart_IsString(name)) return NULL; Dart_NativeFunction result = NULL; const char* cname; HandleError(Dart_StringToCString(name, &cname)); if (strcmp("SystemOpen", cname) == 0) result = SystemOpen; if (strcmp("SystemClose", cname) == 0) result = SystemClose; Dart_ExitScope(); return result; } /* void SystemSrand(Dart_NativeArguments arguments) { Dart_EnterScope(); bool success = false; Dart_Handle seed_object = HandleError(Dart_GetNativeArgument(arguments, 0)); if (Dart_IsInteger(seed_object)) { bool fits; HandleError(Dart_IntegerFitsIntoInt64(seed_object, &fits)); if (fits) { int64_t seed; HandleError(Dart_IntegerToInt64(seed_object, &seed)); srand(static_cast<unsigned>(seed)); success = true; } } Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(success))); Dart_ExitScope(); } uint8_t* randomArray(int seed, int length) { if (length <= 0 || length > 10000000) return NULL; uint8_t* values = reinterpret_cast<uint8_t*>(malloc(length)); if (NULL == values) return NULL; srand(seed); for (int i = 0; i < length; ++i) { values[i] = rand() % 256; } return values; } void wrappedRandomArray(Dart_Port dest_port_id, Dart_CObject* message) { Dart_Port reply_port_id = ILLEGAL_PORT; if (message->type == Dart_CObject_kArray && 3 == message->value.as_array.length) { // Use .as_array and .as_int32 to access the data in the Dart_CObject. Dart_CObject* param0 = message->value.as_array.values[0]; Dart_CObject* param1 = message->value.as_array.values[1]; Dart_CObject* param2 = message->value.as_array.values[2]; if (param0->type == Dart_CObject_kInt32 && param1->type == Dart_CObject_kInt32 && param2->type == Dart_CObject_kSendPort) { int seed = param0->value.as_int32; int length = param1->value.as_int32; reply_port_id = param2->value.as_send_port; uint8_t* values = randomArray(seed, length); if (values != NULL) { Dart_CObject result; result.type = Dart_CObject_kTypedData; result.value.as_typed_data.type = Dart_TypedData_kUint8; result.value.as_typed_data.values = values; result.value.as_typed_data.length = length; Dart_PostCObject(reply_port_id, &result); free(values); // It is OK that result is destroyed when function exits. // Dart_PostCObject has copied its data. return; } } } Dart_CObject result; result.type = Dart_CObject_kNull; Dart_PostCObject(reply_port_id, &result); } void randomArrayServicePort(Dart_NativeArguments arguments) { Dart_EnterScope(); Dart_SetReturnValue(arguments, Dart_Null()); Dart_Port service_port = Dart_NewNativePort("RandomArrayService", wrappedRandomArray, true); if (service_port != ILLEGAL_PORT) { Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port)); Dart_SetReturnValue(arguments, send_port); } Dart_ExitScope(); } struct FunctionLookup { const char* name; Dart_NativeFunction function; }; FunctionLookup function_list[] = { {"SystemRand", SystemRand}, {"SystemSrand", SystemSrand}, {"RandomArray_ServicePort", randomArrayServicePort}, {NULL, NULL}}; Dart_NativeFunction ResolveName(Dart_Handle name, int argc) { if (!Dart_IsString(name)) return NULL; Dart_NativeFunction result = NULL; Dart_EnterScope(); const char* cname; HandleError(Dart_StringToCString(name, &cname)); for (int i=0; function_list[i].name != NULL; ++i) { if (strcmp(function_list[i].name, cname) == 0) { result = function_list[i].function; break; } } Dart_ExitScope(); return result; } } */ <commit_msg>select baudrate method<commit_after>// Licence 2 #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include "dart_api.h" //#include "dart_native_api.h" struct termios tio; struct termios stdio; struct termios old_stdio; int tty_fd; /* Called the first time a native function with a given name is called, to resolve the Dart name of the native function into a C function pointer. */ Dart_NativeFunction ResolveName(Dart_Handle name, int argc); /* Called when the extension is loaded. */ DART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) { if (Dart_IsError(parent_library)) { return parent_library; } Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName); if (Dart_IsError(result_code)) return result_code; return Dart_Null(); } Dart_Handle HandleError(Dart_Handle handle) { if (Dart_IsError(handle)) Dart_PropagateError(handle); return handle; } speed_t toBaudrate(int speed){ switch(speed){ case 50: return B50; case 75: return B75; case 110: return B110; case 134: return B134; case 150: return B150; case 200: return B200; case 300: return B300; case 600: return B600; case 1200: return B1200; case 1800: return B1800; case 2400: return B2400; case 4800: return B4800; case 9600: return B9600; case 19200: return B19200; case 38400: return B38400; case 57600: return B57600; case 115200: return B115200; case 230400: return B230400; } throw "Unknown baudrate"; } void SystemOpen(Dart_NativeArguments arguments) { Dart_EnterScope(); // START opening tcgetattr(STDOUT_FILENO,&old_stdio); // TODO values from method const char *portname = "/dev/tty.usbmodemfd131"; speed_t baudrate = toBaudrate(9600); memset(&stdio,0,sizeof(stdio)); stdio.c_iflag=0; stdio.c_oflag=0; stdio.c_cflag=0; stdio.c_lflag=0; stdio.c_cc[VMIN]=1; stdio.c_cc[VTIME]=0; tcsetattr(STDOUT_FILENO,TCSANOW,&stdio); tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio); fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking memset(&tio,0,sizeof(tio)); tio.c_iflag=0; tio.c_oflag=0; tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information tio.c_lflag=0; tio.c_cc[VMIN]=1; tio.c_cc[VTIME]=5; tty_fd=open(portname, O_RDWR | O_NONBLOCK); bool success = (tty_fd != -1); if(success){ cfsetospeed(&tio, baudrate); cfsetispeed(&tio, baudrate); tcsetattr(tty_fd,TCSANOW,&tio); } // END Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(success))); Dart_ExitScope(); } void SystemClose(Dart_NativeArguments arguments){ Dart_EnterScope(); close(tty_fd); tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio); Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(true))); Dart_ExitScope(); } Dart_NativeFunction ResolveName(Dart_Handle name, int argc) { // If we fail, we return NULL, and Dart throws an exception. if (!Dart_IsString(name)) return NULL; Dart_NativeFunction result = NULL; const char* cname; HandleError(Dart_StringToCString(name, &cname)); if (strcmp("SystemOpen", cname) == 0) result = SystemOpen; if (strcmp("SystemClose", cname) == 0) result = SystemClose; Dart_ExitScope(); return result; } /* void SystemSrand(Dart_NativeArguments arguments) { Dart_EnterScope(); bool success = false; Dart_Handle seed_object = HandleError(Dart_GetNativeArgument(arguments, 0)); if (Dart_IsInteger(seed_object)) { bool fits; HandleError(Dart_IntegerFitsIntoInt64(seed_object, &fits)); if (fits) { int64_t seed; HandleError(Dart_IntegerToInt64(seed_object, &seed)); srand(static_cast<unsigned>(seed)); success = true; } } Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(success))); Dart_ExitScope(); } uint8_t* randomArray(int seed, int length) { if (length <= 0 || length > 10000000) return NULL; uint8_t* values = reinterpret_cast<uint8_t*>(malloc(length)); if (NULL == values) return NULL; srand(seed); for (int i = 0; i < length; ++i) { values[i] = rand() % 256; } return values; } void wrappedRandomArray(Dart_Port dest_port_id, Dart_CObject* message) { Dart_Port reply_port_id = ILLEGAL_PORT; if (message->type == Dart_CObject_kArray && 3 == message->value.as_array.length) { // Use .as_array and .as_int32 to access the data in the Dart_CObject. Dart_CObject* param0 = message->value.as_array.values[0]; Dart_CObject* param1 = message->value.as_array.values[1]; Dart_CObject* param2 = message->value.as_array.values[2]; if (param0->type == Dart_CObject_kInt32 && param1->type == Dart_CObject_kInt32 && param2->type == Dart_CObject_kSendPort) { int seed = param0->value.as_int32; int length = param1->value.as_int32; reply_port_id = param2->value.as_send_port; uint8_t* values = randomArray(seed, length); if (values != NULL) { Dart_CObject result; result.type = Dart_CObject_kTypedData; result.value.as_typed_data.type = Dart_TypedData_kUint8; result.value.as_typed_data.values = values; result.value.as_typed_data.length = length; Dart_PostCObject(reply_port_id, &result); free(values); // It is OK that result is destroyed when function exits. // Dart_PostCObject has copied its data. return; } } } Dart_CObject result; result.type = Dart_CObject_kNull; Dart_PostCObject(reply_port_id, &result); } void randomArrayServicePort(Dart_NativeArguments arguments) { Dart_EnterScope(); Dart_SetReturnValue(arguments, Dart_Null()); Dart_Port service_port = Dart_NewNativePort("RandomArrayService", wrappedRandomArray, true); if (service_port != ILLEGAL_PORT) { Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port)); Dart_SetReturnValue(arguments, send_port); } Dart_ExitScope(); } struct FunctionLookup { const char* name; Dart_NativeFunction function; }; FunctionLookup function_list[] = { {"SystemRand", SystemRand}, {"SystemSrand", SystemSrand}, {"RandomArray_ServicePort", randomArrayServicePort}, {NULL, NULL}}; Dart_NativeFunction ResolveName(Dart_Handle name, int argc) { if (!Dart_IsString(name)) return NULL; Dart_NativeFunction result = NULL; Dart_EnterScope(); const char* cname; HandleError(Dart_StringToCString(name, &cname)); for (int i=0; function_list[i].name != NULL; ++i) { if (strcmp(function_list[i].name, cname) == 0) { result = function_list[i].function; break; } } Dart_ExitScope(); return result; } } */ <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if !DEVICE_FLASH #error [NOT_SUPPORTED] Flash API not supported for this target #else #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "platform/mbed_mpu_mgmt.h" #include "mbed.h" #include "flash_api.h" using namespace utest::v1; #define TEST_CYCLES 10000000 #define ALLOWED_DRIFT_PPM (1000000/5000) //0.5% /* return values to be checked are documented at: http://arm-software.github.io/CMSIS_5/Pack/html/algorithmFunc.html#Verify */ #ifndef ALIGN_DOWN #define ALIGN_DOWN(x, a) ((x)& ~((a) - 1)) #endif static int timer_diff_start; static void erase_range(flash_t *flash, uint32_t addr, uint32_t size) { while (size > 0) { uint32_t sector_size = flash_get_sector_size(flash, addr); TEST_ASSERT_NOT_EQUAL(0, sector_size); int32_t ret = flash_erase_sector(flash, addr); TEST_ASSERT_EQUAL_INT32(0, ret); addr += sector_size; size = size > sector_size ? size - sector_size : 0; } } #if defined (__ICCARM__) MBED_NOINLINE static void delay_loop(uint32_t count) { __asm volatile( "loop: \n" " SUBS %0, %0, #1 \n" " BCS.n loop\n" : "+r"(count) : : "cc" ); } #elif defined ( __GNUC__ ) || defined(__ARMCC_VERSION) MBED_NOINLINE static void delay_loop(uint32_t count) { __asm__ volatile( "%=:\n\t" #if defined(__thumb__) && !defined(__thumb2__) && !defined(__ARMCC_VERSION) "SUB %0, #1\n\t" #else "SUBS %0, %0, #1\n\t" #endif "BCS %=b\n\t" : "+l"(count) : : "cc" ); } #endif MBED_NOINLINE static int time_cpu_cycles(uint32_t cycles) { Timer timer; core_util_critical_section_enter(); timer.start(); delay_loop(cycles); timer.stop(); core_util_critical_section_exit(); return timer.read_us(); } void flash_init_test() { timer_diff_start = time_cpu_cycles(TEST_CYCLES); flash_t test_flash; int32_t ret = flash_init(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_free(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); } void flash_mapping_alignment_test() { flash_t test_flash; int32_t ret = flash_init(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); const uint32_t page_size = flash_get_page_size(&test_flash); const uint32_t flash_start = flash_get_start_address(&test_flash); const uint32_t flash_size = flash_get_size(&test_flash); TEST_ASSERT_TRUE(page_size != 0UL); uint32_t sector_size = flash_get_sector_size(&test_flash, flash_start); for (uint32_t offset = 0; offset < flash_size; offset += sector_size) { const uint32_t sector_start = flash_start + offset; sector_size = flash_get_sector_size(&test_flash, sector_start); const uint32_t sector_end = sector_start + sector_size - 1; const uint32_t end_sector_size = flash_get_sector_size(&test_flash, sector_end); // Sector size must be a valid value TEST_ASSERT_NOT_EQUAL(MBED_FLASH_INVALID_SIZE, sector_size); // Sector size must be greater than zero TEST_ASSERT_NOT_EQUAL(0, sector_size); // All flash sectors must be a multiple of page size TEST_ASSERT_EQUAL(0, sector_size % page_size); // Sector address must be a multiple of sector size TEST_ASSERT_EQUAL(0, sector_start % sector_size); // All address in a sector must return the same sector size TEST_ASSERT_EQUAL(sector_size, end_sector_size); } // Make sure unmapped flash is reported correctly TEST_ASSERT_EQUAL(MBED_FLASH_INVALID_SIZE, flash_get_sector_size(&test_flash, flash_start - 1)); TEST_ASSERT_EQUAL(MBED_FLASH_INVALID_SIZE, flash_get_sector_size(&test_flash, flash_start + flash_size)); ret = flash_free(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); } void flash_erase_sector_test() { flash_t test_flash; int32_t ret = flash_init(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); uint32_t addr_after_last = flash_get_start_address(&test_flash) + flash_get_size(&test_flash); uint32_t last_sector_size = flash_get_sector_size(&test_flash, addr_after_last - 1); uint32_t last_sector = addr_after_last - last_sector_size; TEST_ASSERT_EQUAL_INT32(0, last_sector % last_sector_size); utest_printf("ROM ends at 0x%lx, test starts at 0x%lx\n", FLASHIAP_APP_ROM_END_ADDR, last_sector); TEST_SKIP_UNLESS_MESSAGE(last_sector >= FLASHIAP_APP_ROM_END_ADDR, "Test skipped. Test region overlaps code."); ret = flash_erase_sector(&test_flash, last_sector); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_free(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); } // Erase sector, write one page, erase sector and write new data void flash_program_page_test() { flash_t test_flash; int32_t ret = flash_init(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); uint32_t test_size = flash_get_page_size(&test_flash); uint8_t *data = new uint8_t[test_size]; uint8_t *data_flashed = new uint8_t[test_size]; for (uint32_t i = 0; i < test_size; i++) { data[i] = 0xCE; } // the one before the last page in the system uint32_t address = flash_get_start_address(&test_flash) + flash_get_size(&test_flash) - (2 * test_size); // sector size might not be same as page size uint32_t erase_sector_boundary = ALIGN_DOWN(address, flash_get_sector_size(&test_flash, address)); utest_printf("ROM ends at 0x%lx, test starts at 0x%lx\n", FLASHIAP_APP_ROM_END_ADDR, erase_sector_boundary); TEST_SKIP_UNLESS_MESSAGE(erase_sector_boundary >= FLASHIAP_APP_ROM_END_ADDR, "Test skipped. Test region overlaps code."); ret = flash_erase_sector(&test_flash, erase_sector_boundary); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_program_page(&test_flash, address, data, test_size); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_read(&test_flash, address, data_flashed, test_size); TEST_ASSERT_EQUAL_INT32(0, ret); TEST_ASSERT_EQUAL_UINT8_ARRAY(data, data_flashed, test_size); // sector size might not be same as page size erase_sector_boundary = ALIGN_DOWN(address, flash_get_sector_size(&test_flash, address)); ret = flash_erase_sector(&test_flash, erase_sector_boundary); TEST_ASSERT_EQUAL_INT32(0, ret); // write another data to be certain we are re-flashing for (uint32_t i = 0; i < test_size; i++) { data[i] = 0xAC; } ret = flash_program_page(&test_flash, address, data, test_size); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_read(&test_flash, address, data_flashed, test_size); TEST_ASSERT_EQUAL_INT32(0, ret); TEST_ASSERT_EQUAL_UINT8_ARRAY(data, data_flashed, test_size); ret = flash_free(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); delete[] data; delete[] data_flashed; } // check the execution speed at the start and end of the test to make sure // cache settings weren't changed void flash_clock_and_cache_test() { const int timer_diff_end = time_cpu_cycles(TEST_CYCLES); const int acceptable_range = timer_diff_start / (ALLOWED_DRIFT_PPM); TEST_ASSERT_UINT32_WITHIN(acceptable_range, timer_diff_start, timer_diff_end); } Case cases[] = { Case("Flash - init", flash_init_test), Case("Flash - mapping alignment", flash_mapping_alignment_test), Case("Flash - erase sector", flash_erase_sector_test), Case("Flash - program page", flash_program_page_test), Case("Flash - clock and cache test", flash_clock_and_cache_test), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { mbed_mpu_manager_lock_ram_execution(); mbed_mpu_manager_lock_rom_write(); GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); } void greentea_test_teardown(const size_t passed, const size_t failed, const failure_t failure) { mbed_mpu_manager_unlock_ram_execution(); mbed_mpu_manager_unlock_rom_write(); greentea_test_teardown_handler(passed, failed, failure); } Specification specification(greentea_test_setup, cases, greentea_test_teardown); int main() { Harness::run(specification); } #endif !DEVICE_FLASH <commit_msg>hal-tests-tests-mbed_hal-flash compilation warning<commit_after>/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if !DEVICE_FLASH #error [NOT_SUPPORTED] Flash API not supported for this target #else #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "platform/mbed_mpu_mgmt.h" #include "mbed.h" #include "flash_api.h" using namespace utest::v1; #define TEST_CYCLES 10000000 #define ALLOWED_DRIFT_PPM (1000000/5000) //0.5% /* return values to be checked are documented at: http://arm-software.github.io/CMSIS_5/Pack/html/algorithmFunc.html#Verify */ #ifndef ALIGN_DOWN #define ALIGN_DOWN(x, a) ((x)& ~((a) - 1)) #endif static int timer_diff_start; static void erase_range(flash_t *flash, uint32_t addr, uint32_t size) { while (size > 0) { uint32_t sector_size = flash_get_sector_size(flash, addr); TEST_ASSERT_NOT_EQUAL(0, sector_size); int32_t ret = flash_erase_sector(flash, addr); TEST_ASSERT_EQUAL_INT32(0, ret); addr += sector_size; size = size > sector_size ? size - sector_size : 0; } } #if defined (__ICCARM__) MBED_NOINLINE static void delay_loop(uint32_t count) { __asm volatile( "loop: \n" " SUBS %0, %0, #1 \n" " BCS.n loop\n" : "+r"(count) : : "cc" ); } #elif defined ( __GNUC__ ) || defined(__ARMCC_VERSION) MBED_NOINLINE static void delay_loop(uint32_t count) { __asm__ volatile( "%=:\n\t" #if defined(__thumb__) && !defined(__thumb2__) && !defined(__ARMCC_VERSION) "SUB %0, #1\n\t" #else "SUBS %0, %0, #1\n\t" #endif "BCS %=b\n\t" : "+l"(count) : : "cc" ); } #endif MBED_NOINLINE static int time_cpu_cycles(uint32_t cycles) { Timer timer; core_util_critical_section_enter(); timer.start(); delay_loop(cycles); timer.stop(); core_util_critical_section_exit(); return timer.read_us(); } void flash_init_test() { timer_diff_start = time_cpu_cycles(TEST_CYCLES); flash_t test_flash; int32_t ret = flash_init(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_free(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); } void flash_mapping_alignment_test() { flash_t test_flash; int32_t ret = flash_init(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); const uint32_t page_size = flash_get_page_size(&test_flash); const uint32_t flash_start = flash_get_start_address(&test_flash); const uint32_t flash_size = flash_get_size(&test_flash); TEST_ASSERT_TRUE(page_size != 0UL); uint32_t sector_size = flash_get_sector_size(&test_flash, flash_start); for (uint32_t offset = 0; offset < flash_size; offset += sector_size) { const uint32_t sector_start = flash_start + offset; sector_size = flash_get_sector_size(&test_flash, sector_start); const uint32_t sector_end = sector_start + sector_size - 1; const uint32_t end_sector_size = flash_get_sector_size(&test_flash, sector_end); // Sector size must be a valid value TEST_ASSERT_NOT_EQUAL(MBED_FLASH_INVALID_SIZE, sector_size); // Sector size must be greater than zero TEST_ASSERT_NOT_EQUAL(0, sector_size); // All flash sectors must be a multiple of page size TEST_ASSERT_EQUAL(0, sector_size % page_size); // Sector address must be a multiple of sector size TEST_ASSERT_EQUAL(0, sector_start % sector_size); // All address in a sector must return the same sector size TEST_ASSERT_EQUAL(sector_size, end_sector_size); } // Make sure unmapped flash is reported correctly TEST_ASSERT_EQUAL(MBED_FLASH_INVALID_SIZE, flash_get_sector_size(&test_flash, flash_start - 1)); TEST_ASSERT_EQUAL(MBED_FLASH_INVALID_SIZE, flash_get_sector_size(&test_flash, flash_start + flash_size)); ret = flash_free(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); } void flash_erase_sector_test() { flash_t test_flash; int32_t ret = flash_init(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); uint32_t addr_after_last = flash_get_start_address(&test_flash) + flash_get_size(&test_flash); uint32_t last_sector_size = flash_get_sector_size(&test_flash, addr_after_last - 1); uint32_t last_sector = addr_after_last - last_sector_size; TEST_ASSERT_EQUAL_INT32(0, last_sector % last_sector_size); utest_printf("ROM ends at 0x%lx, test starts at 0x%lx\n", FLASHIAP_APP_ROM_END_ADDR, last_sector); TEST_SKIP_UNLESS_MESSAGE(last_sector >= FLASHIAP_APP_ROM_END_ADDR, "Test skipped. Test region overlaps code."); ret = flash_erase_sector(&test_flash, last_sector); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_free(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); } // Erase sector, write one page, erase sector and write new data void flash_program_page_test() { flash_t test_flash; int32_t ret = flash_init(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); uint32_t test_size = flash_get_page_size(&test_flash); uint8_t *data = new uint8_t[test_size]; uint8_t *data_flashed = new uint8_t[test_size]; for (uint32_t i = 0; i < test_size; i++) { data[i] = 0xCE; } // the one before the last page in the system uint32_t address = flash_get_start_address(&test_flash) + flash_get_size(&test_flash) - (2 * test_size); // sector size might not be same as page size uint32_t erase_sector_boundary = ALIGN_DOWN(address, flash_get_sector_size(&test_flash, address)); utest_printf("ROM ends at 0x%lx, test starts at 0x%lx\n", FLASHIAP_APP_ROM_END_ADDR, erase_sector_boundary); TEST_SKIP_UNLESS_MESSAGE(erase_sector_boundary >= FLASHIAP_APP_ROM_END_ADDR, "Test skipped. Test region overlaps code."); ret = flash_erase_sector(&test_flash, erase_sector_boundary); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_program_page(&test_flash, address, data, test_size); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_read(&test_flash, address, data_flashed, test_size); TEST_ASSERT_EQUAL_INT32(0, ret); TEST_ASSERT_EQUAL_UINT8_ARRAY(data, data_flashed, test_size); // sector size might not be same as page size erase_sector_boundary = ALIGN_DOWN(address, flash_get_sector_size(&test_flash, address)); ret = flash_erase_sector(&test_flash, erase_sector_boundary); TEST_ASSERT_EQUAL_INT32(0, ret); // write another data to be certain we are re-flashing for (uint32_t i = 0; i < test_size; i++) { data[i] = 0xAC; } ret = flash_program_page(&test_flash, address, data, test_size); TEST_ASSERT_EQUAL_INT32(0, ret); ret = flash_read(&test_flash, address, data_flashed, test_size); TEST_ASSERT_EQUAL_INT32(0, ret); TEST_ASSERT_EQUAL_UINT8_ARRAY(data, data_flashed, test_size); ret = flash_free(&test_flash); TEST_ASSERT_EQUAL_INT32(0, ret); delete[] data; delete[] data_flashed; } // check the execution speed at the start and end of the test to make sure // cache settings weren't changed void flash_clock_and_cache_test() { const int timer_diff_end = time_cpu_cycles(TEST_CYCLES); const int acceptable_range = timer_diff_start / (ALLOWED_DRIFT_PPM); TEST_ASSERT_UINT32_WITHIN(acceptable_range, timer_diff_start, timer_diff_end); } Case cases[] = { Case("Flash - init", flash_init_test), Case("Flash - mapping alignment", flash_mapping_alignment_test), Case("Flash - erase sector", flash_erase_sector_test), Case("Flash - program page", flash_program_page_test), Case("Flash - clock and cache test", flash_clock_and_cache_test), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { mbed_mpu_manager_lock_ram_execution(); mbed_mpu_manager_lock_rom_write(); GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); } void greentea_test_teardown(const size_t passed, const size_t failed, const failure_t failure) { mbed_mpu_manager_unlock_ram_execution(); mbed_mpu_manager_unlock_rom_write(); greentea_test_teardown_handler(passed, failed, failure); } Specification specification(greentea_test_setup, cases, greentea_test_teardown); int main() { Harness::run(specification); } #endif // !DEVICE_FLASH <|endoftext|>
<commit_before>// @(#)root/ged:$Id$ // Author: Marek Biskup, Ilka Antcheva 22/07/03 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGedMarkerSelect, TGedMarkerPopup // // // // The TGedMarkerPopup is a popup containing buttons to // // select marker style. // // // // The TGedMarkerSelect widget is a button showing selected marker // // and a little down arrow. When clicked on the arrow the // // TGedMarkerPopup pops up. // // // // Selecting a marker in this widget will generate the event: // // kC_MARKERSEL, kMAR_SELCHANGED, widget id, style. // // // // and the signal: // // MarkerSelected(Style_t marker) // // // ////////////////////////////////////////////////////////////////////////// #include "TGedMarkerSelect.h" #include "TGPicture.h" #include "TGToolTip.h" #include "TGButton.h" #include "Riostream.h" ClassImp(TGedMarkerSelect) ClassImp(TGedMarkerPopup) struct MarkerDescription_t { const char* fFilename; // xpm file name const char* fName; // type number for tooltip Int_t fNumber; // marker type number }; static MarkerDescription_t gMarkers[] = { {"marker1.xpm", "1", 1}, {"marker6.xpm", "6", 6}, {"marker7.xpm", "7", 7}, {"marker2.xpm", "2", 2}, {"marker3.xpm", "3", 3}, {"marker4.xpm", "4", 4}, {"marker5.xpm", "5", 5}, {"marker20.xpm", "20", 20}, {"marker21.xpm", "21", 21}, {"marker22.xpm", "22", 22}, {"marker23.xpm", "23", 23}, {"marker24.xpm", "24", 24}, {"marker25.xpm", "25", 25}, {"marker26.xpm", "26", 26}, {"marker27.xpm", "27", 27}, {"marker28.xpm", "28", 28}, {"marker29.xpm", "29", 29}, {"marker30.xpm", "30", 30}, {0, 0, 0}, }; static MarkerDescription_t* GetMarkerByNumber(Int_t number) { for (Int_t i = 0; gMarkers[i].fFilename != 0; i++) { if (gMarkers[i].fNumber == number) return &gMarkers[i]; } return 0; } //______________________________________________________________________________ TGedMarkerPopup::TGedMarkerPopup(const TGWindow *p, const TGWindow *m, Style_t markerStyle) : TGedPopup(p, m, 30, 30, kDoubleBorder | kRaisedFrame | kOwnBackground, GetDefaultFrameBackground()) { // Create marker popup window. TGButton *b; fCurrentStyle = markerStyle; Pixel_t white; gClient->GetColorByName("white", white); // white background SetBackgroundColor(white); SetLayoutManager(new TGTileLayout(this, 1)); for (int i = 0; gMarkers[i].fFilename != 0; i++) { AddFrame(b = new TGPictureButton(this, gMarkers[i].fFilename, gMarkers[i].fNumber, TGButton::GetDefaultGC()(), kSunkenFrame), new TGLayoutHints(kLHintsLeft, 14, 14, 14, 14)); b->SetToolTipText(gMarkers[i].fName); } Resize(65, 94); MapSubwindows(); } //______________________________________________________________________________ TGedMarkerPopup::~TGedMarkerPopup() { // Destructor. TGFrameElement *el; TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->InheritsFrom(TGPictureButton::Class())) fClient->FreePicture(((TGPictureButton *)el->fFrame)->GetPicture()); } Cleanup(); } //______________________________________________________________________________ Bool_t TGedMarkerPopup::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Process messages generated by the marker popup window. if (GET_MSG(msg) == kC_COMMAND && GET_SUBMSG(msg) == kCM_BUTTON) { SendMessage(fMsgWindow, MK_MSG(kC_MARKERSEL, kMAR_SELCHANGED), 0, parm1); EndPopup(); } if (parm2) ; // no warning return kTRUE; } //______________________________________________________________________________ TGedMarkerSelect::TGedMarkerSelect(const TGWindow *p, Style_t markerStyle, Int_t id) : TGedSelect(p, id) { // Create and show marker popup window. fPicture = 0; SetPopup(new TGedMarkerPopup(gClient->GetDefaultRoot(), this, markerStyle)); SetMarkerStyle(markerStyle); } //_____________________________________________________________________________ Bool_t TGedMarkerSelect::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Process messages according to the user input. if (GET_MSG(msg) == kC_MARKERSEL && GET_SUBMSG(msg) == kMAR_SELCHANGED) { SetMarkerStyle(parm2); SendMessage(fMsgWindow, MK_MSG(kC_MARKERSEL, kMAR_SELCHANGED), fWidgetId, parm2); } if (parm1) // no warning ; return kTRUE; } //_____________________________________________________________________________ void TGedMarkerSelect::DoRedraw() { // Draw selected marker type as current one. TGedSelect::DoRedraw(); Int_t x, y; UInt_t w, h; if (IsEnabled()) { // pattern rectangle x = fBorderWidth + 2; y = fBorderWidth + 2; // 1; h = fHeight - (fBorderWidth * 2) - 4; // -3; // 14 w = h; if (fState == kButtonDown) { ++x; ++y; } gVirtualX->DrawRectangle(fId, GetShadowGC()(), x, y, w - 1, h - 1); if (fPicture != 0) fPicture->Draw(fId, fDrawGC->GetGC(), x + 1, y + 1); } else { // sunken rectangle x = fBorderWidth + 2; y = fBorderWidth + 2; // 1; w = 42; h = fHeight - (fBorderWidth * 2) - 4; // 3; Draw3dRectangle(kSunkenFrame, x, y, w, h); } } //_____________________________________________________________________________ void TGedMarkerSelect::SetMarkerStyle(Style_t markerStyle) { // Set marker. fMarkerStyle = markerStyle; gClient->NeedRedraw(this); if (fPicture) { gClient->FreePicture(fPicture); fPicture = 0; } MarkerDescription_t *md = GetMarkerByNumber(fMarkerStyle); if (md) fPicture = gClient->GetPicture(md->fFilename); MarkerSelected(fMarkerStyle); } //______________________________________________________________________________ void TGedMarkerSelect::SavePrimitive(ostream &out, Option_t * /*= ""*/) { // Save the pattern select widget as a C++ statement(s) on output stream out out <<" TGedMarkerSelect *"; out << GetName() << " = new TGedMarkerSelect(" << fParent->GetName() << "," << fMarkerStyle << "," << WidgetId() << ");" << endl; } <commit_msg>Cosmetics.<commit_after>// @(#)root/ged:$Id$ // Author: Marek Biskup, Ilka Antcheva 22/07/03 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGedMarkerSelect, TGedMarkerPopup // // // // The TGedMarkerPopup is a popup containing buttons to // // select marker style. // // // // The TGedMarkerSelect widget is a button showing selected marker // // and a little down arrow. When clicked on the arrow the // // TGedMarkerPopup pops up. // // // // Selecting a marker in this widget will generate the event: // // kC_MARKERSEL, kMAR_SELCHANGED, widget id, style. // // // // and the signal: // // MarkerSelected(Style_t marker) // // // ////////////////////////////////////////////////////////////////////////// #include "TGedMarkerSelect.h" #include "TGPicture.h" #include "TGToolTip.h" #include "TGButton.h" #include "Riostream.h" ClassImp(TGedMarkerSelect) ClassImp(TGedMarkerPopup) struct MarkerDescription_t { const char* fFilename; // xpm file name const char* fName; // type number for tooltip Int_t fNumber; // marker type number }; static MarkerDescription_t gMarkers[] = { {"marker1.xpm", "1", 1}, {"marker6.xpm", "6", 6}, {"marker7.xpm", "7", 7}, {"marker2.xpm", "2", 2}, {"marker3.xpm", "3", 3}, {"marker4.xpm", "4", 4}, {"marker5.xpm", "5", 5}, {"marker20.xpm", "20", 20}, {"marker21.xpm", "21", 21}, {"marker22.xpm", "22", 22}, {"marker23.xpm", "23", 23}, {"marker24.xpm", "24", 24}, {"marker25.xpm", "25", 25}, {"marker26.xpm", "26", 26}, {"marker27.xpm", "27", 27}, {"marker28.xpm", "28", 28}, {"marker29.xpm", "29", 29}, {"marker30.xpm", "30", 30}, {0, 0, 0}, }; static MarkerDescription_t* GetMarkerByNumber(Int_t number) { for (Int_t i = 0; gMarkers[i].fFilename != 0; i++) { if (gMarkers[i].fNumber == number) return &gMarkers[i]; } return 0; } //______________________________________________________________________________ TGedMarkerPopup::TGedMarkerPopup(const TGWindow *p, const TGWindow *m, Style_t markerStyle) : TGedPopup(p, m, 30, 30, kDoubleBorder | kRaisedFrame | kOwnBackground, GetDefaultFrameBackground()) { // Create marker popup window. TGButton *b; fCurrentStyle = markerStyle; Pixel_t white; gClient->GetColorByName("white", white); // white background SetBackgroundColor(white); SetLayoutManager(new TGTileLayout(this, 1)); for (int i = 0; gMarkers[i].fFilename != 0; i++) { AddFrame(b = new TGPictureButton(this, gMarkers[i].fFilename, gMarkers[i].fNumber, TGButton::GetDefaultGC()(), kSunkenFrame), new TGLayoutHints(kLHintsLeft, 14, 14, 14, 14)); b->SetToolTipText(gMarkers[i].fName); } Resize(65, 94); MapSubwindows(); } //______________________________________________________________________________ TGedMarkerPopup::~TGedMarkerPopup() { // Destructor. TGFrameElement *el; TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->InheritsFrom(TGPictureButton::Class())) fClient->FreePicture(((TGPictureButton *)el->fFrame)->GetPicture()); } Cleanup(); } //______________________________________________________________________________ Bool_t TGedMarkerPopup::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Process messages generated by the marker popup window. if (GET_MSG(msg) == kC_COMMAND && GET_SUBMSG(msg) == kCM_BUTTON) { SendMessage(fMsgWindow, MK_MSG(kC_MARKERSEL, kMAR_SELCHANGED), 0, parm1); EndPopup(); } if (parm2) ; // no warning return kTRUE; } //______________________________________________________________________________ TGedMarkerSelect::TGedMarkerSelect(const TGWindow *p, Style_t markerStyle, Int_t id) : TGedSelect(p, id) { // Create and show marker popup window. fPicture = 0; SetPopup(new TGedMarkerPopup(gClient->GetDefaultRoot(), this, markerStyle)); SetMarkerStyle(markerStyle); } //_____________________________________________________________________________ Bool_t TGedMarkerSelect::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Process messages according to the user input. if (GET_MSG(msg) == kC_MARKERSEL && GET_SUBMSG(msg) == kMAR_SELCHANGED) { SetMarkerStyle(parm2); parm1 = (Long_t)fWidgetId; SendMessage(fMsgWindow, MK_MSG(kC_MARKERSEL, kMAR_SELCHANGED), parm1, parm2); } return kTRUE; } //_____________________________________________________________________________ void TGedMarkerSelect::DoRedraw() { // Draw selected marker type as current one. TGedSelect::DoRedraw(); Int_t x, y; UInt_t w, h; if (IsEnabled()) { // pattern rectangle x = fBorderWidth + 2; y = fBorderWidth + 2; // 1; h = fHeight - (fBorderWidth * 2) - 4; // -3; // 14 w = h; if (fState == kButtonDown) { ++x; ++y; } gVirtualX->DrawRectangle(fId, GetShadowGC()(), x, y, w - 1, h - 1); if (fPicture != 0) fPicture->Draw(fId, fDrawGC->GetGC(), x + 1, y + 1); } else { // sunken rectangle x = fBorderWidth + 2; y = fBorderWidth + 2; // 1; w = 42; h = fHeight - (fBorderWidth * 2) - 4; // 3; Draw3dRectangle(kSunkenFrame, x, y, w, h); } } //_____________________________________________________________________________ void TGedMarkerSelect::SetMarkerStyle(Style_t markerStyle) { // Set marker. fMarkerStyle = markerStyle; gClient->NeedRedraw(this); if (fPicture) { gClient->FreePicture(fPicture); fPicture = 0; } MarkerDescription_t *md = GetMarkerByNumber(fMarkerStyle); if (md) fPicture = gClient->GetPicture(md->fFilename); MarkerSelected(fMarkerStyle); } //______________________________________________________________________________ void TGedMarkerSelect::SavePrimitive(ostream &out, Option_t * /*= ""*/) { // Save the pattern select widget as a C++ statement(s) on output stream out out <<" TGedMarkerSelect *"; out << GetName() << " = new TGedMarkerSelect(" << fParent->GetName() << "," << fMarkerStyle << "," << WidgetId() << ");" << endl; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: baside3.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2004-07-23 12:08:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _BASIDE3_HXX #define _BASIDE3_HXX #ifndef _SVHEADER_HXX //#include <svheader.hxx> #endif #include <bastypes.hxx> #include <svtools/undo.hxx> #ifndef _COM_SUN_STAR_SCRIPT_XLIBRYARYCONTAINER_HPP_ #include <com/sun/star/script/XLibraryContainer.hpp> #endif class StarBASIC; class SfxItemSet; class DlgEditor; class DlgEdModel; class DlgEdPage; class DlgEdView; class SfxUndoManager; class DialogWindow: public IDEBaseWindow { private: DlgEditor* pEditor; SfxUndoManager* pUndoMgr; Link aOldNotifyUndoActionHdl; protected: virtual void Paint( const Rectangle& ); virtual void Resize(); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void LoseFocus(); DECL_LINK( NotifyUndoActionHdl, SfxUndoAction * ); virtual void DoInit(); virtual void DoScroll( ScrollBar* pCurScrollBar ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); void InitSettings(BOOL bFont,BOOL bForeground,BOOL bBackground); public: TYPEINFO(); DialogWindow( Window* pParent, SfxObjectShell* pShell, String aLibName, String aName, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xDialogModel ); DialogWindow( DialogWindow* pCurView ); ~DialogWindow(); virtual void ExecuteCommand( SfxRequest& rReq ); virtual void GetState( SfxItemSet& ); DlgEditor* GetEditor() const { return pEditor; } ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > GetDialog() const; DlgEdModel* GetModel() const; DlgEdPage* GetPage() const; DlgEdView* GetView() const; BOOL RenameDialog( const String& rNewName ); void DisableBrowser(); void UpdateBrowser(); virtual String GetTitle(); virtual BasicEntryDescriptor CreateEntryDescriptor(); virtual void SetReadOnly( BOOL bReadOnly ); virtual BOOL IsReadOnly(); virtual void StoreData(); virtual BOOL IsModified(); virtual BOOL IsPasteAllowed(); virtual SfxUndoManager* GetUndoManager(); virtual void PrintData( Printer* pPrinter ); virtual void Deactivating(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible(); }; #endif // _BASIDE3_HXX <commit_msg>INTEGRATION: CWS gcc4fwdecl (1.4.110); FILE MERGED 2005/06/01 16:09:16 pmladek 1.4.110.1: #i50058# Fixed forward declarations for gcc4 in basctl<commit_after>/************************************************************************* * * $RCSfile: baside3.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2005-06-14 16:35:07 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _BASIDE3_HXX #define _BASIDE3_HXX #ifndef _SVHEADER_HXX //#include <svheader.hxx> #endif #include <bastypes.hxx> #include <svtools/undo.hxx> #ifndef _COM_SUN_STAR_SCRIPT_XLIBRYARYCONTAINER_HPP_ #include <com/sun/star/script/XLibraryContainer.hpp> #endif class Printer; class StarBASIC; class SfxItemSet; class DlgEditor; class DlgEdModel; class DlgEdPage; class DlgEdView; class SfxUndoManager; class DialogWindow: public IDEBaseWindow { private: DlgEditor* pEditor; SfxUndoManager* pUndoMgr; Link aOldNotifyUndoActionHdl; protected: virtual void Paint( const Rectangle& ); virtual void Resize(); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void LoseFocus(); DECL_LINK( NotifyUndoActionHdl, SfxUndoAction * ); virtual void DoInit(); virtual void DoScroll( ScrollBar* pCurScrollBar ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); void InitSettings(BOOL bFont,BOOL bForeground,BOOL bBackground); public: TYPEINFO(); DialogWindow( Window* pParent, SfxObjectShell* pShell, String aLibName, String aName, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xDialogModel ); DialogWindow( DialogWindow* pCurView ); ~DialogWindow(); virtual void ExecuteCommand( SfxRequest& rReq ); virtual void GetState( SfxItemSet& ); DlgEditor* GetEditor() const { return pEditor; } ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > GetDialog() const; DlgEdModel* GetModel() const; DlgEdPage* GetPage() const; DlgEdView* GetView() const; BOOL RenameDialog( const String& rNewName ); void DisableBrowser(); void UpdateBrowser(); virtual String GetTitle(); virtual BasicEntryDescriptor CreateEntryDescriptor(); virtual void SetReadOnly( BOOL bReadOnly ); virtual BOOL IsReadOnly(); virtual void StoreData(); virtual BOOL IsModified(); virtual BOOL IsPasteAllowed(); virtual SfxUndoManager* GetUndoManager(); virtual void PrintData( Printer* pPrinter ); virtual void Deactivating(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible(); }; #endif // _BASIDE3_HXX <|endoftext|>
<commit_before> #include <map> #include <string> #include <ifstream> #include <cassert> #include <cstdint> #include <fcntl.h> #include <unistd.h> #include "partition/hash.h" // TODO: how to include this #include "partition_io.h" #include "edisense_types.h" using namespace std; static map<string, node_t> readHostsFile(string &hostnames) { map<string, node_t> host_to_id; ifstream ifs(hostnames); if (!ifs) { cerr << hostnames << " could not be opened for reading!" << endl; exit(1); } while(ifs) // host file is whitespace delimited { string host; ifs >> host; if (host_to_id.find(host) != host_to_id.end()) { cerr << "duplicate hostnames in file: " << host << endl; exit(1); } node_t node_id = hostToNodeId(host); host_to_id[host] = node_id; } ifs.close(); return host_to_id; } int main(int argc, char *argv[]) { if (argc != 5) { cerr << "Usage: ./generate_partition_table <hostnames file> <output file> <n_partitions> <n_replicas>" << endl; return 0; } string hostnames(argv[1]); string output_file(argv[2]); int n_partitions = atoi(argv[3]); int n_replicas = atoi(argv[4]); if (n_partitions <= 0 || n_replicas <= 0) // TODO: determine reasonable limits { cerr << "thats not cool... must set reasonable number of replacas and partitions" << endl; return 0; } map<string, node_t> host_to_id = readHostsFile(hostnames); int n_hosts = host_to_id.size(); if (n_hosts < n_replicas) { cerr << "there cannot be more replicas than hosts" << endl; return 0; } size_t partition_table_size = n_partitions * n_replicas * sizeof(node_t); // allocate partition table partition_t partition_table[partition_table_size]; int partition_table_idx = 0; bool more_partitions_to_allocate = true; while (more_partitions_to_allocate) { for (auto &kv : host_to_id) { partition_table[partition_table_idx] = kv.second; partition_table_idx++; if (partition_table_idx >= partition_table_size) { more_partitions_to_allocate = false; break; } } } writePartitionTable(output_file.c_str(), &partition_table, n_partitions, n_replicas); cout << "done writing partition_table: " << output_file << endl; }<commit_msg>fixed issue where not closing ifstreams/ofstreams<commit_after> #include <map> #include <string> #include <ifstream> #include <cassert> #include <cstdint> #include <fcntl.h> #include <unistd.h> #include "partition/hash.h" #include "partition/partition_io.h" #include "edisense_types.h" using namespace std; static map<string, node_t> readHostsFile(string &hostnames) { map<string, node_t> host_to_id; ifstream ifs(hostnames); if (!ifs) { cerr << hostnames << " could not be opened for reading!" << endl; exit(1); } while(ifs) // host file is whitespace delimited { string host; ifs >> host; if (host_to_id.find(host) != host_to_id.end()) { cerr << "duplicate hostnames in file: " << host << endl; exit(1); } node_t node_id = hostToNodeId(host); host_to_id[host] = node_id; } ifs.close(); return host_to_id; } int main(int argc, char *argv[]) { if (argc != 5) { cerr << "Usage: ./generate_partition_table <hostnames file> <output file> <n_partitions> <n_replicas>" << endl; return 0; } string hostnames(argv[1]); string output_file(argv[2]); int n_partitions = atoi(argv[3]); int n_replicas = atoi(argv[4]); if (n_partitions <= 0 || n_replicas <= 0) // TODO: determine reasonable limits { cerr << "thats not cool... must set reasonable number of replacas and partitions" << endl; return 0; } map<string, node_t> host_to_id = readHostsFile(hostnames); int n_hosts = host_to_id.size(); if (n_hosts < n_replicas) { cerr << "there cannot be more replicas than hosts" << endl; return 0; } size_t partition_table_size = n_partitions * n_replicas * sizeof(node_t); // allocate partition table partition_t partition_table[partition_table_size]; int partition_table_idx = 0; bool more_partitions_to_allocate = true; while (more_partitions_to_allocate) { for (auto &kv : host_to_id) { partition_table[partition_table_idx] = kv.second; partition_table_idx++; if (partition_table_idx >= partition_table_size) { more_partitions_to_allocate = false; break; } } } writePartitionTable(output_file.c_str(), &partition_table, n_partitions, n_replicas); cout << "done writing partition_table: " << output_file << endl; }<|endoftext|>
<commit_before>#include "connection.h" #include <QScriptValueIterator> namespace QJSTP { const QByteArray Connection::TERMINATOR = QByteArray::fromRawData("\0", 1); const QString Connection::HANDSHAKE = "handshake"; const QString Connection::CALL = "call"; const QString Connection::CALL_BACK = "callback"; const QString Connection::EVENT = "event"; const QString Connection::INSPECT = "inspect"; //const QString Connection::STATE = "state"; //const QString Connection::STREAM = "stream"; //const QString Connection::HEALTH = "health"; QByteArray getMessage(QString type, quint64 id); QByteArray getMessage(QString type, quint64 id, QString name); QByteArray getMessage(QString type, quint64 id, QScriptValue parameters); QByteArray getMessage(QString type, quint64 id, QString name, QScriptValue parameters); QByteArray getMessage(QString type, quint64 id, QString interface, QString method); Connection::Connection(QString address, quint16 port) : callbacks(), socket(this) { connect(socket, SIGNAL(connected()), this, SLOT(onConnected())); connect(socket, SIGNAL(readyRead()), this, SLOT(onData())); // connect(socket, SIGNAL(error(QAbstractSocket::SocketError)()), this, SLOT(onError(QAbstractSocket::SocketError))); connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected())); socket->connectToHost(address, port); } void Connection::call(QString interface, QString method, QScriptValue parameters, handler callback) { } void Connection::callback(quint64 id, QScriptValue parameters) { } void Connection::event(QString interface, QString method, QScriptValue parameters, QList <handler> callbacks) { } void Connection::handshake(QString name, QScriptValue parameters, handler callback) { QByteArray message; if (parameters.isNull() || parameters.isUndefined()) { message = getMessage(HANDSHAKE, packageId, name); } else { message = getMessage(HANDSHAKE, packageId, name, parameters); } socket->write(message); callbacks.insert(packageId, { callback }); packageId++; } void Connection::inspect(QString interface, handler callback) { } void Connection::onHandshake(QScriptValue parameters) { } void Connection::onCall(QScriptValue parameters) { } void Connection::onCallback(QScriptValue parameters) { } void Connection::onEvent(QScriptValue parameters) { } void Connection::onInspect(QScriptValue parameters) { } void Connection::onConnected() { } void Connection::onData() { buffer.append(socket->readAll()); int index = -1; while((index = buffer.indexOf(TERMINATOR)) > 0) { QByteArray message = buffer.mid(0, index); buffer.remove(0, index); QScriptValue package = Parser::parse(message); QString packageType; if (package.property(HANDSHAKE).isValid()) { onHandshake(package); packageType = HANDSHAKE; } else if (package.property(CALL).isValid()) { onCall(package); packageType = CALL; } else if (package.property(CALL_BACK).isValid()) { onCallback(package); packageType = CALL_BACK; } else if (package.property(EVENT).isValid()) { onEvent(package); packageType = EVENT; } else if (package.property(INSPECT).isValid()) { onInspect(package); packageType = INSPECT; } for (auto func : callbacks.value(package.property(packageType).property(0).toInt32())) { func(package); } } } void Connection::onDisconnected() { } void Connection::onError(QAbstractSocket::SocketError socketError) { } QByteArray getMessage(QString type, quint64 id) { QByteArray message = "{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + "]}" + Connection::TERMINATOR; return message; } QByteArray getMessage(QString type, quint64 id, QString name) { return QByteArray("{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + ",'" + name.toUtf8() + "']}" + Connection::TERMINATOR); } QByteArray getMessage(QString type, quint64 id, QString name, QScriptValue parameters) { return QByteArray("{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + ",'" + name.toUtf8() + "']," + Parser::stringify(parameters).toUtf8() + "}" + Connection::TERMINATOR); } QByteArray getMessage(QString type, quint64 id, QScriptValue parameters) { } QByteArray getMessage(QString type, quint64 id, QString interface, QString method) { } } <commit_msg>Added possibility to use SSL<commit_after>#include "connection.h" #include <QSslSocket> #include <QScriptValueIterator> namespace QJSTP { const QByteArray Connection::TERMINATOR = QByteArray::fromRawData("\0", 1); const QString Connection::HANDSHAKE = "handshake"; const QString Connection::CALL = "call"; const QString Connection::CALL_BACK = "callback"; const QString Connection::EVENT = "event"; const QString Connection::INSPECT = "inspect"; //const QString Connection::STATE = "state"; //const QString Connection::STREAM = "stream"; //const QString Connection::HEALTH = "health"; QByteArray getMessage(QString type, quint64 id); QByteArray getMessage(QString type, quint64 id, QString name); QByteArray getMessage(QString type, quint64 id, QScriptValue parameters); QByteArray getMessage(QString type, quint64 id, QString name, QScriptValue parameters); QByteArray getMessage(QString type, quint64 id, QString interface, QString method); Connection::Connection(QString address, quint16 port, bool useSSL) : callbacks() { if (useSSL) { socket = new QSslSocket(this); } else { socket = new QTcpSocket(this); } connect(socket, SIGNAL(connected()), this, SLOT(onConnected())); connect(socket, SIGNAL(readyRead()), this, SLOT(onData())); // connect(socket, SIGNAL(error(QAbstractSocket::SocketError)()), this, SLOT(onError(QAbstractSocket::SocketError))); connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected())); socket->connectToHost(address, port); } void Connection::call(QString interface, QString method, QScriptValue parameters, handler callback) { } void Connection::callback(quint64 id, QScriptValue parameters) { } void Connection::event(QString interface, QString method, QScriptValue parameters, QList <handler> callbacks) { } void Connection::handshake(QString name, QScriptValue parameters, handler callback) { QByteArray message; if (parameters.isNull() || parameters.isUndefined()) { message = getMessage(HANDSHAKE, packageId, name); } else { message = getMessage(HANDSHAKE, packageId, name, parameters); } socket->write(message); callbacks.insert(packageId, { callback }); packageId++; } void Connection::inspect(QString interface, handler callback) { } void Connection::onHandshake(QScriptValue parameters) { } void Connection::onCall(QScriptValue parameters) { } void Connection::onCallback(QScriptValue parameters) { } void Connection::onEvent(QScriptValue parameters) { } void Connection::onInspect(QScriptValue parameters) { } void Connection::onConnected() { } void Connection::onData() { buffer.append(socket->readAll()); int index = -1; while((index = buffer.indexOf(TERMINATOR)) > 0) { QByteArray message = buffer.mid(0, index); buffer.remove(0, index); QScriptValue package = Parser::parse(message); QString packageType; if (package.property(HANDSHAKE).isValid()) { onHandshake(package); packageType = HANDSHAKE; } else if (package.property(CALL).isValid()) { onCall(package); packageType = CALL; } else if (package.property(CALL_BACK).isValid()) { onCallback(package); packageType = CALL_BACK; } else if (package.property(EVENT).isValid()) { onEvent(package); packageType = EVENT; } else if (package.property(INSPECT).isValid()) { onInspect(package); packageType = INSPECT; } for (auto func : callbacks.value(package.property(packageType).property(0).toInt32())) { func(package); } } } void Connection::onDisconnected() { } void Connection::onError(QAbstractSocket::SocketError socketError) { } QByteArray getMessage(QString type, quint64 id) { QByteArray message = "{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + "]}" + Connection::TERMINATOR; return message; } QByteArray getMessage(QString type, quint64 id, QString name) { return QByteArray("{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + ",'" + name.toUtf8() + "']}" + Connection::TERMINATOR); } QByteArray getMessage(QString type, quint64 id, QString name, QScriptValue parameters) { return QByteArray("{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + ",'" + name.toUtf8() + "']," + Parser::stringify(parameters).toUtf8() + "}" + Connection::TERMINATOR); } QByteArray getMessage(QString type, quint64 id, QScriptValue parameters) { } QByteArray getMessage(QString type, quint64 id, QString interface, QString method) { } } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android 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 "base/test/test_task_runner.h" #include <stdio.h> #include <unistd.h> #include <chrono> #include "base/logging.h" // TODO: the current implementation quite hacky as it keeps waking up every 1ms. namespace perfetto { namespace base { namespace { constexpr int kFileDescriptorWatchTimeoutMs = 100; } // namespace TestTaskRunner::TestTaskRunner() = default; TestTaskRunner::~TestTaskRunner() { PERFETTO_DCHECK(task_queue_.empty()); } void TestTaskRunner::Run() { for (;;) RunUntilIdle(); } void TestTaskRunner::RunUntilIdle() { do { QueueFileDescriptorWatches(/* blocking = */ task_queue_.empty()); } while (RunOneTask()); } void TestTaskRunner::RunUntilCheckpoint(const std::string& checkpoint, int timeout_ms) { if (checkpoints_.count(checkpoint) == 0) { fprintf(stderr, "[TestTaskRunner] Checkpoint \"%s\" does not exist.\n", checkpoint.c_str()); abort(); } auto tstart = std::chrono::system_clock::now(); auto deadline = tstart + std::chrono::milliseconds(timeout_ms); while (!checkpoints_[checkpoint]) { QueueFileDescriptorWatches(/* blocking = */ task_queue_.empty()); RunOneTask(); if (std::chrono::system_clock::now() > deadline) { fprintf(stderr, "[TestTaskRunner] Failed to reach checkpoint \"%s\"\n", checkpoint.c_str()); abort(); } } } bool TestTaskRunner::RunOneTask() { if (task_queue_.empty()) return false; std::function<void()> closure = std::move(task_queue_.front()); task_queue_.pop_front(); closure(); return true; } std::function<void()> TestTaskRunner::CreateCheckpoint( const std::string& checkpoint) { PERFETTO_DCHECK(checkpoints_.count(checkpoint) == 0); auto checkpoint_iter = checkpoints_.emplace(checkpoint, false); return [checkpoint_iter] { checkpoint_iter.first->second = true; }; } void TestTaskRunner::QueueFileDescriptorWatches(bool blocking) { uint32_t timeout_ms = blocking ? kFileDescriptorWatchTimeoutMs : 0; struct timeval timeout; timeout.tv_usec = (timeout_ms % 1000) * 1000L; timeout.tv_sec = static_cast<time_t>(timeout_ms / 1000); int max_fd = 0; fd_set fds_in = {}; fd_set fds_err = {}; for (const auto& it : watched_fds_) { FD_SET(it.first, &fds_in); FD_SET(it.first, &fds_err); max_fd = std::max(max_fd, it.first); } int res = select(max_fd + 1, &fds_in, nullptr, &fds_err, &timeout); if (res < 0) { perror("select() failed"); abort(); } if (res == 0) return; // timeout for (int fd = 0; fd <= max_fd; ++fd) { if (!FD_ISSET(fd, &fds_in) && !FD_ISSET(fd, &fds_err)) { continue; } auto fd_and_callback = watched_fds_.find(fd); PERFETTO_DCHECK(fd_and_callback != watched_fds_.end()); if (fd_watch_task_queued_[fd]) continue; auto callback = fd_and_callback->second; task_queue_.emplace_back([this, callback, fd]() { fd_watch_task_queued_[fd] = false; callback(); }); fd_watch_task_queued_[fd] = true; } } // TaskRunner implementation. void TestTaskRunner::PostTask(std::function<void()> closure) { task_queue_.emplace_back(std::move(closure)); } void TestTaskRunner::AddFileDescriptorWatch(int fd, std::function<void()> callback) { PERFETTO_DCHECK(fd >= 0); PERFETTO_DCHECK(watched_fds_.count(fd) == 0); watched_fds_.emplace(fd, std::move(callback)); fd_watch_task_queued_[fd] = false; } void TestTaskRunner::RemoveFileDescriptorWatch(int fd) { PERFETTO_DCHECK(fd >= 0); PERFETTO_DCHECK(watched_fds_.count(fd) == 1); watched_fds_.erase(fd); fd_watch_task_queued_.erase(fd); } } // namespace base } // namespace perfetto <commit_msg>Fix build: remove DCHECK on TestTaskRunner am: 8242ad440a am: 238f1cf3e0 am: 7ccef406b7<commit_after>/* * Copyright (C) 2017 The Android 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 "base/test/test_task_runner.h" #include <stdio.h> #include <unistd.h> #include <chrono> #include "base/logging.h" // TODO: the current implementation quite hacky as it keeps waking up every 1ms. namespace perfetto { namespace base { namespace { constexpr int kFileDescriptorWatchTimeoutMs = 100; } // namespace TestTaskRunner::TestTaskRunner() = default; TestTaskRunner::~TestTaskRunner() = default; void TestTaskRunner::Run() { for (;;) RunUntilIdle(); } void TestTaskRunner::RunUntilIdle() { do { QueueFileDescriptorWatches(/* blocking = */ task_queue_.empty()); } while (RunOneTask()); } void TestTaskRunner::RunUntilCheckpoint(const std::string& checkpoint, int timeout_ms) { if (checkpoints_.count(checkpoint) == 0) { fprintf(stderr, "[TestTaskRunner] Checkpoint \"%s\" does not exist.\n", checkpoint.c_str()); abort(); } auto tstart = std::chrono::system_clock::now(); auto deadline = tstart + std::chrono::milliseconds(timeout_ms); while (!checkpoints_[checkpoint]) { QueueFileDescriptorWatches(/* blocking = */ task_queue_.empty()); RunOneTask(); if (std::chrono::system_clock::now() > deadline) { fprintf(stderr, "[TestTaskRunner] Failed to reach checkpoint \"%s\"\n", checkpoint.c_str()); abort(); } } } bool TestTaskRunner::RunOneTask() { if (task_queue_.empty()) return false; std::function<void()> closure = std::move(task_queue_.front()); task_queue_.pop_front(); closure(); return true; } std::function<void()> TestTaskRunner::CreateCheckpoint( const std::string& checkpoint) { PERFETTO_DCHECK(checkpoints_.count(checkpoint) == 0); auto checkpoint_iter = checkpoints_.emplace(checkpoint, false); return [checkpoint_iter] { checkpoint_iter.first->second = true; }; } void TestTaskRunner::QueueFileDescriptorWatches(bool blocking) { uint32_t timeout_ms = blocking ? kFileDescriptorWatchTimeoutMs : 0; struct timeval timeout; timeout.tv_usec = (timeout_ms % 1000) * 1000L; timeout.tv_sec = static_cast<time_t>(timeout_ms / 1000); int max_fd = 0; fd_set fds_in = {}; fd_set fds_err = {}; for (const auto& it : watched_fds_) { FD_SET(it.first, &fds_in); FD_SET(it.first, &fds_err); max_fd = std::max(max_fd, it.first); } int res = select(max_fd + 1, &fds_in, nullptr, &fds_err, &timeout); if (res < 0) { perror("select() failed"); abort(); } if (res == 0) return; // timeout for (int fd = 0; fd <= max_fd; ++fd) { if (!FD_ISSET(fd, &fds_in) && !FD_ISSET(fd, &fds_err)) { continue; } auto fd_and_callback = watched_fds_.find(fd); PERFETTO_DCHECK(fd_and_callback != watched_fds_.end()); if (fd_watch_task_queued_[fd]) continue; auto callback = fd_and_callback->second; task_queue_.emplace_back([this, callback, fd]() { fd_watch_task_queued_[fd] = false; callback(); }); fd_watch_task_queued_[fd] = true; } } // TaskRunner implementation. void TestTaskRunner::PostTask(std::function<void()> closure) { task_queue_.emplace_back(std::move(closure)); } void TestTaskRunner::AddFileDescriptorWatch(int fd, std::function<void()> callback) { PERFETTO_DCHECK(fd >= 0); PERFETTO_DCHECK(watched_fds_.count(fd) == 0); watched_fds_.emplace(fd, std::move(callback)); fd_watch_task_queued_[fd] = false; } void TestTaskRunner::RemoveFileDescriptorWatch(int fd) { PERFETTO_DCHECK(fd >= 0); PERFETTO_DCHECK(watched_fds_.count(fd) == 1); watched_fds_.erase(fd); fd_watch_task_queued_.erase(fd); } } // namespace base } // namespace perfetto <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "setupgenerator.h" #include "shellgenerator.h" #include "reporthandler.h" #include "fileout.h" //#define Q_SCRIPT_LAZY_GENERATOR void SetupGenerator::addClass(const QString& package, const AbstractMetaClass *cls) { packHash[package].append(cls); } void maybeDeclareMetaType(QTextStream &stream, const QString &typeName, QSet<QString> &registeredTypeNames); bool hasDefaultConstructor(const AbstractMetaClass *meta_class); void SetupGenerator::generate() { AbstractMetaClassList classes_with_polymorphic_id; { QHashIterator<QString, QList<const AbstractMetaClass*> > pack(packHash); while (pack.hasNext()) { pack.next(); QList<const AbstractMetaClass*> list = pack.value(); foreach (const AbstractMetaClass *cls, list) { if (cls->typeEntry()->isPolymorphicBase()) { classes_with_polymorphic_id.append((AbstractMetaClass*)cls); } } } } QHashIterator<QString, QList<const AbstractMetaClass*> > pack(packHash); while (pack.hasNext()) { pack.next(); QList<const AbstractMetaClass*> list = pack.value(); if (list.isEmpty()) continue; QString packKey = pack.key(); QString packName = pack.key(); QStringList components = packName.split("_"); if ((components.size() > 2) && (components.at(0) == "com") && (components.at(1) == "trolltech")) { // kill com.trolltech in key components.removeAt(0); components.removeAt(0); } QString shortPackName; foreach (QString comp, components) { comp[0] = comp[0].toUpper(); shortPackName += comp; } // add missing camel case (workaround..) if (shortPackName == "QtWebkit") { shortPackName = "QtWebKit"; } else if (shortPackName == "QtXmlpatterns") { shortPackName = "QtXmlPatterns"; } else if (shortPackName == "QtOpengl") { shortPackName = "QtOpenGL"; } else if (shortPackName == "QtUitools") { shortPackName = "QtUiTools"; } { FileOut initFile(m_out_dir + "/generated_cpp/" + packName + "/" + packKey + "_init.cpp"); QTextStream &s = initFile.stream; s << "#include <PythonQt.h>" << endl; for (int i=0; i<(list.count()+MAX_CLASSES_PER_FILE-1) / MAX_CLASSES_PER_FILE; i++) { s << "#include \"" << packKey << QString::number(i) << ".h\"" << endl; } s << endl; QStringList polymorphicHandlers; if (!packName.endsWith("_builtin")) { polymorphicHandlers = writePolymorphicHandler(s, list.at(0)->package(), classes_with_polymorphic_id); s << endl; } // declare individual class creation functions s << "void PythonQt_init_" << shortPackName << "() {" << endl; if (shortPackName.endsWith("Builtin")) { shortPackName = shortPackName.mid(shortPackName.length()-strlen("builtin")); } QStringList cppClassNames; foreach (const AbstractMetaClass *cls, list) { QString shellCreator; if (cls->generateShellClass()) { shellCreator = ", PythonQtSetInstanceWrapperOnShell<" + ShellGenerator::shellClassName(cls) + ">"; } if (cls->isQObject()) { s << "PythonQt::self()->registerClass(&" << cls->qualifiedCppName() << "::staticMetaObject, \"" << shortPackName <<"\", PythonQtCreateObject<PythonQtWrapper_" << cls->name() << ">" << shellCreator << ");" << endl; } else { QString baseName = cls->baseClass()?cls->baseClass()->qualifiedCppName():""; s << "PythonQt::self()->registerCPPClass(\""<< cls->qualifiedCppName() << "\", \"" << baseName << "\", \"" << shortPackName <<"\", PythonQtCreateObject<PythonQtWrapper_" << cls->name() << ">" << shellCreator << ");" << endl; } foreach(AbstractMetaClass* interface, cls->interfaces()) { // the interface might be our own class... (e.g. QPaintDevice) if (interface->qualifiedCppName() != cls->qualifiedCppName()) { s << "PythonQt::self()->addParentClass(\""<< cls->qualifiedCppName() << "\", \"" << interface->qualifiedCppName() << "\",PythonQtUpcastingOffset<" << cls->qualifiedCppName() <<","<<interface->qualifiedCppName()<<">());" << endl; } } } s << endl; foreach (QString handler, polymorphicHandlers) { s << "PythonQt::self()->addPolymorphicHandler(\""<< handler << "\", polymorphichandler_" << handler << ");" << endl; } s << "}"; s << endl; } } } QStringList SetupGenerator::writePolymorphicHandler(QTextStream &s, const QString &package, const AbstractMetaClassList &classes) { QStringList handlers; foreach (AbstractMetaClass *cls, classes) { const ComplexTypeEntry *centry = cls->typeEntry(); if (!centry->isPolymorphicBase()) continue; bool isGraphicsItem = (cls->qualifiedCppName()=="QGraphicsItem"); AbstractMetaClassList classList = this->classes(); bool first = true; foreach (AbstractMetaClass *clazz, classList) { bool inherits = false; if (isGraphicsItem) { foreach(AbstractMetaClass* interfaze, clazz->interfaces()) { if (interfaze->qualifiedCppName()=="QGraphicsItem") { inherits = true; break; } } } else { inherits = clazz->inheritsFrom(cls); } if (clazz->package() == package && inherits) { if (!clazz->typeEntry()->polymorphicIdValue().isEmpty() || isGraphicsItem) { // On first find, open the function if (first) { first = false; QString handler = cls->name(); handlers.append(handler); s << "static void* polymorphichandler_" << handler << "(const void *ptr, char **class_name)" << endl << "{" << endl << " Q_ASSERT(ptr != 0);" << endl << " " << cls->qualifiedCppName() << " *object = (" << cls->qualifiedCppName() << " *)ptr;" << endl; } // For each, add case label QString polyId = clazz->typeEntry()->polymorphicIdValue(); if (isGraphicsItem) { polyId = "%1->type() == " + clazz->qualifiedCppName() + "::Type"; } s << " if (" << polyId.replace("%1", "object") << ") {" << endl << " *class_name = \"" << clazz->name() << "\";" << endl << " return (" << clazz->qualifiedCppName() << "*)object;" << endl << " }" << endl; } else { QString warning = QString("class '%1' inherits from polymorphic class '%2', but has no polymorphic id set") .arg(clazz->name()) .arg(cls->name()); ReportHandler::warning(warning); } } } // Close the function if it has been opened if (!first) { s << " return NULL;" << endl << "}" << endl; } } return handlers; } <commit_msg>fixed builtin package name<commit_after>/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "setupgenerator.h" #include "shellgenerator.h" #include "reporthandler.h" #include "fileout.h" //#define Q_SCRIPT_LAZY_GENERATOR void SetupGenerator::addClass(const QString& package, const AbstractMetaClass *cls) { packHash[package].append(cls); } void maybeDeclareMetaType(QTextStream &stream, const QString &typeName, QSet<QString> &registeredTypeNames); bool hasDefaultConstructor(const AbstractMetaClass *meta_class); void SetupGenerator::generate() { AbstractMetaClassList classes_with_polymorphic_id; { QHashIterator<QString, QList<const AbstractMetaClass*> > pack(packHash); while (pack.hasNext()) { pack.next(); QList<const AbstractMetaClass*> list = pack.value(); foreach (const AbstractMetaClass *cls, list) { if (cls->typeEntry()->isPolymorphicBase()) { classes_with_polymorphic_id.append((AbstractMetaClass*)cls); } } } } QHashIterator<QString, QList<const AbstractMetaClass*> > pack(packHash); while (pack.hasNext()) { pack.next(); QList<const AbstractMetaClass*> list = pack.value(); if (list.isEmpty()) continue; QString packKey = pack.key(); QString packName = pack.key(); QStringList components = packName.split("_"); if ((components.size() > 2) && (components.at(0) == "com") && (components.at(1) == "trolltech")) { // kill com.trolltech in key components.removeAt(0); components.removeAt(0); } QString shortPackName; foreach (QString comp, components) { comp[0] = comp[0].toUpper(); shortPackName += comp; } // add missing camel case (workaround..) if (shortPackName == "QtWebkit") { shortPackName = "QtWebKit"; } else if (shortPackName == "QtXmlpatterns") { shortPackName = "QtXmlPatterns"; } else if (shortPackName == "QtOpengl") { shortPackName = "QtOpenGL"; } else if (shortPackName == "QtUitools") { shortPackName = "QtUiTools"; } { FileOut initFile(m_out_dir + "/generated_cpp/" + packName + "/" + packKey + "_init.cpp"); QTextStream &s = initFile.stream; s << "#include <PythonQt.h>" << endl; for (int i=0; i<(list.count()+MAX_CLASSES_PER_FILE-1) / MAX_CLASSES_PER_FILE; i++) { s << "#include \"" << packKey << QString::number(i) << ".h\"" << endl; } s << endl; QStringList polymorphicHandlers; if (!packName.endsWith("_builtin")) { polymorphicHandlers = writePolymorphicHandler(s, list.at(0)->package(), classes_with_polymorphic_id); s << endl; } // declare individual class creation functions s << "void PythonQt_init_" << shortPackName << "() {" << endl; if (shortPackName.endsWith("Builtin")) { shortPackName = shortPackName.mid(0, shortPackName.length()-strlen("builtin")); } QStringList cppClassNames; foreach (const AbstractMetaClass *cls, list) { QString shellCreator; if (cls->generateShellClass()) { shellCreator = ", PythonQtSetInstanceWrapperOnShell<" + ShellGenerator::shellClassName(cls) + ">"; } if (cls->isQObject()) { s << "PythonQt::self()->registerClass(&" << cls->qualifiedCppName() << "::staticMetaObject, \"" << shortPackName <<"\", PythonQtCreateObject<PythonQtWrapper_" << cls->name() << ">" << shellCreator << ");" << endl; } else { QString baseName = cls->baseClass()?cls->baseClass()->qualifiedCppName():""; s << "PythonQt::self()->registerCPPClass(\""<< cls->qualifiedCppName() << "\", \"" << baseName << "\", \"" << shortPackName <<"\", PythonQtCreateObject<PythonQtWrapper_" << cls->name() << ">" << shellCreator << ");" << endl; } foreach(AbstractMetaClass* interface, cls->interfaces()) { // the interface might be our own class... (e.g. QPaintDevice) if (interface->qualifiedCppName() != cls->qualifiedCppName()) { s << "PythonQt::self()->addParentClass(\""<< cls->qualifiedCppName() << "\", \"" << interface->qualifiedCppName() << "\",PythonQtUpcastingOffset<" << cls->qualifiedCppName() <<","<<interface->qualifiedCppName()<<">());" << endl; } } } s << endl; foreach (QString handler, polymorphicHandlers) { s << "PythonQt::self()->addPolymorphicHandler(\""<< handler << "\", polymorphichandler_" << handler << ");" << endl; } s << "}"; s << endl; } } } QStringList SetupGenerator::writePolymorphicHandler(QTextStream &s, const QString &package, const AbstractMetaClassList &classes) { QStringList handlers; foreach (AbstractMetaClass *cls, classes) { const ComplexTypeEntry *centry = cls->typeEntry(); if (!centry->isPolymorphicBase()) continue; bool isGraphicsItem = (cls->qualifiedCppName()=="QGraphicsItem"); AbstractMetaClassList classList = this->classes(); bool first = true; foreach (AbstractMetaClass *clazz, classList) { bool inherits = false; if (isGraphicsItem) { foreach(AbstractMetaClass* interfaze, clazz->interfaces()) { if (interfaze->qualifiedCppName()=="QGraphicsItem") { inherits = true; break; } } } else { inherits = clazz->inheritsFrom(cls); } if (clazz->package() == package && inherits) { if (!clazz->typeEntry()->polymorphicIdValue().isEmpty() || isGraphicsItem) { // On first find, open the function if (first) { first = false; QString handler = cls->name(); handlers.append(handler); s << "static void* polymorphichandler_" << handler << "(const void *ptr, char **class_name)" << endl << "{" << endl << " Q_ASSERT(ptr != 0);" << endl << " " << cls->qualifiedCppName() << " *object = (" << cls->qualifiedCppName() << " *)ptr;" << endl; } // For each, add case label QString polyId = clazz->typeEntry()->polymorphicIdValue(); if (isGraphicsItem) { polyId = "%1->type() == " + clazz->qualifiedCppName() + "::Type"; } s << " if (" << polyId.replace("%1", "object") << ") {" << endl << " *class_name = \"" << clazz->name() << "\";" << endl << " return (" << clazz->qualifiedCppName() << "*)object;" << endl << " }" << endl; } else { QString warning = QString("class '%1' inherits from polymorphic class '%2', but has no polymorphic id set") .arg(clazz->name()) .arg(cls->name()); ReportHandler::warning(warning); } } } // Close the function if it has been opened if (!first) { s << " return NULL;" << endl << "}" << endl; } } return handlers; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "shellgenerator.h" #include "reporthandler.h" #include "metaqtscript.h" bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const { uint cg = meta_class->typeEntry()->codeGeneration(); if (meta_class->name().startsWith("QtScript")) return false; if (meta_class->name().startsWith("QFuture")) return false; if (meta_class->name().startsWith("Global")) return false; if (meta_class->name().startsWith("QStyleOptionComplex")) return false; if (meta_class->name().startsWith("QTextLayout")) return false; //if (meta_class->name().startsWith("QTextStream")) return false; // because of >> operators //if (meta_class->name().startsWith("QDataStream")) return false; // " return ((cg & TypeEntry::GenerateCode) != 0); } void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options) { if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) { s << type->originalTypeDescription(); return; } if (type->isArray()) { writeTypeInfo(s, type->arrayElementType(), options); if (options & ArrayAsPointer) { s << "*"; } else { s << "[" << type->arrayElementCount() << "]"; } return; } const TypeEntry *te = type->typeEntry(); if (type->isConstant() && !(options & ExcludeConst)) s << "const "; if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) { s << "int"; } else if (te->isFlags()) { s << ((FlagsTypeEntry *) te)->originalName(); } else { s << fixCppTypeName(te->qualifiedCppName()); } if (type->instantiations().size() > 0 && (!type->isContainer() || (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) { s << '<'; QList<AbstractMetaType *> args = type->instantiations(); bool nested_template = false; for (int i=0; i<args.size(); ++i) { if (i != 0) s << ", "; nested_template |= args.at(i)->isContainer(); writeTypeInfo(s, args.at(i)); } if (nested_template) s << ' '; s << '>'; } s << QString(type->indirections(), '*'); if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr)) s << "&"; if (type->isReference() && (options & ConvertReferenceToPtr)) { s << "*"; } if (!(options & SkipName)) s << ' '; } void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner, const AbstractMetaArgumentList &arguments, Option option, int numArguments) { if (numArguments < 0) numArguments = arguments.size(); for (int i=0; i<numArguments; ++i) { if (i != 0) s << ", "; AbstractMetaArgument *arg = arguments.at(i); writeTypeInfo(s, arg->type(), option); if (!(option & SkipName)) s << " " << arg->argumentName(); if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) { s << " = "; QString expr = arg->originalDefaultValueExpression(); if (expr != "0") { QString qualifier; if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) { qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier(); } else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) { qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier(); } if (!qualifier.isEmpty()) { s << qualifier << "::"; } } if (expr.contains("defaultConnection")) { expr.replace("defaultConnection","QSqlDatabase::defaultConnection"); } if (expr == "MediaSource()") { expr = "Phonon::MediaSource()"; } s << expr; } } } /*! * Writes the function \a meta_function signature to the textstream \a s. * * The \a name_prefix can be used to give the function name a prefix, * like "__public_" or "__override_" and \a classname_prefix can * be used to give the class name a prefix. * * The \a option flags can be used to tweak various parameters, such as * showing static, original vs renamed name, underscores for space etc. * * The \a extra_arguments list is a list of extra arguments on the * form "bool static_call". */ void ShellGenerator::writeFunctionSignature(QTextStream &s, const AbstractMetaFunction *meta_function, const AbstractMetaClass *implementor, const QString &name_prefix, Option option, const QString &classname_prefix, const QStringList &extra_arguments, int numArguments) { // ### remove the implementor AbstractMetaType *function_type = meta_function->type(); if ((option & SkipReturnType) == 0) { if (function_type) { writeTypeInfo(s, function_type, option); s << " "; } else if (!meta_function->isConstructor()) { s << "void "; } } if (implementor) { if (classname_prefix.isEmpty()) s << wrapperClassName(implementor) << "::"; else s << classname_prefix << implementor->name() << "::"; } QString function_name; if (option & OriginalName) function_name = meta_function->originalName(); else function_name = meta_function->name(); if (option & UnderscoreSpaces) function_name = function_name.replace(' ', '_'); if (meta_function->isConstructor()) function_name = meta_function->ownerClass()->name(); if (meta_function->isStatic() && (option & ShowStatic)) { function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name; } if (function_name.startsWith("operator")) { function_name = meta_function->name(); } s << name_prefix << function_name; if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction) s << "_setter"; else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction) s << "_getter"; s << "("; if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) { s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject"; if (meta_function->arguments().size() != 0) { s << ", "; } } writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments); // The extra arguments... for (int i=0; i<extra_arguments.size(); ++i) { if (i > 0 || meta_function->arguments().size() != 0) s << ", "; s << extra_arguments.at(i); } s << ")"; if (meta_function->isConstant()) s << " const"; } AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions = meta_class->queryFunctions( AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements ); AbstractMetaFunctionList functions2 = meta_class->queryFunctions( AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements ); QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions); foreach(AbstractMetaFunction* func, functions2) { set1.insert(func); } AbstractMetaFunctionList resultFunctions; foreach(AbstractMetaFunction* func, set1.toList()) { if (!func->isAbstract() && func->implementingClass()==meta_class) { resultFunctions << func; } } return resultFunctions; } AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions = meta_class->queryFunctions( AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible // | AbstractMetaClass::NotRemovedFromTargetLang ); return functions; } AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions; AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class); foreach(AbstractMetaFunction* func, functions1) { if (!func->isPublic() || func->isVirtual()) { functions << func; } } return functions; } /*! Writes the include defined by \a inc to \a stream. */ void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc) { if (inc.name.isEmpty()) return; if (inc.type == Include::TargetLangImport) return; stream << "#include "; if (inc.type == Include::IncludePath) stream << "<"; else stream << "\""; stream << inc.name; if (inc.type == Include::IncludePath) stream << ">"; else stream << "\""; stream << endl; } /*! Returns true if the given function \a fun is operator>>() or operator<<() that streams from/to a Q{Data,Text}Stream, false otherwise. */ bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun) { return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction) && (fun->arguments().size() == 1) && (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom")) || ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo")))); } bool ShellGenerator::isBuiltIn(const QString& name) { static QSet<QString> builtIn; if (builtIn.isEmpty()) { builtIn.insert("Qt"); builtIn.insert("QFont"); builtIn.insert("QPixmap"); builtIn.insert("QBrush"); builtIn.insert("QBitArray"); builtIn.insert("QPalette"); builtIn.insert("QPen"); builtIn.insert("QIcon"); builtIn.insert("QImage"); builtIn.insert("QPolygon"); builtIn.insert("QRegion"); builtIn.insert("QBitmap"); builtIn.insert("QCursor"); builtIn.insert("QColor"); builtIn.insert("QSizePolicy"); builtIn.insert("QKeySequence"); builtIn.insert("QTextLength"); builtIn.insert("QTextFormat"); builtIn.insert("QMatrix"); builtIn.insert("QDate"); builtIn.insert("QTime"); builtIn.insert("QDateTime"); builtIn.insert("QUrl"); builtIn.insert("QLocale"); builtIn.insert("QRect"); builtIn.insert("QRectF"); builtIn.insert("QSize"); builtIn.insert("QSizeF"); builtIn.insert("QLine"); builtIn.insert("QLineF"); builtIn.insert("QPoint"); builtIn.insert("QPointF"); builtIn.insert("QRegExp"); } return builtIn.contains(name); } <commit_msg>added alphabetic sorting<commit_after>/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "shellgenerator.h" #include "reporthandler.h" #include "metaqtscript.h" bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const { uint cg = meta_class->typeEntry()->codeGeneration(); if (meta_class->name().startsWith("QtScript")) return false; if (meta_class->name().startsWith("QFuture")) return false; if (meta_class->name().startsWith("Global")) return false; if (meta_class->name().startsWith("QStyleOptionComplex")) return false; if (meta_class->name().startsWith("QTextLayout")) return false; //if (meta_class->name().startsWith("QTextStream")) return false; // because of >> operators //if (meta_class->name().startsWith("QDataStream")) return false; // " return ((cg & TypeEntry::GenerateCode) != 0); } void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options) { if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) { s << type->originalTypeDescription(); return; } if (type->isArray()) { writeTypeInfo(s, type->arrayElementType(), options); if (options & ArrayAsPointer) { s << "*"; } else { s << "[" << type->arrayElementCount() << "]"; } return; } const TypeEntry *te = type->typeEntry(); if (type->isConstant() && !(options & ExcludeConst)) s << "const "; if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) { s << "int"; } else if (te->isFlags()) { s << ((FlagsTypeEntry *) te)->originalName(); } else { s << fixCppTypeName(te->qualifiedCppName()); } if (type->instantiations().size() > 0 && (!type->isContainer() || (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) { s << '<'; QList<AbstractMetaType *> args = type->instantiations(); bool nested_template = false; for (int i=0; i<args.size(); ++i) { if (i != 0) s << ", "; nested_template |= args.at(i)->isContainer(); writeTypeInfo(s, args.at(i)); } if (nested_template) s << ' '; s << '>'; } s << QString(type->indirections(), '*'); if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr)) s << "&"; if (type->isReference() && (options & ConvertReferenceToPtr)) { s << "*"; } if (!(options & SkipName)) s << ' '; } void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner, const AbstractMetaArgumentList &arguments, Option option, int numArguments) { if (numArguments < 0) numArguments = arguments.size(); for (int i=0; i<numArguments; ++i) { if (i != 0) s << ", "; AbstractMetaArgument *arg = arguments.at(i); writeTypeInfo(s, arg->type(), option); if (!(option & SkipName)) s << " " << arg->argumentName(); if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) { s << " = "; QString expr = arg->originalDefaultValueExpression(); if (expr != "0") { QString qualifier; if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) { qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier(); } else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) { qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier(); } if (!qualifier.isEmpty()) { s << qualifier << "::"; } } if (expr.contains("defaultConnection")) { expr.replace("defaultConnection","QSqlDatabase::defaultConnection"); } if (expr == "MediaSource()") { expr = "Phonon::MediaSource()"; } s << expr; } } } /*! * Writes the function \a meta_function signature to the textstream \a s. * * The \a name_prefix can be used to give the function name a prefix, * like "__public_" or "__override_" and \a classname_prefix can * be used to give the class name a prefix. * * The \a option flags can be used to tweak various parameters, such as * showing static, original vs renamed name, underscores for space etc. * * The \a extra_arguments list is a list of extra arguments on the * form "bool static_call". */ void ShellGenerator::writeFunctionSignature(QTextStream &s, const AbstractMetaFunction *meta_function, const AbstractMetaClass *implementor, const QString &name_prefix, Option option, const QString &classname_prefix, const QStringList &extra_arguments, int numArguments) { // ### remove the implementor AbstractMetaType *function_type = meta_function->type(); if ((option & SkipReturnType) == 0) { if (function_type) { writeTypeInfo(s, function_type, option); s << " "; } else if (!meta_function->isConstructor()) { s << "void "; } } if (implementor) { if (classname_prefix.isEmpty()) s << wrapperClassName(implementor) << "::"; else s << classname_prefix << implementor->name() << "::"; } QString function_name; if (option & OriginalName) function_name = meta_function->originalName(); else function_name = meta_function->name(); if (option & UnderscoreSpaces) function_name = function_name.replace(' ', '_'); if (meta_function->isConstructor()) function_name = meta_function->ownerClass()->name(); if (meta_function->isStatic() && (option & ShowStatic)) { function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name; } if (function_name.startsWith("operator")) { function_name = meta_function->name(); } s << name_prefix << function_name; if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction) s << "_setter"; else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction) s << "_getter"; s << "("; if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) { s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject"; if (meta_function->arguments().size() != 0) { s << ", "; } } writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments); // The extra arguments... for (int i=0; i<extra_arguments.size(); ++i) { if (i > 0 || meta_function->arguments().size() != 0) s << ", "; s << extra_arguments.at(i); } s << ")"; if (meta_function->isConstant()) s << " const"; } AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions = meta_class->queryFunctions( AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements ); AbstractMetaFunctionList functions2 = meta_class->queryFunctions( AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements ); QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions); foreach(AbstractMetaFunction* func, functions2) { set1.insert(func); } AbstractMetaFunctionList resultFunctions; foreach(AbstractMetaFunction* func, set1.toList()) { if (!func->isAbstract() && func->implementingClass()==meta_class) { resultFunctions << func; } } qStableSort(resultFunctions); return resultFunctions; } AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions = meta_class->queryFunctions( AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible // | AbstractMetaClass::NotRemovedFromTargetLang ); qStableSort(functions); return functions; } AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions; AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class); foreach(AbstractMetaFunction* func, functions1) { if (!func->isPublic() || func->isVirtual()) { functions << func; } } qStableSort(functions); return functions; } /*! Writes the include defined by \a inc to \a stream. */ void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc) { if (inc.name.isEmpty()) return; if (inc.type == Include::TargetLangImport) return; stream << "#include "; if (inc.type == Include::IncludePath) stream << "<"; else stream << "\""; stream << inc.name; if (inc.type == Include::IncludePath) stream << ">"; else stream << "\""; stream << endl; } /*! Returns true if the given function \a fun is operator>>() or operator<<() that streams from/to a Q{Data,Text}Stream, false otherwise. */ bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun) { return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction) && (fun->arguments().size() == 1) && (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom")) || ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo")))); } bool ShellGenerator::isBuiltIn(const QString& name) { static QSet<QString> builtIn; if (builtIn.isEmpty()) { builtIn.insert("Qt"); builtIn.insert("QFont"); builtIn.insert("QPixmap"); builtIn.insert("QBrush"); builtIn.insert("QBitArray"); builtIn.insert("QPalette"); builtIn.insert("QPen"); builtIn.insert("QIcon"); builtIn.insert("QImage"); builtIn.insert("QPolygon"); builtIn.insert("QRegion"); builtIn.insert("QBitmap"); builtIn.insert("QCursor"); builtIn.insert("QColor"); builtIn.insert("QSizePolicy"); builtIn.insert("QKeySequence"); builtIn.insert("QTextLength"); builtIn.insert("QTextFormat"); builtIn.insert("QMatrix"); builtIn.insert("QDate"); builtIn.insert("QTime"); builtIn.insert("QDateTime"); builtIn.insert("QUrl"); builtIn.insert("QLocale"); builtIn.insert("QRect"); builtIn.insert("QRectF"); builtIn.insert("QSize"); builtIn.insert("QSizeF"); builtIn.insert("QLine"); builtIn.insert("QLineF"); builtIn.insert("QPoint"); builtIn.insert("QPointF"); builtIn.insert("QRegExp"); } return builtIn.contains(name); } <|endoftext|>
<commit_before>/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file formatters/c_decorator.hpp * \author Andrey Semashev * \date 18.11.2012 * * The header contains implementation of C-style character decorators. */ #ifndef BOOST_LOG_EXPRESSIONS_FORMATTERS_C_DECORATOR_HPP_INCLUDED_ #define BOOST_LOG_EXPRESSIONS_FORMATTERS_C_DECORATOR_HPP_INCLUDED_ #include <limits> #include <boost/range/iterator_range_core.hpp> #include <boost/log/detail/config.hpp> #include <boost/log/detail/snprintf.hpp> #include <boost/log/expressions/formatters/char_decorator.hpp> #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace expressions { namespace aux { template< typename > struct c_decorator_traits; #ifdef BOOST_LOG_USE_CHAR template< > struct c_decorator_traits< char > { static boost::iterator_range< const char* const* > get_patterns() { static const char* const patterns[] = { "\\", "\a", "\b", "\f", "\n", "\r", "\t", "\v", "'", "\"", "?" }; return boost::make_iterator_range(patterns); } static boost::iterator_range< const char* const* > get_replacements() { static const char* const replacements[] = { "\\\\", "\\a", "\\b", "\\f", "\\n", "\\r", "\\t", "\\v", "\\'", "\\\"", "\\?" }; return boost::make_iterator_range(replacements); } template< unsigned int N > static std::size_t print_escaped(char (&buf)[N], char c) { int n = boost::log::aux::snprintf(buf, N, "\\x%0.2X", static_cast< unsigned int >(static_cast< uint8_t >(c))); if (n < 0) { n = 0; buf[0] = '\0'; } return static_cast< unsigned int >(n) >= N ? N - 1 : static_cast< unsigned int >(n); } }; #endif // BOOST_LOG_USE_CHAR #ifdef BOOST_LOG_USE_WCHAR_T template< > struct c_decorator_traits< wchar_t > { static boost::iterator_range< const wchar_t* const* > get_patterns() { static const wchar_t* const patterns[] = { L"\\", L"\a", L"\b", L"\f", L"\n", L"\r", L"\t", L"\v", L"'", L"\"", L"?" }; return boost::make_iterator_range(patterns); } static boost::iterator_range< const wchar_t* const* > get_replacements() { static const wchar_t* const replacements[] = { L"\\\\", L"\\a", L"\\b", L"\\f", L"\\n", L"\\r", L"\\t", L"\\v", L"\\'", L"\\\"", L"\\?" }; return boost::make_iterator_range(replacements); } template< unsigned int N > static std::size_t print_escaped(wchar_t (&buf)[N], wchar_t c) { const wchar_t* format; unsigned int val; if (sizeof(wchar_t) == 1) { format = L"\\x%0.2X"; val = static_cast< uint8_t >(c); } else if (sizeof(wchar_t) == 2) { format = L"\\x%0.4X"; val = static_cast< uint16_t >(c); } else { format = L"\\x%0.8X"; val = static_cast< uint32_t >(c); } int n = boost::log::aux::swprintf(buf, N, format, val); if (n < 0) { n = 0; buf[0] = L'\0'; } return static_cast< unsigned int >(n) >= N ? N - 1 : static_cast< unsigned int >(n); } }; #endif // BOOST_LOG_USE_WCHAR_T template< typename CharT > struct c_decorator_gen { typedef CharT char_type; template< typename SubactorT > BOOST_FORCEINLINE char_decorator_actor< SubactorT, pattern_replacer< char_type > > operator[] (SubactorT const& subactor) const { typedef c_decorator_traits< char_type > traits_type; typedef pattern_replacer< char_type > replacer_type; typedef char_decorator_actor< SubactorT, replacer_type > result_type; typedef typename result_type::terminal_type terminal_type; typename result_type::base_type act = {{ terminal_type(subactor, replacer_type(traits_type::get_patterns(), traits_type::get_replacements())) }}; return result_type(act); } }; } // namespace aux /*! * C-style decorator generator object. The decorator replaces characters with specific meaning in C * language with the corresponding escape sequences. The generator provides <tt>operator[]</tt> that * can be used to construct the actual decorator. For example: * * <code> * c_decor[ attr< std::string >("MyAttr") ] * </code> * * For wide-character formatting there is the similar \c wc_decor decorator generator object. */ #ifdef BOOST_LOG_USE_CHAR const aux::c_decorator_gen< char > c_decor = {}; #endif #ifdef BOOST_LOG_USE_WCHAR_T const aux::c_decorator_gen< wchar_t > wc_decor = {}; #endif /*! * The function creates a C-style decorator generator for arbitrary character type. */ template< typename CharT > BOOST_FORCEINLINE aux::c_decorator_gen< CharT > make_c_decor() { return aux::c_decorator_gen< CharT >(); } /*! * A character decorator implementation that escapes all non-prontable and non-ASCII characters * in the output with C-style escape sequences. */ template< typename CharT > class c_ascii_pattern_replacer : public pattern_replacer< CharT > { private: //! Base type typedef pattern_replacer< CharT > base_type; public: //! Result type typedef typename base_type::result_type result_type; //! Character type typedef typename base_type::char_type char_type; //! String type typedef typename base_type::string_type string_type; private: //! Traits type typedef aux::c_decorator_traits< char_type > traits_type; public: //! Default constructor c_ascii_pattern_replacer() : base_type(traits_type::get_patterns(), traits_type::get_replacements()) { } //! Applies string replacements starting from the specified position result_type operator() (string_type& str, typename string_type::size_type start_pos = 0) const { base_type::operator() (str, start_pos); typedef typename string_type::iterator string_iterator; for (string_iterator it = str.begin() + start_pos, end = str.end(); it != end; ++it) { char_type c = *it; if (c < 0x20 || c > 0x7e) { char_type buf[(std::numeric_limits< char_type >::digits + 3) / 4 + 3]; std::size_t n = traits_type::print_escaped(buf, c); std::size_t pos = it - str.begin(); str.replace(pos, 1, buf, n); it = str.begin() + n - 1; end = str.end(); } } } }; namespace aux { template< typename CharT > struct c_ascii_decorator_gen { typedef CharT char_type; template< typename SubactorT > BOOST_FORCEINLINE char_decorator_actor< SubactorT, c_ascii_pattern_replacer< char_type > > operator[] (SubactorT const& subactor) const { typedef c_decorator_traits< char_type > traits_type; typedef c_ascii_pattern_replacer< char_type > replacer_type; typedef char_decorator_actor< SubactorT, replacer_type > result_type; typedef typename result_type::terminal_type terminal_type; typename result_type::base_type act = {{ terminal_type(subactor, replacer_type()) }}; return result_type(act); } }; } // namespace aux /*! * C-style decorator generator object. Acts similarly to \c c_decor, except that \c c_ascii_decor also * converts all non-ASCII and non-printable ASCII characters, except for space character, into * C-style hexadecimal escape sequences. The generator provides <tt>operator[]</tt> that * can be used to construct the actual decorator. For example: * * <code> * c_ascii_decor[ attr< std::string >("MyAttr") ] * </code> * * For wide-character formatting there is the similar \c wc_ascii_decor decorator generator object. */ #ifdef BOOST_LOG_USE_CHAR const aux::c_ascii_decorator_gen< char > c_ascii_decor = {}; #endif #ifdef BOOST_LOG_USE_WCHAR_T const aux::c_ascii_decorator_gen< wchar_t > wc_ascii_decor = {}; #endif /*! * The function creates a C-style decorator generator for arbitrary character type. */ template< typename CharT > BOOST_FORCEINLINE aux::c_ascii_decorator_gen< CharT > make_c_ascii_decor() { return aux::c_ascii_decorator_gen< CharT >(); } } // namespace expressions BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_EXPRESSIONS_FORMATTERS_C_DECORATOR_HPP_INCLUDED_ <commit_msg>Removed unused typedef.<commit_after>/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file formatters/c_decorator.hpp * \author Andrey Semashev * \date 18.11.2012 * * The header contains implementation of C-style character decorators. */ #ifndef BOOST_LOG_EXPRESSIONS_FORMATTERS_C_DECORATOR_HPP_INCLUDED_ #define BOOST_LOG_EXPRESSIONS_FORMATTERS_C_DECORATOR_HPP_INCLUDED_ #include <limits> #include <boost/range/iterator_range_core.hpp> #include <boost/log/detail/config.hpp> #include <boost/log/detail/snprintf.hpp> #include <boost/log/expressions/formatters/char_decorator.hpp> #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace expressions { namespace aux { template< typename > struct c_decorator_traits; #ifdef BOOST_LOG_USE_CHAR template< > struct c_decorator_traits< char > { static boost::iterator_range< const char* const* > get_patterns() { static const char* const patterns[] = { "\\", "\a", "\b", "\f", "\n", "\r", "\t", "\v", "'", "\"", "?" }; return boost::make_iterator_range(patterns); } static boost::iterator_range< const char* const* > get_replacements() { static const char* const replacements[] = { "\\\\", "\\a", "\\b", "\\f", "\\n", "\\r", "\\t", "\\v", "\\'", "\\\"", "\\?" }; return boost::make_iterator_range(replacements); } template< unsigned int N > static std::size_t print_escaped(char (&buf)[N], char c) { int n = boost::log::aux::snprintf(buf, N, "\\x%0.2X", static_cast< unsigned int >(static_cast< uint8_t >(c))); if (n < 0) { n = 0; buf[0] = '\0'; } return static_cast< unsigned int >(n) >= N ? N - 1 : static_cast< unsigned int >(n); } }; #endif // BOOST_LOG_USE_CHAR #ifdef BOOST_LOG_USE_WCHAR_T template< > struct c_decorator_traits< wchar_t > { static boost::iterator_range< const wchar_t* const* > get_patterns() { static const wchar_t* const patterns[] = { L"\\", L"\a", L"\b", L"\f", L"\n", L"\r", L"\t", L"\v", L"'", L"\"", L"?" }; return boost::make_iterator_range(patterns); } static boost::iterator_range< const wchar_t* const* > get_replacements() { static const wchar_t* const replacements[] = { L"\\\\", L"\\a", L"\\b", L"\\f", L"\\n", L"\\r", L"\\t", L"\\v", L"\\'", L"\\\"", L"\\?" }; return boost::make_iterator_range(replacements); } template< unsigned int N > static std::size_t print_escaped(wchar_t (&buf)[N], wchar_t c) { const wchar_t* format; unsigned int val; if (sizeof(wchar_t) == 1) { format = L"\\x%0.2X"; val = static_cast< uint8_t >(c); } else if (sizeof(wchar_t) == 2) { format = L"\\x%0.4X"; val = static_cast< uint16_t >(c); } else { format = L"\\x%0.8X"; val = static_cast< uint32_t >(c); } int n = boost::log::aux::swprintf(buf, N, format, val); if (n < 0) { n = 0; buf[0] = L'\0'; } return static_cast< unsigned int >(n) >= N ? N - 1 : static_cast< unsigned int >(n); } }; #endif // BOOST_LOG_USE_WCHAR_T template< typename CharT > struct c_decorator_gen { typedef CharT char_type; template< typename SubactorT > BOOST_FORCEINLINE char_decorator_actor< SubactorT, pattern_replacer< char_type > > operator[] (SubactorT const& subactor) const { typedef c_decorator_traits< char_type > traits_type; typedef pattern_replacer< char_type > replacer_type; typedef char_decorator_actor< SubactorT, replacer_type > result_type; typedef typename result_type::terminal_type terminal_type; typename result_type::base_type act = {{ terminal_type(subactor, replacer_type(traits_type::get_patterns(), traits_type::get_replacements())) }}; return result_type(act); } }; } // namespace aux /*! * C-style decorator generator object. The decorator replaces characters with specific meaning in C * language with the corresponding escape sequences. The generator provides <tt>operator[]</tt> that * can be used to construct the actual decorator. For example: * * <code> * c_decor[ attr< std::string >("MyAttr") ] * </code> * * For wide-character formatting there is the similar \c wc_decor decorator generator object. */ #ifdef BOOST_LOG_USE_CHAR const aux::c_decorator_gen< char > c_decor = {}; #endif #ifdef BOOST_LOG_USE_WCHAR_T const aux::c_decorator_gen< wchar_t > wc_decor = {}; #endif /*! * The function creates a C-style decorator generator for arbitrary character type. */ template< typename CharT > BOOST_FORCEINLINE aux::c_decorator_gen< CharT > make_c_decor() { return aux::c_decorator_gen< CharT >(); } /*! * A character decorator implementation that escapes all non-prontable and non-ASCII characters * in the output with C-style escape sequences. */ template< typename CharT > class c_ascii_pattern_replacer : public pattern_replacer< CharT > { private: //! Base type typedef pattern_replacer< CharT > base_type; public: //! Result type typedef typename base_type::result_type result_type; //! Character type typedef typename base_type::char_type char_type; //! String type typedef typename base_type::string_type string_type; private: //! Traits type typedef aux::c_decorator_traits< char_type > traits_type; public: //! Default constructor c_ascii_pattern_replacer() : base_type(traits_type::get_patterns(), traits_type::get_replacements()) { } //! Applies string replacements starting from the specified position result_type operator() (string_type& str, typename string_type::size_type start_pos = 0) const { base_type::operator() (str, start_pos); typedef typename string_type::iterator string_iterator; for (string_iterator it = str.begin() + start_pos, end = str.end(); it != end; ++it) { char_type c = *it; if (c < 0x20 || c > 0x7e) { char_type buf[(std::numeric_limits< char_type >::digits + 3) / 4 + 3]; std::size_t n = traits_type::print_escaped(buf, c); std::size_t pos = it - str.begin(); str.replace(pos, 1, buf, n); it = str.begin() + n - 1; end = str.end(); } } } }; namespace aux { template< typename CharT > struct c_ascii_decorator_gen { typedef CharT char_type; template< typename SubactorT > BOOST_FORCEINLINE char_decorator_actor< SubactorT, c_ascii_pattern_replacer< char_type > > operator[] (SubactorT const& subactor) const { typedef c_ascii_pattern_replacer< char_type > replacer_type; typedef char_decorator_actor< SubactorT, replacer_type > result_type; typedef typename result_type::terminal_type terminal_type; typename result_type::base_type act = {{ terminal_type(subactor, replacer_type()) }}; return result_type(act); } }; } // namespace aux /*! * C-style decorator generator object. Acts similarly to \c c_decor, except that \c c_ascii_decor also * converts all non-ASCII and non-printable ASCII characters, except for space character, into * C-style hexadecimal escape sequences. The generator provides <tt>operator[]</tt> that * can be used to construct the actual decorator. For example: * * <code> * c_ascii_decor[ attr< std::string >("MyAttr") ] * </code> * * For wide-character formatting there is the similar \c wc_ascii_decor decorator generator object. */ #ifdef BOOST_LOG_USE_CHAR const aux::c_ascii_decorator_gen< char > c_ascii_decor = {}; #endif #ifdef BOOST_LOG_USE_WCHAR_T const aux::c_ascii_decorator_gen< wchar_t > wc_ascii_decor = {}; #endif /*! * The function creates a C-style decorator generator for arbitrary character type. */ template< typename CharT > BOOST_FORCEINLINE aux::c_ascii_decorator_gen< CharT > make_c_ascii_decor() { return aux::c_ascii_decorator_gen< CharT >(); } } // namespace expressions BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_EXPRESSIONS_FORMATTERS_C_DECORATOR_HPP_INCLUDED_ <|endoftext|>
<commit_before>#include "Animus.h" CAnimus::CAnimus(void) { } void CAnimus::Begin() { PersMem.Begin(); // loads data from EEPROM to RAM AnimusKeyboard.Begin(); // initialise keyboard module Comms.Begin(BAUD); // start comms Mod.Begin(); // initialise mods } void CAnimus::Loop() { MillisLoop(); // checks pseudoRTOS status // start of pseudo rtos code if (Async1MSDelay()) // should run once every 1 to 1.5ms { // layering checks in case of layout remapping if (Global.KeyLayer >= Global.LAY || Global.TempLayer >= Global.LAY) { Global.KeyLayer = 0; Global.TempLayer = 0; } KeyScan(); // physical key layers scanned // start of physical key loops for (byte i = 0; i < Global.ROW; i++) // this is placed inside the 1ms delay to slow it down a bit { for (byte j = 0; j < Global.COL; j++) { if (Global.KeyState[j][i] == HIGH) // if key is down { if (Global.KeyStateCoolDown[j][i] == 0) // if key was not recently released { PressCoords(j, i); Global.LayerState[j][i] = Global.TempLayer; PrePress(PersMem.GetKeyData(j, i, Global.TempLayer), PersMem.GetKeyType(j, i, Global.TempLayer)); PressKey(PersMem.GetKeyData(j, i, Global.TempLayer), PersMem.GetKeyType(j, i, Global.TempLayer)); Global.KeyStateCoolDown[j][i] = 255; } } else if (Global.KeyState[j][i] == LOW) // if key is up { if (Global.KeyStateCoolDown[j][i] == 255 - Global.KeyUpDelay) // if key was previously held down { ReleaseKey(PersMem.GetKeyData(j, i, Global.LayerState[j][i]), PersMem.GetKeyType(j, i, Global.LayerState[j][i])); Global.KeyStateCoolDown[j][i] = Global.KeyDownDelay; } } } } // end of physical key loops // start of countdowns for (byte i = 0; i < Global.ROW; i++) { for (byte j = 0; j < Global.COL; j++) { if (Global.KeyStateCoolDown[j][i] > 0 && Global.KeyStateCoolDown[j][i] != 255 - Global.KeyUpDelay) { Global.KeyStateCoolDown[j][i]--; } } } //end of countdowns } // end of pesudo rtos PersMem.Loop(); Mod.Loop(); Comms.Loop(); } void CAnimus::PressCoords(byte x, byte y) { Mod.PressCoords(x, y); } void CAnimus::PrePress(byte val, byte type) { Mod.PrePress(val, type); } void CAnimus::PressKey(byte val, byte type) { if (Global.HasUSB) { if (type == 0) // normal HID keystroke { AnimusKeyboard.Press(val); } else if (type == 1) // FN keys { Global.TempLayer = val; } else if (type == 2) // move main layer up or down or bitwise rotate the layer { if (val == 0) { SwitchLayer(true); } else if (val == 1) { SwitchLayer(false); } else { RotateLayer(val); } } else if (type == 3) // toggle layers { if (Global.TempLayer == val) { Global.TempLayer = Global.KeyLayer; } else { Global.TempLayer = val; } } } // for other key types, use a mod Mod.PressKey(val, type); } void CAnimus::ReleaseKey(byte val, byte type) { if (Global.HasUSB) { if (type == 0) { AnimusKeyboard.Release(val); } else if (type == 1) { Global.TempLayer = Global.KeyLayer; } } Mod.ReleaseKey(val, type); } void CAnimus::SwitchLayer(bool increment) { if (increment) // if true, go up a layer { Global.KeyLayer++; } else { Global.KeyLayer--; } if (Global.KeyLayer > 254) // rollover handling { Global.KeyLayer = Global.LAY -1; } else if (Global.KeyLayer >= Global.LAY) { Global.KeyLayer = 0; } } void CAnimus::RotateLayer(byte val) // bitwise layer shift { byte newLayer = Global.KeyLayer; byte mask = 1 << newLayer; if (!val) { /* No layers are allowed. Do nothing. */ return; } /* Find the next layer within the bitfield. Limit iterations to 10, to ensure no infinite loop. */ for (byte i = 0; i < 10; i++) { newLayer++; mask <<= 1; if ((! mask) || (newLayer >= Global.LAY)) { newLayer = 0; mask = 1; } if (val & mask) { /* newLayer is an allowed layer within the bitfield. */ break; } } Global.KeyLayer = newLayer; } void CAnimus::KeyScan() { for (int i = 0; i < Global.COL; i++) { pinMode(Global.HPins[i], OUTPUT); for (int j = 0; j < Global.ROW; j++) { byte val = digitalRead(Global.VPins[j]); Global.KeyState[i][j] = (val == LOW); } pinMode(Global.HPins[i], INPUT); } } void CAnimus::MillisLoop() { CurrentMillis = millis(); if(CurrentMillis - PreviousMillis >= 1) // this elapses every 1-1.5 ms { PreviousMillis = CurrentMillis; ReadyMillis = true; } else { ReadyMillis = false; } } bool CAnimus::Async1MSDelay() { return ReadyMillis; } CAnimus Animus; <commit_msg>added comment<commit_after>#include "Animus.h" CAnimus::CAnimus(void) { } void CAnimus::Begin() { PersMem.Begin(); // loads data from EEPROM to RAM AnimusKeyboard.Begin(); // initialise keyboard module Comms.Begin(BAUD); // start comms Mod.Begin(); // initialise mods } void CAnimus::Loop() { MillisLoop(); // checks pseudoRTOS status // start of pseudo rtos code if (Async1MSDelay()) // should run once every 1 to 1.5ms { // layering checks in case of layout remapping if (Global.KeyLayer >= Global.LAY || Global.TempLayer >= Global.LAY) { Global.KeyLayer = 0; Global.TempLayer = 0; } KeyScan(); // physical key layers scanned // start of physical key loops for (byte i = 0; i < Global.ROW; i++) // this is placed inside the 1ms delay to slow it down a bit { for (byte j = 0; j < Global.COL; j++) { if (Global.KeyState[j][i] == HIGH) // if key is down { if (Global.KeyStateCoolDown[j][i] == 0) // if key was not recently released { PressCoords(j, i); Global.LayerState[j][i] = Global.TempLayer; PrePress(PersMem.GetKeyData(j, i, Global.TempLayer), PersMem.GetKeyType(j, i, Global.TempLayer)); PressKey(PersMem.GetKeyData(j, i, Global.TempLayer), PersMem.GetKeyType(j, i, Global.TempLayer)); Global.KeyStateCoolDown[j][i] = 255; } } else if (Global.KeyState[j][i] == LOW) // if key is up { if (Global.KeyStateCoolDown[j][i] == 255 - Global.KeyUpDelay) // if key was previously held down AND is currently up after KeyUpDelay amount of time { ReleaseKey(PersMem.GetKeyData(j, i, Global.LayerState[j][i]), PersMem.GetKeyType(j, i, Global.LayerState[j][i])); Global.KeyStateCoolDown[j][i] = Global.KeyDownDelay; } } } } // end of physical key loops // start of countdowns for (byte i = 0; i < Global.ROW; i++) { for (byte j = 0; j < Global.COL; j++) { // what we did here saved 16 bits per key if (Global.KeyStateCoolDown[j][i] > 0 && Global.KeyStateCoolDown[j][i] != 255 - Global.KeyUpDelay) { Global.KeyStateCoolDown[j][i]--; // decrement KeyStateCoolDown if the key is being held down or if it was released, thus activating the keyup and keydown cooldowns } } } //end of countdowns } // end of pesudo rtos PersMem.Loop(); Mod.Loop(); Comms.Loop(); } void CAnimus::PressCoords(byte x, byte y) { Mod.PressCoords(x, y); } void CAnimus::PrePress(byte val, byte type) { Mod.PrePress(val, type); } void CAnimus::PressKey(byte val, byte type) { if (Global.HasUSB) { if (type == 0) // normal HID keystroke { AnimusKeyboard.Press(val); } else if (type == 1) // FN keys { Global.TempLayer = val; } else if (type == 2) // move main layer up or down or bitwise rotate the layer { if (val == 0) { SwitchLayer(true); } else if (val == 1) { SwitchLayer(false); } else { RotateLayer(val); } } else if (type == 3) // toggle layers { if (Global.TempLayer == val) { Global.TempLayer = Global.KeyLayer; } else { Global.TempLayer = val; } } } // for other key types, use a mod Mod.PressKey(val, type); } void CAnimus::ReleaseKey(byte val, byte type) { if (Global.HasUSB) { if (type == 0) { AnimusKeyboard.Release(val); } else if (type == 1) { Global.TempLayer = Global.KeyLayer; } } Mod.ReleaseKey(val, type); } void CAnimus::SwitchLayer(bool increment) { if (increment) // if true, go up a layer { Global.KeyLayer++; } else { Global.KeyLayer--; } if (Global.KeyLayer > 254) // rollover handling { Global.KeyLayer = Global.LAY -1; } else if (Global.KeyLayer >= Global.LAY) { Global.KeyLayer = 0; } } void CAnimus::RotateLayer(byte val) // bitwise layer shift { byte newLayer = Global.KeyLayer; byte mask = 1 << newLayer; if (!val) { /* No layers are allowed. Do nothing. */ return; } /* Find the next layer within the bitfield. Limit iterations to 10, to ensure no infinite loop. */ for (byte i = 0; i < 10; i++) { newLayer++; mask <<= 1; if ((! mask) || (newLayer >= Global.LAY)) { newLayer = 0; mask = 1; } if (val & mask) { /* newLayer is an allowed layer within the bitfield. */ break; } } Global.KeyLayer = newLayer; } void CAnimus::KeyScan() { for (int i = 0; i < Global.COL; i++) { pinMode(Global.HPins[i], OUTPUT); for (int j = 0; j < Global.ROW; j++) { byte val = digitalRead(Global.VPins[j]); Global.KeyState[i][j] = (val == LOW); } pinMode(Global.HPins[i], INPUT); } } void CAnimus::MillisLoop() { CurrentMillis = millis(); if(CurrentMillis - PreviousMillis >= 1) // this elapses every 1-1.5 ms { PreviousMillis = CurrentMillis; ReadyMillis = true; } else { ReadyMillis = false; } } bool CAnimus::Async1MSDelay() { return ReadyMillis; } CAnimus Animus; <|endoftext|>
<commit_before>/*========================================================================= Library: IntersonArray Copyright Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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 <Windows.h> // Sleep #include "itkImageFileWriter.h" #include "IntersonArrayCxxControlsHWControls.h" #include "IntersonArrayCxxImagingContainer.h" #include "AcquireIntersonArrayBModeCLP.h" typedef IntersonArrayCxx::Imaging::Container ContainerType; const unsigned int Dimension = 3; typedef ContainerType::PixelType PixelType; typedef itk::Image< PixelType, Dimension > ImageType; struct CallbackClientData { ImageType * Image; itk::SizeValueType FrameIndex; }; void __stdcall pasteIntoImage( PixelType * buffer, void * clientData ) { CallbackClientData * callbackClientData = static_cast< CallbackClientData * >( clientData ); ImageType * image = callbackClientData->Image; const ImageType::RegionType & largestRegion = image->GetLargestPossibleRegion(); const ImageType::SizeType imageSize = largestRegion.GetSize(); const itk::SizeValueType imageFrames = imageSize[2]; if( callbackClientData->FrameIndex >= imageFrames ) { return; } const int framePixels = imageSize[0] * imageSize[1]; PixelType * imageBuffer = image->GetPixelContainer()->GetBufferPointer(); imageBuffer += framePixels * callbackClientData->FrameIndex; std::memcpy( imageBuffer, buffer, framePixels * sizeof( PixelType ) ); std::cout << "Acquired frame: " << callbackClientData->FrameIndex << std::endl; ++(callbackClientData->FrameIndex); } int main( int argc, char * argv[] ) { PARSE_ARGS; typedef IntersonArrayCxx::Controls::HWControls HWControlsType; HWControlsType hwControls; const int steering = 0; typedef HWControlsType::FoundProbesType FoundProbesType; FoundProbesType foundProbes; hwControls.FindAllProbes( foundProbes ); if( foundProbes.empty() ) { std::cerr << "Could not find the probe." << std::endl; return EXIT_FAILURE; } hwControls.FindMyProbe( 0 ); const unsigned int probeId = hwControls.GetProbeID(); if( probeId == 0 ) { std::cerr << "Could not find the probe." << std::endl; return EXIT_FAILURE; } HWControlsType::FrequenciesType frequencies; hwControls.GetFrequency( frequencies ); if( !hwControls.SetFrequencyAndFocus( frequencyIndex, focusIndex, steering ) ) { std::cerr << "Could not set the frequency." << std::endl; return EXIT_FAILURE; } if( !hwControls.SendHighVoltage( highVoltage, highVoltage ) ) { std::cerr << "Could not set the high voltage." << std::endl; return EXIT_FAILURE; } if( !hwControls.EnableHighVoltage() ) { std::cerr << "Could not enable high voltage." << std::endl; return EXIT_FAILURE; } if( !hwControls.SendDynamic( gain ) ) { std::cerr << "Could not set dynamic gain." << std::endl; } hwControls.DisableHardButton(); ContainerType container; container.SetRFData( false ); const int height = hwControls.GetLinesPerArray(); const int width = container.MAX_SAMPLES; const int depth = 100; const int depthCfm = 50; if( hwControls.ValidDepth( depth ) == depth ) { ContainerType::ScanConverterError converterErrorIdle = container.IdleInitScanConverter( depth, width, height, probeId, steering, depthCfm, false, false, 0, false ); ContainerType::ScanConverterError converterError = container.HardInitScanConverter( depth, width, height, steering, depthCfm ); if( converterError != ContainerType::SUCCESS ) { std::cerr << "Error during hard scan converter initialization: " << converterError << std::endl; return EXIT_FAILURE; } } else { std::cerr << "Invalid requested depth for probe." << std::endl; } const int scanWidth = container.GetWidthScan(); const int scanHeight = container.GetHeightScan(); std::cout << "Width = " << width << std::endl; std::cout << "Height = " << height << std::endl; std::cout << "ScanWidth = " << scanWidth << std::endl; std::cout << "ScanHeight = " << scanHeight << std::endl; std::cout << "MM per Pixel = " << container.GetMmPerPixel() << std::endl; std::cout << "Depth: " << depth << "mm" << std::endl; const itk::SizeValueType framesToCollect = frames; ImageType::Pointer image = ImageType::New(); typedef ImageType::RegionType RegionType; RegionType imageRegion; ImageType::IndexType imageIndex; imageIndex.Fill( 0 ); imageRegion.SetIndex( imageIndex ); ImageType::SizeType imageSize; imageSize[0] = width; imageSize[1] = height; imageSize[2] = framesToCollect; imageRegion.SetSize( imageSize ); image->SetRegions( imageRegion ); ImageType::SpacingType imageSpacing; imageSpacing[ 0 ] = container.GetMmPerPixel(); imageSpacing[ 1 ] = 38.0 / (height - 1); imageSpacing[ 2 ] = 1; image->SetSpacing( imageSpacing ); image->Allocate(); CallbackClientData clientData; clientData.Image = image.GetPointer(); clientData.FrameIndex = 0; container.SetNewImageCallback( &pasteIntoImage, &clientData ); container.StartReadScan(); Sleep( 100 ); // "time to start" if( !hwControls.StartBmode() ) { std::cerr << "Could not start B-mode collection." << std::endl; return EXIT_FAILURE; }; int c = 0; while( clientData.FrameIndex < framesToCollect && c < 100 ) { std::cout << clientData.FrameIndex << " of " << framesToCollect << std::endl; std::cout << c << " of 100" << std::endl; Sleep( 100 ); ++c; } hwControls.StopAcquisition(); container.StopReadScan(); Sleep( 100 ); // "time to stop" typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputImage ); writer->SetInput( image ); try { writer->Update(); } catch( itk::ExceptionObject & error ) { std::cerr << "Error: " << error << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>BUG: Add correct Direction and Axial spacing for AcquireIntersonArrayBMode<commit_after>/*========================================================================= Library: IntersonArray Copyright Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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 <Windows.h> // Sleep #include "itkImageFileWriter.h" #include "IntersonArrayCxxControlsHWControls.h" #include "IntersonArrayCxxImagingContainer.h" #include "AcquireIntersonArrayBModeCLP.h" typedef IntersonArrayCxx::Imaging::Container ContainerType; const unsigned int Dimension = 3; typedef ContainerType::PixelType PixelType; typedef itk::Image< PixelType, Dimension > ImageType; struct CallbackClientData { ImageType * Image; itk::SizeValueType FrameIndex; }; void __stdcall pasteIntoImage( PixelType * buffer, void * clientData ) { CallbackClientData * callbackClientData = static_cast< CallbackClientData * >( clientData ); ImageType * image = callbackClientData->Image; const ImageType::RegionType & largestRegion = image->GetLargestPossibleRegion(); const ImageType::SizeType imageSize = largestRegion.GetSize(); const itk::SizeValueType imageFrames = imageSize[2]; if( callbackClientData->FrameIndex >= imageFrames ) { return; } const int framePixels = imageSize[0] * imageSize[1]; PixelType * imageBuffer = image->GetPixelContainer()->GetBufferPointer(); imageBuffer += framePixels * callbackClientData->FrameIndex; std::memcpy( imageBuffer, buffer, framePixels * sizeof( PixelType ) ); std::cout << "Acquired frame: " << callbackClientData->FrameIndex << std::endl; ++(callbackClientData->FrameIndex); } int main( int argc, char * argv[] ) { PARSE_ARGS; typedef IntersonArrayCxx::Controls::HWControls HWControlsType; HWControlsType hwControls; const int steering = 0; typedef HWControlsType::FoundProbesType FoundProbesType; FoundProbesType foundProbes; hwControls.FindAllProbes( foundProbes ); if( foundProbes.empty() ) { std::cerr << "Could not find the probe." << std::endl; return EXIT_FAILURE; } hwControls.FindMyProbe( 0 ); const unsigned int probeId = hwControls.GetProbeID(); if( probeId == 0 ) { std::cerr << "Could not find the probe." << std::endl; return EXIT_FAILURE; } HWControlsType::FrequenciesType frequencies; hwControls.GetFrequency( frequencies ); if( !hwControls.SetFrequencyAndFocus( frequencyIndex, focusIndex, steering ) ) { std::cerr << "Could not set the frequency." << std::endl; return EXIT_FAILURE; } if( !hwControls.SendHighVoltage( highVoltage, highVoltage ) ) { std::cerr << "Could not set the high voltage." << std::endl; return EXIT_FAILURE; } if( !hwControls.EnableHighVoltage() ) { std::cerr << "Could not enable high voltage." << std::endl; return EXIT_FAILURE; } if( !hwControls.SendDynamic( gain ) ) { std::cerr << "Could not set dynamic gain." << std::endl; } hwControls.DisableHardButton(); ContainerType container; container.SetRFData( false ); const int height = hwControls.GetLinesPerArray(); const int width = container.MAX_SAMPLES; const int depth = 100; const int depthCfm = 50; if( hwControls.ValidDepth( depth ) == depth ) { ContainerType::ScanConverterError converterErrorIdle = container.IdleInitScanConverter( depth, width, height, probeId, steering, depthCfm, false, false, 0, false ); ContainerType::ScanConverterError converterError = container.HardInitScanConverter( depth, width, height, steering, depthCfm ); if( converterError != ContainerType::SUCCESS ) { std::cerr << "Error during hard scan converter initialization: " << converterError << std::endl; return EXIT_FAILURE; } } else { std::cerr << "Invalid requested depth for probe." << std::endl; } const int scanWidth = container.GetWidthScan(); const int scanHeight = container.GetHeightScan(); std::cout << "Width = " << width << std::endl; std::cout << "Height = " << height << std::endl; std::cout << "ScanWidth = " << scanWidth << std::endl; std::cout << "ScanHeight = " << scanHeight << std::endl; std::cout << "MM per Pixel = " << container.GetMmPerPixel() << std::endl; std::cout << "Depth: " << depth << "mm" << std::endl; const itk::SizeValueType framesToCollect = frames; ImageType::Pointer image = ImageType::New(); typedef ImageType::RegionType RegionType; RegionType imageRegion; ImageType::IndexType imageIndex; imageIndex.Fill( 0 ); imageRegion.SetIndex( imageIndex ); ImageType::SizeType imageSize; imageSize[0] = width; imageSize[1] = height; imageSize[2] = framesToCollect; imageRegion.SetSize( imageSize ); image->SetRegions( imageRegion ); ImageType::SpacingType imageSpacing; imageSpacing[ 0 ] = container.GetMmPerPixel() / 10.; imageSpacing[ 1 ] = 38.0 / (height - 1); imageSpacing[ 2 ] = 1; image->SetSpacing( imageSpacing ); ImageType::DirectionType direction; direction.SetIdentity(); ImageType::DirectionType::InternalMatrixType & vnlDirection = direction.GetVnlMatrix(); vnlDirection.put(0, 0, 0.0); vnlDirection.put(0, 1, -1.0); vnlDirection.put(1, 0, 1.0); vnlDirection.put(1, 1, 0.0); image->SetDirection( direction ); image->Allocate(); CallbackClientData clientData; clientData.Image = image.GetPointer(); clientData.FrameIndex = 0; container.SetNewImageCallback( &pasteIntoImage, &clientData ); container.StartReadScan(); Sleep( 100 ); // "time to start" if( !hwControls.StartBmode() ) { std::cerr << "Could not start B-mode collection." << std::endl; return EXIT_FAILURE; }; int c = 0; while( clientData.FrameIndex < framesToCollect && c < 100 ) { std::cout << clientData.FrameIndex << " of " << framesToCollect << std::endl; std::cout << c << " of 100" << std::endl; Sleep( 100 ); ++c; } hwControls.StopAcquisition(); container.StopReadScan(); Sleep( 100 ); // "time to stop" typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputImage ); writer->SetInput( image ); try { writer->Update(); } catch( itk::ExceptionObject & error ) { std::cerr << "Error: " << error << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Author: Valeri Fine 21/01/2002 /**************************************************************************** ** $Id$ ** ** Copyright (C) 2002 by Valeri Fine. Brookhaven National Laboratory. ** All rights reserved. ** ** This file may be distributed under the terms of the Q Public License ** as defined by Trolltech AS of Norway and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** *****************************************************************************/ ///////////////////////////////////////////////////////////////////////////////// // // TQtPadFont class is Qt QFont class with TAttText ROOT class interface // ///////////////////////////////////////////////////////////////////////////////// #include "TQtPadFont.h" #include "TSystem.h" #include "TMath.h" #include <QFontMetrics> #include <QDebug> TString TQtPadFont::fgRomanFontName = "Times New Roman"; TString TQtPadFont::fgArialFontName = "Arial"; TString TQtPadFont::fgCourierFontName = "Courier New"; TString TQtPadFont::fgSymbolFontFamily= "Symbol"; //______________________________________________________________________________ static float CalibrateFont() { // Use the ROOT font with ID=1 to calibrate the current font on fly; // Environment variable ROOTFONTFACTOR allows to set the factor manually static float fontCalibFactor = -1; if (fontCalibFactor < 0 ) { const char * envFactor = gSystem->Getenv("ROOTFONTFACTOR"); bool ok=false; if (envFactor && envFactor[0]) fontCalibFactor= QString(envFactor).toFloat(&ok); if (!ok) { TQtPadFont pattern; pattern.SetTextFont(62); int w,h; QFontMetrics metrics(pattern); w = metrics.width("This is a PX distribution"); h = metrics.height(); // X11 returns h = 12 // XFT returns h = 14 // WIN32 TTF returns h = 16 // Nimbus Roman returns h = 18 // Qt4 XFT h = 21 #if 0 qDebug() << " Font metric w = " << w <<" h = "<< h << "points=" << pattern.pointSize() << "pixels=" << pattern.pixelSize() << pattern; #endif float f; switch (h) { case 12: f = 1.10; break;// it was f = 1.13 :-(; case 14: f = 0.915; break;// it was f = 0.94 :-(; case 16: f = 0.965; break;// to be tested yet case 18: f = 0.92; break;// to be tested yet case 20: f = 0.99; break;// to be tested yet case 21: f = 0.90; break;// to be tested yet default: f = 1.10; break; } fontCalibFactor = f; } } return fontCalibFactor; } //______________________________________________________________________________ static inline float FontMagicFactor(float size) { // Adjust the font size to match that for Postscipt format static float calibration =0; if (calibration == 0) calibration = CalibrateFont(); return TMath::Max(calibration*size,Float_t(1.0)); } //______________________________________________________________________________ TQtPadFont::TQtPadFont(): TAttText() {fTextFont = -1;fTextSize = -1; } //______________________________________________________________________________ void TQtPadFont::SetTextFont(const char *fontname, int italic_, int bold_) { //*-* mode : Option message //*-* italic : Italic attribut of the TTF font //*-* bold : Weight attribute of the TTF font //*-* fontname : the name of True Type Font (TTF) to draw text. //*-* //*-* Set text font to specified name. This function returns 0 if //*-* the specified font is found, 1 if not. this->setWeight((long) bold_*10); this->setItalic((Bool_t)italic_); this->setFamily(fontname); #if QT_VERSION >= 0x40000 if (!strcmp(fontname,RomanFontName())) { this->setStyleHint(QFont::Serif); } else if (!strcmp(fontname,ArialFontName())) { this->setStyleHint(QFont::SansSerif); } else if (!strcmp(fontname,CourierFontName())){ this->setStyleHint(QFont::TypeWriter); } this->setStyleStrategy(QFont::PreferDevice); #if 0 qDebug() << "TQtPadFont::SetTextFont:" << fontname << this->lastResortFamily () << this->lastResortFont () << this->substitute (fontname) << "ROOT font number=" << fTextFont; #endif #endif #if 0 qDebug() << "TGQt::SetTextFont font:" << fontname << " bold=" << bold_ << " italic="<< italic_; #endif } //______________________________________________________________________________ void TQtPadFont::SetTextFont(Font_t fontnumber) { //*-*-*-*-*-*-*-*-*-*-*-*-*Set current text font number*-*-*-*-*-*-*-*-*-*-*-* //*-* =========================== //*-* List of the currently supported fonts (screen and PostScript) //*-* ============================================================= //*-* Font ID X11 Win32 TTF lfItalic lfWeight x 10 //*-* 1 : times-medium-i-normal "Times New Roman" 1 5 //*-* 2 : times-bold-r-normal "Times New Roman" 0 8 //*-* 3 : times-bold-i-normal "Times New Roman" 1 8 //*-* 4 : helvetica-medium-r-normal "Arial" 0 5 //*-* 5 : helvetica-medium-o-normal "Arial" 1 5 //*-* 6 : helvetica-bold-r-normal "Arial" 0 8 //*-* 7 : helvetica-bold-o-normal "Arial" 1 8 //*-* 8 : courier-medium-r-normal "Courier New" 0 5 //*-* 9 : courier-medium-o-normal "Courier New" 1 5 //*-* 10 : courier-bold-r-normal "Courier New" 0 8 //*-* 11 : courier-bold-o-normal "Courier New" 1 8 //*-* 12 : symbol-medium-r-normal "Symbol" 0 6 //*-* 13 : times-medium-r-normal "Times New Roman" 0 5 //*-* 14 : "Wingdings" 0 5 if ( (fTextFont == fontnumber) || (fontnumber <0) ) return; TAttText::SetTextFont(fontnumber); int it, bld; const char *fontName = RomanFontName(); switch(fTextFont/10) { case 1: it = 1; bld = 5; fontName = RomanFontName(); break; case 2: it = 0; bld = 8; fontName = RomanFontName(); break; case 3: it = 1; bld = 8; fontName = RomanFontName(); break; case 4: it = 0; bld = 5; fontName = ArialFontName(); break; case 5: it = 1; bld = 5; fontName = ArialFontName(); break; case 6: it = 0; bld = 8; fontName = ArialFontName(); break; case 7: it = 1; bld = 8; fontName = ArialFontName(); break; case 8: it = 0; bld = 5; fontName = CourierFontName(); break; case 9: it = 1; bld = 5; fontName = CourierFontName(); break; case 10: it = 0; bld = 8; fontName = CourierFontName(); break; case 11: it = 1; bld = 8; fontName = CourierFontName(); break; case 12: it = 0; bld = 5; fontName = SymbolFontFamily(); break; case 13: it = 0; bld = 5; fontName = RomanFontName(); break; case 14: it = 0; bld = 5; fontName = "Wingdings"; break; default: it = 0; bld = 5; fontName = RomanFontName(); break; } SetTextFont(fontName, it, bld); } //______________________________________________________________________________ void TQtPadFont::SetTextSize(Float_t textsize) { //*-*-*-*-*-*-*-*-*-*-*-*-*Set current text size*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================== if ( fTextSize != textsize ) { TAttText::SetTextSize(textsize); if (fTextSize > 0) { Int_t tsize =(Int_t)( textsize+0.5); SetTextSizePixels(int(FontMagicFactor(tsize))); } } } //______________________________________________________________________________ void TQtPadFont::SetTextSizePixels(Int_t npixels) { // Set the text pixel size TAttText::SetTextSizePixels(npixels); if (npixels <=0) npixels=1; this->setPixelSize(npixels); } //______________________________________________________________________________ const char *TQtPadFont::RomanFontName() { // Get the system name for the "Roman" font return fgRomanFontName; } //______________________________________________________________________________ const char *TQtPadFont::ArialFontName() { // Get the system name for the "Arial" font return fgArialFontName; } //______________________________________________________________________________ const char *TQtPadFont::CourierFontName() { // Get the system name for the "Courier" font return fgCourierFontName; } //______________________________________________________________________________ const char *TQtPadFont::SymbolFontFamily() { // Get the system name for the "Symbol" font return fgSymbolFontFamily; } //______________________________________________________________________________ void TQtPadFont::SetSymbolFontFamily(const char *symbolFnName) { // Set the system name for the "Symbol" font fgSymbolFontFamily = symbolFnName; // we need the TString here !!! } //______________________________________________________________________________ void TQtPadFont::SetTextMagnify(Float_t mgn) { // // Scale the font accroding the inout mgn magnification factor // mgn : magnification factor // ------- // see: TVirtualX::DrawText(int x, int y, float angle, float mgn, const char *text, TVirtualX::ETextMode /*mode*/) // Int_t tsize = (Int_t)(fTextSize+0.5); if (TMath::Abs(mgn-1) >0.05) { int pxSize = mgn*FontMagicFactor(tsize); if(pxSize<=0) pxSize=1; this->setPixelSize(pxSize); } } <commit_msg>Fix a compilation warning<commit_after>// Author: Valeri Fine 21/01/2002 /**************************************************************************** ** $Id$ ** ** Copyright (C) 2002 by Valeri Fine. Brookhaven National Laboratory. ** All rights reserved. ** ** This file may be distributed under the terms of the Q Public License ** as defined by Trolltech AS of Norway and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** *****************************************************************************/ ///////////////////////////////////////////////////////////////////////////////// // // TQtPadFont class is Qt QFont class with TAttText ROOT class interface // ///////////////////////////////////////////////////////////////////////////////// #include "TQtPadFont.h" #include "TSystem.h" #include "TMath.h" #include <QFontMetrics> #include <QDebug> TString TQtPadFont::fgRomanFontName = "Times New Roman"; TString TQtPadFont::fgArialFontName = "Arial"; TString TQtPadFont::fgCourierFontName = "Courier New"; TString TQtPadFont::fgSymbolFontFamily= "Symbol"; //______________________________________________________________________________ static float CalibrateFont() { // Use the ROOT font with ID=1 to calibrate the current font on fly; // Environment variable ROOTFONTFACTOR allows to set the factor manually static float fontCalibFactor = -1; if (fontCalibFactor < 0 ) { const char * envFactor = gSystem->Getenv("ROOTFONTFACTOR"); bool ok=false; if (envFactor && envFactor[0]) fontCalibFactor= QString(envFactor).toFloat(&ok); if (!ok) { TQtPadFont pattern; pattern.SetTextFont(62); int w,h; QFontMetrics metrics(pattern); w = metrics.width("This is a PX distribution"); h = metrics.height(); // X11 returns h = 12 // XFT returns h = 14 // WIN32 TTF returns h = 16 // Nimbus Roman returns h = 18 // Qt4 XFT h = 21 #if 0 qDebug() << " Font metric w = " << w <<" h = "<< h << "points=" << pattern.pointSize() << "pixels=" << pattern.pixelSize() << pattern; #endif float f; switch (h) { case 12: f = 1.10; break;// it was f = 1.13 :-(; case 14: f = 0.915; break;// it was f = 0.94 :-(; case 16: f = 0.965; break;// to be tested yet case 18: f = 0.92; break;// to be tested yet case 20: f = 0.99; break;// to be tested yet case 21: f = 0.90; break;// to be tested yet default: f = 1.10; break; } fontCalibFactor = f; } } return fontCalibFactor; } //______________________________________________________________________________ static inline float FontMagicFactor(float size) { // Adjust the font size to match that for Postscipt format static float calibration =0; if (calibration == 0) calibration = CalibrateFont(); return TMath::Max(calibration*size,Float_t(1.0)); } //______________________________________________________________________________ TQtPadFont::TQtPadFont(): TAttText() {fTextFont = -1;fTextSize = -1; } //______________________________________________________________________________ void TQtPadFont::SetTextFont(const char *fontname, int italic_, int bold_) { //*-* mode : Option message //*-* italic : Italic attribut of the TTF font //*-* bold : Weight attribute of the TTF font //*-* fontname : the name of True Type Font (TTF) to draw text. //*-* //*-* Set text font to specified name. This function returns 0 if //*-* the specified font is found, 1 if not. this->setWeight((long) bold_*10); this->setItalic((Bool_t)italic_); this->setFamily(fontname); #if QT_VERSION >= 0x40000 if (!strcmp(fontname,RomanFontName())) { this->setStyleHint(QFont::Serif); } else if (!strcmp(fontname,ArialFontName())) { this->setStyleHint(QFont::SansSerif); } else if (!strcmp(fontname,CourierFontName())){ this->setStyleHint(QFont::TypeWriter); } this->setStyleStrategy(QFont::PreferDevice); #if 0 qDebug() << "TQtPadFont::SetTextFont:" << fontname << this->lastResortFamily () << this->lastResortFont () << this->substitute (fontname) << "ROOT font number=" << fTextFont; #endif #endif #if 0 qDebug() << "TGQt::SetTextFont font:" << fontname << " bold=" << bold_ << " italic="<< italic_; #endif } //______________________________________________________________________________ void TQtPadFont::SetTextFont(Font_t fontnumber) { //*-*-*-*-*-*-*-*-*-*-*-*-*Set current text font number*-*-*-*-*-*-*-*-*-*-*-* //*-* =========================== //*-* List of the currently supported fonts (screen and PostScript) //*-* ============================================================= //*-* Font ID X11 Win32 TTF lfItalic lfWeight x 10 //*-* 1 : times-medium-i-normal "Times New Roman" 1 5 //*-* 2 : times-bold-r-normal "Times New Roman" 0 8 //*-* 3 : times-bold-i-normal "Times New Roman" 1 8 //*-* 4 : helvetica-medium-r-normal "Arial" 0 5 //*-* 5 : helvetica-medium-o-normal "Arial" 1 5 //*-* 6 : helvetica-bold-r-normal "Arial" 0 8 //*-* 7 : helvetica-bold-o-normal "Arial" 1 8 //*-* 8 : courier-medium-r-normal "Courier New" 0 5 //*-* 9 : courier-medium-o-normal "Courier New" 1 5 //*-* 10 : courier-bold-r-normal "Courier New" 0 8 //*-* 11 : courier-bold-o-normal "Courier New" 1 8 //*-* 12 : symbol-medium-r-normal "Symbol" 0 6 //*-* 13 : times-medium-r-normal "Times New Roman" 0 5 //*-* 14 : "Wingdings" 0 5 if ( (fTextFont == fontnumber) || (fontnumber <0) ) return; TAttText::SetTextFont(fontnumber); int it, bld; const char *fontName = RomanFontName(); switch(fTextFont/10) { case 1: it = 1; bld = 5; fontName = RomanFontName(); break; case 2: it = 0; bld = 8; fontName = RomanFontName(); break; case 3: it = 1; bld = 8; fontName = RomanFontName(); break; case 4: it = 0; bld = 5; fontName = ArialFontName(); break; case 5: it = 1; bld = 5; fontName = ArialFontName(); break; case 6: it = 0; bld = 8; fontName = ArialFontName(); break; case 7: it = 1; bld = 8; fontName = ArialFontName(); break; case 8: it = 0; bld = 5; fontName = CourierFontName(); break; case 9: it = 1; bld = 5; fontName = CourierFontName(); break; case 10: it = 0; bld = 8; fontName = CourierFontName(); break; case 11: it = 1; bld = 8; fontName = CourierFontName(); break; case 12: it = 0; bld = 5; fontName = SymbolFontFamily(); break; case 13: it = 0; bld = 5; fontName = RomanFontName(); break; case 14: it = 0; bld = 5; fontName = "Wingdings"; break; default: it = 0; bld = 5; fontName = RomanFontName(); break; } SetTextFont(fontName, it, bld); } //______________________________________________________________________________ void TQtPadFont::SetTextSize(Float_t textsize) { //*-*-*-*-*-*-*-*-*-*-*-*-*Set current text size*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================== if ( fTextSize != textsize ) { TAttText::SetTextSize(textsize); if (fTextSize > 0) { Int_t tsize =(Int_t)( textsize+0.5); SetTextSizePixels(int(FontMagicFactor(tsize))); } } } //______________________________________________________________________________ void TQtPadFont::SetTextSizePixels(Int_t npixels) { // Set the text pixel size TAttText::SetTextSizePixels(npixels); if (npixels <=0) npixels=1; this->setPixelSize(npixels); } //______________________________________________________________________________ const char *TQtPadFont::RomanFontName() { // Get the system name for the "Roman" font return fgRomanFontName; } //______________________________________________________________________________ const char *TQtPadFont::ArialFontName() { // Get the system name for the "Arial" font return fgArialFontName; } //______________________________________________________________________________ const char *TQtPadFont::CourierFontName() { // Get the system name for the "Courier" font return fgCourierFontName; } //______________________________________________________________________________ const char *TQtPadFont::SymbolFontFamily() { // Get the system name for the "Symbol" font return fgSymbolFontFamily; } //______________________________________________________________________________ void TQtPadFont::SetSymbolFontFamily(const char *symbolFnName) { // Set the system name for the "Symbol" font fgSymbolFontFamily = symbolFnName; // we need the TString here !!! } //______________________________________________________________________________ void TQtPadFont::SetTextMagnify(Float_t mgn) { // // Scale the font accroding the inout mgn magnification factor // mgn : magnification factor // ------- // see: TVirtualX::DrawText(int x, int y, float angle, float mgn, const char *text, TVirtualX::ETextMode /*mode*/) // Int_t tsize = (Int_t)(fTextSize+0.5); if (TMath::Abs(mgn-1) >0.05) { int pxSize = int(mgn*FontMagicFactor(tsize)); if(pxSize<=0) pxSize=1; this->setPixelSize(pxSize); } } <|endoftext|>